Initial commit

This commit is contained in:
Porawit Dongwang
2026-09-16 23:20:08 +07:00
commit 0041668dbb
32577 changed files with 3687927 additions and 0 deletions
@@ -0,0 +1,5 @@
CLEAR_ALERTS_PASSWORD=your_password_here
# Resource Alert Thresholds (Percentage)
ALERT_RAM_PERCENT=85
ALERT_DISK_PERCENT=85
@@ -0,0 +1,19 @@
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=soar
DB_USERNAME=root
DB_PASSWORD=
WAZUH_API_URL=https://127.0.0.1:55000
WAZUH_API_USER=wazuh-wui
WAZUH_API_PASSWORD=wazuh-wui
WAZUH_INDEXER_URL=https://127.0.0.1:9200
WAZUH_INDEXER_USER=admin
WAZUH_INDEXER_PASSWORD=admin
VIRUSTOTAL_API_KEY=your_api_key_here
# Cleanup Settings
ALERT_RETENTION_DAYS=90
APP_NAME="KSH SOAR"
@@ -0,0 +1,6 @@
<IfModule mod_rewrite.c>
RewriteEngine On
# ถ้าไม่ใช่ไฟล์หรือโฟลเดอร์ที่มีอยู่จริง ให้ส่งไปที่ public/index.php
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
@@ -0,0 +1,154 @@
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit();
}
// ตั้งค่าการเชื่อมต่อฐานข้อมูล MySQL
$host = "localhost";
$db_name = "it_asset";
$username = "root";
$password = "@Samui@10742";
try {
$conn = new PDO("mysql:host=$host;dbname=$db_name;charset=utf8", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $exception) {
echo json_encode(["error" => "เชื่อมต่อฐานข้อมูลไม่ได้: " . $exception->getMessage()]);
exit;
}
$method = $_SERVER['REQUEST_METHOD'];
// ดึงข้อมูล (GET)
if ($method === 'GET') {
try {
$stmt = $conn->prepare("SELECT * FROM assets ORDER BY last_seen DESC");
$stmt->execute();
$assets = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($assets);
} catch (PDOException $e) {
echo json_encode(["error" => "ดึงข้อมูลผิดพลาด: " . $e->getMessage()]);
}
exit;
}
// รับและอัปเดตข้อมูล (POST)
if ($method === 'POST') {
$data = json_decode(file_get_contents("php://input"));
if (!empty($data->hostname)) {
// เตรียมข้อมูล
$id = isset($data->id) ? $data->id : null;
$asset_tag = !empty($data->asset_tag) ? $data->asset_tag : null;
$hostname = $data->hostname;
$os_version = isset($data->os_version) ? $data->os_version : null;
$cpu_model = isset($data->cpu_model) ? $data->cpu_model : null;
$ram_gb = isset($data->ram_gb) ? $data->ram_gb : null;
$storage_gb = isset($data->storage_gb) ? $data->storage_gb : null;
$ip_address = isset($data->ip_address) ? $data->ip_address : null;
$mac_address = isset($data->mac_address) ? $data->mac_address : null;
$status = !empty($data->status) ? $data->status : 'Active';
$is_auto_updated = isset($data->is_auto_updated) ? $data->is_auto_updated : 1;
try {
if ($id) {
// อัปเดตข้อมูลทั้งหมดผ่าน ID (แก้ไขข้อผิดพลาดแล้ว)
$sql = "UPDATE assets SET
asset_tag = :asset_tag,
hostname = :hostname,
os_version = :os_version,
cpu_model = :cpu_model,
ram_gb = :ram_gb,
storage_gb = :storage_gb,
ip_address = :ip_address,
mac_address = :mac_address,
status = :status,
is_auto_updated = :is_auto_updated,
last_seen = NOW()
WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->execute([
':asset_tag' => $asset_tag,
':hostname' => $hostname,
':os_version' => $os_version,
':cpu_model' => $cpu_model,
':ram_gb' => $ram_gb,
':storage_gb' => $storage_gb,
':ip_address' => $ip_address,
':mac_address' => $mac_address,
':status' => $status,
':is_auto_updated' => $is_auto_updated,
':id' => $id
]);
} else {
// ตรวจสอบเครื่องที่มีอยู่แล้ว (กรณี Agent/เพิ่มใหม่)
$check = $conn->prepare("SELECT id FROM assets WHERE hostname = :hostname LIMIT 1");
$check->execute([':hostname' => $hostname]);
$exists = $check->fetch(PDO::FETCH_ASSOC);
if ($exists) {
$sql = "UPDATE assets SET
asset_tag = COALESCE(:asset_tag, asset_tag),
os_version = COALESCE(:os_version, os_version),
cpu_model = COALESCE(:cpu_model, cpu_model),
ram_gb = COALESCE(:ram_gb, ram_gb),
storage_gb = COALESCE(:storage_gb, storage_gb),
ip_address = COALESCE(:ip_address, ip_address),
mac_address = COALESCE(:mac_address, mac_address),
status = COALESCE(:status, status),
is_auto_updated = :is_auto_updated,
last_seen = NOW()
WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->execute([
':asset_tag' => $asset_tag,
':os_version' => $os_version,
':cpu_model' => $cpu_model,
':ram_gb' => $ram_gb,
':storage_gb' => $storage_gb,
':ip_address' => $ip_address,
':mac_address' => $mac_address,
':status' => $status,
':is_auto_updated' => $is_auto_updated,
':id' => $exists['id']
]);
} else {
$sql = "INSERT INTO assets (asset_tag, hostname, os_version, cpu_model, ram_gb, storage_gb, ip_address, mac_address, status, is_auto_updated)
VALUES (:asset_tag, :hostname, :os_version, :cpu_model, :ram_gb, :storage_gb, :ip_address, :mac_address, :status, :is_auto_updated)";
$stmt = $conn->prepare($sql);
$stmt->execute([
':asset_tag' => $asset_tag,
':hostname' => $hostname,
':os_version' => $os_version,
':cpu_model' => $cpu_model,
':ram_gb' => $ram_gb,
':storage_gb' => $storage_gb,
':ip_address' => $ip_address,
':mac_address' => $mac_address,
':status' => $status,
':is_auto_updated' => $is_auto_updated
]);
}
}
echo json_encode(["success" => true, "message" => "บันทึกข้อมูลสำเร็จ"]);
} catch (PDOException $e) {
if ($e->getCode() == 23000) {
echo json_encode(["error" => "รหัสทรัพย์สิน (Asset Tag) หรือ MAC Address นี้ถูกใช้ในระบบไปแล้ว"]);
} else {
echo json_encode(["error" => "เกิดข้อผิดพลาดที่ฐานข้อมูล: " . $e->getMessage()]);
}
}
} else {
echo json_encode(["error" => "ข้อมูลไม่ครบถ้วน กรุณาระบุชื่อเครื่อง"]);
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,8 @@
@echo off
color 0B
echo ===================================================
echo Auto Sysmon Configuration Updater for L7 Network
echo ===================================================
echo.
powershell -NoProfile -ExecutionPolicy Bypass -EncodedCommand JABFAHIAcgBvAHIAQQBjAHQAaQBvAG4AUAByAGUAZgBlAHIAZQBuAGMAZQAgAD0AIAAnAFMAdABvAHAAJwAKAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAiAFsAKgBdACAAUwBlAGEAcgBjAGgAaQBuAGcAIABmAG8AcgAgAFMAeQBzAG0AbwBuACAAUwBlAHIAdgBpAGMAZQAgAHAAYQB0AGgALgAuAC4AIgAKACQAcwB5AHMAbQBvAG4AUwB2AGMAIAA9ACAARwBlAHQALQBDAGkAbQBJAG4AcwB0AGEAbgBjAGUAIABXAGkAbgAzADIAXwBTAGUAcgB2AGkAYwBlACAALQBGAGkAbAB0AGUAcgAgACIATgBhAG0AZQAgAGwAaQBrAGUAIAAnAFMAeQBzAG0AbwBuACUAJwAiACAAfAAgAFMAZQBsAGUAYwB0AC0ATwBiAGoAZQBjAHQAIAAtAEYAaQByAHMAdAAgADEACgBpAGYAIAAoAC0AbgBvAHQAIAAkAHMAeQBzAG0AbwBuAFMAdgBjACkAIAB7ACAAVwByAGkAdABlAC0ASABvAHMAdAAgACIARQByAHIAbwByADoAIABTAHkAcwBtAG8AbgAgAHMAZQByAHYAaQBjAGUAIABpAHMAIABuAG8AdAAgAGkAbgBzAHQAYQBsAGwAZQBkACAAbwBuACAAdABoAGkAcwAgAG0AYQBjAGgAaQBuAGUAIQAiACAALQBGAG8AcgBlAGcAcgBvAHUAbgBkAEMAbwBsAG8AcgAgAFIAZQBkADsAIABTAHQAYQByAHQALQBTAGwAZQBlAHAAIAAtAHMAIAA1ADsAIABlAHgAaQB0ACAAMQAgAH0ACgAkAHMAeQBzAG0AbwBuAEUAeABlACAAPQAgACQAcwB5AHMAbQBvAG4AUwB2AGMALgBQAGEAdABoAE4AYQBtAGUAIAAtAHIAZQBwAGwAYQBjAGUAIAAnACIAJwAsACAAJwAnAAoAVwByAGkAdABlAC0ASABvAHMAdAAgACIAWwAqAF0AIABEAG8AdwBuAGwAbwBhAGQAaQBuAGcAIABsAGEAdABlAHMAdAAgAFMAdwBpAGYAdABPAG4AUwBlAGMAdQByAGkAdAB5ACAAYwBvAG4AZgBpAGcALgAuAC4AIgAKACQAeABtAGwAUABhAHQAaAAgAD0AIAAiACQAZQBuAHYAOgBUAEUATQBQAFwAcwB5AHMAbQBvAG4AXwBzAG8AYQByAC4AeABtAGwAIgAKAEkAbgB2AG8AawBlAC0AVwBlAGIAUgBlAHEAdQBlAHMAdAAgAC0AVQByAGkAIAAnAGgAdAB0AHAAcwA6AC8ALwByAGEAdwAuAGcAaQB0AGgAdQBiAHUAcwBlAHIAYwBvAG4AdABlAG4AdAAuAGMAbwBtAC8AUwB3AGkAZgB0AE8AbgBTAGUAYwB1AHIAaQB0AHkALwBzAHkAcwBtAG8AbgAtAGMAbwBuAGYAaQBnAC8AbQBhAHMAdABlAHIALwBzAHkAcwBtAG8AbgBjAG8AbgBmAGkAZwAtAGUAeABwAG8AcgB0AC4AeABtAGwAJwAgAC0ATwB1AHQARgBpAGwAZQAgACQAeABtAGwAUABhAHQAaAAKAFsAeABtAGwAXQAkAHgAbQBsACAAPQAgAEcAZQB0AC0AQwBvAG4AdABlAG4AdAAgACQAeABtAGwAUABhAHQAaAAKAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAiAFsAKgBdACAAUABhAHQAYwBoAGkAbgBnACAATgBlAHQAdwBvAHIAawAgACYAIABEAE4AUwAgAEwAbwBnAGcAaQBuAGcAIAByAHUAbABlAHMALgAuAC4AIgAKACQAeABtAGwALgBTAGUAbABlAGMAdABOAG8AZABlAHMAKAAnAC8ALwBSAHUAbABlAEcAcgBvAHUAcAAvAE4AZQB0AHcAbwByAGsAQwBvAG4AbgBlAGMAdAAnACkAIAB8ACAARgBvAHIARQBhAGMAaAAtAE8AYgBqAGUAYwB0ACAAewAgACQAXwAuAFAAYQByAGUAbgB0AE4AbwBkAGUALgBSAGUAbQBvAHYAZQBDAGgAaQBsAGQAKAAkAF8AKQAgAHwAIABPAHUAdAAtAE4AdQBsAGwAIAB9AAoAJAB4AG0AbAAuAFMAZQBsAGUAYwB0AE4AbwBkAGUAcwAoACcALwAvAFIAdQBsAGUARwByAG8AdQBwAC8ARABuAHMAUQB1AGUAcgB5ACcAKQAgAHwAIABGAG8AcgBFAGEAYwBoAC0ATwBiAGoAZQBjAHQAIAB7ACAAJABfAC4AUABhAHIAZQBuAHQATgBvAGQAZQAuAFIAZQBtAG8AdgBlAEMAaABpAGwAZAAoACQAXwApACAAfAAgAE8AdQB0AC0ATgB1AGwAbAAgAH0ACgAkAG4AZQB3AE4AZQB0ACAAPQAgACQAeABtAGwALgBDAHIAZQBhAHQAZQBFAGwAZQBtAGUAbgB0ACgAJwBOAGUAdAB3AG8AcgBrAEMAbwBuAG4AZQBjAHQAJwApAAoAJABuAGUAdwBOAGUAdAAuAFMAZQB0AEEAdAB0AHIAaQBiAHUAdABlACgAJwBvAG4AbQBhAHQAYwBoACcALAAgACcAZQB4AGMAbAB1AGQAZQAnACkACgAkAHgAbQBsAC4AUwBlAGwAZQBjAHQAUwBpAG4AZwBsAGUATgBvAGQAZQAoACcALwAvAEUAdgBlAG4AdABGAGkAbAB0AGUAcgBpAG4AZwAnACkALgBBAHAAcABlAG4AZABDAGgAaQBsAGQAKAAkAG4AZQB3AE4AZQB0ACkAIAB8ACAATwB1AHQALQBOAHUAbABsAAoAJABuAGUAdwBEAG4AcwAgAD0AIAAkAHgAbQBsAC4AQwByAGUAYQB0AGUARQBsAGUAbQBlAG4AdAAoACcARABuAHMAUQB1AGUAcgB5ACcAKQAKACQAbgBlAHcARABuAHMALgBTAGUAdABBAHQAdAByAGkAYgB1AHQAZQAoACcAbwBuAG0AYQB0AGMAaAAnACwAIAAnAGUAeABjAGwAdQBkAGUAJwApAAoAJAB4AG0AbAAuAFMAZQBsAGUAYwB0AFMAaQBuAGcAbABlAE4AbwBkAGUAKAAnAC8ALwBFAHYAZQBuAHQARgBpAGwAdABlAHIAaQBuAGcAJwApAC4AQQBwAHAAZQBuAGQAQwBoAGkAbABkACgAJABuAGUAdwBEAG4AcwApACAAfAAgAE8AdQB0AC0ATgB1AGwAbAAKACQAeABtAGwALgBTAGEAdgBlACgAJAB4AG0AbABQAGEAdABoACkACgBXAHIAaQB0AGUALQBIAG8AcwB0ACAAIgBbACoAXQAgAEEAcABwAGwAeQBpAG4AZwAgAGMAbwBuAGYAaQBnAHUAcgBhAHQAaQBvAG4AIAB0AG8AIABTAHkAcwBtAG8AbgAuAC4ALgAiAAoAJgAgACQAcwB5AHMAbQBvAG4ARQB4AGUAIAAtAGMAIAAkAHgAbQBsAFAAYQB0AGgACgBXAHIAaQB0AGUALQBIAG8AcwB0ACAAIgBbACoAXQAgAFUAcABkAGEAdABlACAAQwBvAG0AcABsAGUAdABlACEAIgAgAC0ARgBvAHIAZQBnAHIAbwB1AG4AZABDAG8AbABvAHIAIABHAHIAZQBlAG4ACgBTAHQAYQByAHQALQBTAGwAZQBlAHAAIAAtAHMAIAAzAA==
pause
@@ -0,0 +1,39 @@
@echo off
color 0B
echo ===================================================
echo Auto Sysmon Configuration Updater for L7 Network
echo ===================================================
echo.
set "PS_SCRIPT=%TEMP%\update_sysmon_script.ps1"
echo $ErrorActionPreference = 'Stop' > "%PS_SCRIPT%"
echo Write-Host "[*] Searching for Sysmon Service path..." >> "%PS_SCRIPT%"
echo $sysmonSvc = Get-CimInstance Win32_Service -Filter "Name like 'Sysmon%'" ^| Select-Object -First 1 >> "%PS_SCRIPT%"
echo if (-not $sysmonSvc) { Write-Host "Error: Sysmon service is not installed!" -ForegroundColor Red; exit 1 } >> "%PS_SCRIPT%"
echo $sysmonExe = $sysmonSvc.PathName -replace '\"', '' >> "%PS_SCRIPT%"
echo Write-Host "[*] Downloading latest SwiftOnSecurity config..." >> "%PS_SCRIPT%"
echo $xmlPath = "$env:TEMP\sysmon_soar.xml" >> "%PS_SCRIPT%"
echo Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/SwiftOnSecurity/sysmon-config/master/sysmonconfig-export.xml' -OutFile $xmlPath >> "%PS_SCRIPT%"
echo [xml]$xml = Get-Content $xmlPath >> "%PS_SCRIPT%"
echo Write-Host "[*] Patching Network & DNS Logging rules..." >> "%PS_SCRIPT%"
echo $xml.SelectNodes('//RuleGroup/NetworkConnect') ^| ForEach-Object { $_.ParentNode.RemoveChild($_) ^| Out-Null } >> "%PS_SCRIPT%"
echo $xml.SelectNodes('//RuleGroup/DnsQuery') ^| ForEach-Object { $_.ParentNode.RemoveChild($_) ^| Out-Null } >> "%PS_SCRIPT%"
echo $newNet = $xml.CreateElement('NetworkConnect') >> "%PS_SCRIPT%"
echo $newNet.SetAttribute('onmatch', 'exclude') >> "%PS_SCRIPT%"
echo $xml.SelectSingleNode('//EventFiltering').AppendChild($newNet) ^| Out-Null >> "%PS_SCRIPT%"
echo $newDns = $xml.CreateElement('DnsQuery') >> "%PS_SCRIPT%"
echo $newDns.SetAttribute('onmatch', 'exclude') >> "%PS_SCRIPT%"
echo $xml.SelectSingleNode('//EventFiltering').AppendChild($newDns) ^| Out-Null >> "%PS_SCRIPT%"
echo $xml.Save($xmlPath) >> "%PS_SCRIPT%"
echo Write-Host "[*] Applying configuration to Sysmon..." >> "%PS_SCRIPT%"
echo ^& $sysmonExe -c $xmlPath >> "%PS_SCRIPT%"
powershell -NoProfile -ExecutionPolicy Bypass -File "%PS_SCRIPT%"
echo.
del "%PS_SCRIPT%"
echo ===================================================
echo [*] Update Complete!
echo ===================================================
pause
@@ -0,0 +1,48 @@
@echo off
color 0B
echo ===================================================
echo Auto Sysmon Configuration Updater for L7 Network
echo ===================================================
echo.
set "PS_SCRIPT=%TEMP%\sysmon_updater.ps1"
echo $ErrorActionPreference = 'Stop' > "%PS_SCRIPT%"
echo Write-Host "[*] Searching for Sysmon Service..." >> "%PS_SCRIPT%"
echo $sysmonSvc = Get-CimInstance Win32_Service -Filter "Name like 'Sysmon%%'" >> "%PS_SCRIPT%"
echo if (-not $sysmonSvc) { Write-Host "Error: Sysmon service not found!" -ForegroundColor Red; exit 1 } >> "%PS_SCRIPT%"
echo $sysmonExe = $sysmonSvc[0].PathName -replace '\"', '' >> "%PS_SCRIPT%"
echo Write-Host "[*] Downloading SwiftOnSecurity config..." >> "%PS_SCRIPT%"
echo $xmlPath = "$env:TEMP\sysmon_soar.xml" >> "%PS_SCRIPT%"
echo Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/SwiftOnSecurity/sysmon-config/master/sysmonconfig-export.xml' -OutFile $xmlPath >> "%PS_SCRIPT%"
echo [xml]$xml = Get-Content $xmlPath >> "%PS_SCRIPT%"
echo Write-Host "[*] Patching Network and DNS Logging rules..." >> "%PS_SCRIPT%"
echo $netNodes = $xml.SelectNodes('//RuleGroup/NetworkConnect') >> "%PS_SCRIPT%"
echo foreach ($node in $netNodes) { $null = $node.ParentNode.RemoveChild($node) } >> "%PS_SCRIPT%"
echo $dnsNodes = $xml.SelectNodes('//RuleGroup/DnsQuery') >> "%PS_SCRIPT%"
echo foreach ($node in $dnsNodes) { $null = $node.ParentNode.RemoveChild($node) } >> "%PS_SCRIPT%"
echo $newNet = $xml.CreateElement('NetworkConnect') >> "%PS_SCRIPT%"
echo $newNet.SetAttribute('onmatch', 'exclude') >> "%PS_SCRIPT%"
echo $null = $xml.SelectSingleNode('//EventFiltering').AppendChild($newNet) >> "%PS_SCRIPT%"
echo $newDns = $xml.CreateElement('DnsQuery') >> "%PS_SCRIPT%"
echo $newDns.SetAttribute('onmatch', 'exclude') >> "%PS_SCRIPT%"
echo $null = $xml.SelectSingleNode('//EventFiltering').AppendChild($newDns) >> "%PS_SCRIPT%"
echo $xml.Save($xmlPath) >> "%PS_SCRIPT%"
echo Write-Host "[*] Applying configuration to Sysmon..." >> "%PS_SCRIPT%"
echo Start-Process -FilePath $sysmonExe -ArgumentList "-c `"$xmlPath`"" -Wait -NoNewWindow >> "%PS_SCRIPT%"
powershell -NoProfile -ExecutionPolicy Bypass -File "%PS_SCRIPT%"
echo.
del "%PS_SCRIPT%"
echo ===================================================
echo [*] Update Complete!
echo ===================================================
pause
@@ -0,0 +1 @@
JABFAHIAcgBvAHIAQQBjAHQAaQBvAG4AUAByAGUAZgBlAHIAZQBuAGMAZQAgAD0AIAAnAFMAdABvAHAAJwAKAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAiAFsAKgBdACAAUwBlAGEAcgBjAGgAaQBuAGcAIABmAG8AcgAgAFMAeQBzAG0AbwBuACAAUwBlAHIAdgBpAGMAZQAgAHAAYQB0AGgALgAuAC4AIgAKACQAcwB5AHMAbQBvAG4AUwB2AGMAIAA9ACAARwBlAHQALQBDAGkAbQBJAG4AcwB0AGEAbgBjAGUAIABXAGkAbgAzADIAXwBTAGUAcgB2AGkAYwBlACAALQBGAGkAbAB0AGUAcgAgACIATgBhAG0AZQAgAGwAaQBrAGUAIAAnAFMAeQBzAG0AbwBuACUAJwAiACAAfAAgAFMAZQBsAGUAYwB0AC0ATwBiAGoAZQBjAHQAIAAtAEYAaQByAHMAdAAgADEACgBpAGYAIAAoAC0AbgBvAHQAIAAkAHMAeQBzAG0AbwBuAFMAdgBjACkAIAB7ACAAVwByAGkAdABlAC0ASABvAHMAdAAgACIARQByAHIAbwByADoAIABTAHkAcwBtAG8AbgAgAHMAZQByAHYAaQBjAGUAIABpAHMAIABuAG8AdAAgAGkAbgBzAHQAYQBsAGwAZQBkACAAbwBuACAAdABoAGkAcwAgAG0AYQBjAGgAaQBuAGUAIQAiACAALQBGAG8AcgBlAGcAcgBvAHUAbgBkAEMAbwBsAG8AcgAgAFIAZQBkADsAIABlAHgAaQB0ACAAMQAgAH0ACgAkAHMAeQBzAG0AbwBuAEUAeABlACAAPQAgACQAcwB5AHMAbQBvAG4AUwB2AGMALgBQAGEAdABoAE4AYQBtAGUAIAAtAHIAZQBwAGwAYQBjAGUAIAAnACIAJwAsACAAJwAnAAoAVwByAGkAdABlAC0ASABvAHMAdAAgACIAWwAqAF0AIABGAG8AdQBuAGQAIABTAHkAcwBtAG8AbgAgAGEAdAAgACQAcwB5AHMAbQBvAG4ARQB4AGUAIgAKAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAiAFsAKgBdACAARABvAHcAbgBsAG8AYQBkAGkAbgBnACAAbABhAHQAZQBzAHQAIABTAHcAaQBmAHQATwBuAFMAZQBjAHUAcgBpAHQAeQAgAGMAbwBuAGYAaQBnAC4ALgAuACIACgAkAHgAbQBsAFAAYQB0AGgAIAA9ACAAIgAkAGUAbgB2ADoAVABFAE0AUABcAHMAeQBzAG0AbwBuAF8AcwBvAGEAcgAuAHgAbQBsACIACgBJAG4AdgBvAGsAZQAtAFcAZQBiAFIAZQBxAHUAZQBzAHQAIAAtAFUAcgBpACAAJwBoAHQAdABwAHMAOgAvAC8AcgBhAHcALgBnAGkAdABoAHUAYgB1AHMAZQByAGMAbwBuAHQAZQBuAHQALgBjAG8AbQAvAFMAdwBpAGYAdABPAG4AUwBlAGMAdQByAGkAdAB5AC8AcwB5AHMAbQBvAG4ALQBjAG8AbgBmAGkAZwAvAG0AYQBzAHQAZQByAC8AcwB5AHMAbQBvAG4AYwBvAG4AZgBpAGcALQBlAHgAcABvAHIAdAAuAHgAbQBsACcAIAAtAE8AdQB0AEYAaQBsAGUAIAAkAHgAbQBsAFAAYQB0AGgACgBbAHgAbQBsAF0AJAB4AG0AbAAgAD0AIABHAGUAdAAtAEMAbwBuAHQAZQBuAHQAIAAkAHgAbQBsAFAAYQB0AGgACgBXAHIAaQB0AGUALQBIAG8AcwB0ACAAIgBbACoAXQAgAFAAYQB0AGMAaABpAG4AZwAgAE4AZQB0AHcAbwByAGsAIAAmACAARABOAFMAIABMAG8AZwBnAGkAbgBnACAAcgB1AGwAZQBzAC4ALgAuACIACgAkAHgAbQBsAC4AUwBlAGwAZQBjAHQATgBvAGQAZQBzACgAJwAvAC8AUgB1AGwAZQBHAHIAbwB1AHAALwBOAGUAdAB3AG8AcgBrAEMAbwBuAG4AZQBjAHQAJwApACAAfAAgAEYAbwByAEUAYQBjAGgALQBPAGIAagBlAGMAdAAgAHsAIAAkAF8ALgBQAGEAcgBlAG4AdABOAG8AZABlAC4AUgBlAG0AbwB2AGUAQwBoAGkAbABkACgAJABfACkAIAB8ACAATwB1AHQALQBOAHUAbABsACAAfQAKACQAeABtAGwALgBTAGUAbABlAGMAdABOAG8AZABlAHMAKAAnAC8ALwBSAHUAbABlAEcAcgBvAHUAcAAvAEQAbgBzAFEAdQBlAHIAeQAnACkAIAB8ACAARgBvAHIARQBhAGMAaAAtAE8AYgBqAGUAYwB0ACAAewAgACQAXwAuAFAAYQByAGUAbgB0AE4AbwBkAGUALgBSAGUAbQBvAHYAZQBDAGgAaQBsAGQAKAAkAF8AKQAgAHwAIABPAHUAdAAtAE4AdQBsAGwAIAB9AAoAJABuAGUAdwBOAGUAdAAgAD0AIAAkAHgAbQBsAC4AQwByAGUAYQB0AGUARQBsAGUAbQBlAG4AdAAoACcATgBlAHQAdwBvAHIAawBDAG8AbgBuAGUAYwB0ACcAKQAKACQAbgBlAHcATgBlAHQALgBTAGUAdABBAHQAdAByAGkAYgB1AHQAZQAoACcAbwBuAG0AYQB0AGMAaAAnACwAIAAnAGUAeABjAGwAdQBkAGUAJwApAAoAJAB4AG0AbAAuAFMAZQBsAGUAYwB0AFMAaQBuAGcAbABlAE4AbwBkAGUAKAAnAC8ALwBFAHYAZQBuAHQARgBpAGwAdABlAHIAaQBuAGcAJwApAC4AQQBwAHAAZQBuAGQAQwBoAGkAbABkACgAJABuAGUAdwBOAGUAdAApACAAfAAgAE8AdQB0AC0ATgB1AGwAbAAKACQAbgBlAHcARABuAHMAIAA9ACAAJAB4AG0AbAAuAEMAcgBlAGEAdABlAEUAbABlAG0AZQBuAHQAKAAnAEQAbgBzAFEAdQBlAHIAeQAnACkACgAkAG4AZQB3AEQAbgBzAC4AUwBlAHQAQQB0AHQAcgBpAGIAdQB0AGUAKAAnAG8AbgBtAGEAdABjAGgAJwAsACAAJwBlAHgAYwBsAHUAZABlACcAKQAKACQAeABtAGwALgBTAGUAbABlAGMAdABTAGkAbgBnAGwAZQBOAG8AZABlACgAJwAvAC8ARQB2AGUAbgB0AEYAaQBsAHQAZQByAGkAbgBnACcAKQAuAEEAcABwAGUAbgBkAEMAaABpAGwAZAAoACQAbgBlAHcARABuAHMAKQAgAHwAIABPAHUAdAAtAE4AdQBsAGwACgAkAHgAbQBsAC4AUwBhAHYAZQAoACQAeABtAGwAUABhAHQAaAApAAoAVwByAGkAdABlAC0ASABvAHMAdAAgACIAWwAqAF0AIABBAHAAcABsAHkAaQBuAGcAIABjAG8AbgBmAGkAZwB1AHIAYQB0AGkAbwBuACAAdABvACAAUwB5AHMAbQBvAG4ALgAuAC4AIgAKAFMAdABhAHIAdAAtAFAAcgBvAGMAZQBzAHMAIAAtAEYAaQBsAGUAUABhAHQAaAAgACQAcwB5AHMAbQBvAG4ARQB4AGUAIAAtAEEAcgBnAHUAbQBlAG4AdABMAGkAcwB0ACAAIgAtAGMAIABgACIAJAB4AG0AbABQAGEAdABoAGAAIgAiACAALQBXAGEAaQB0ACAALQBOAG8ATgBlAHcAVwBpAG4AZABvAHcACgA=
@@ -0,0 +1,27 @@
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use Dotenv\Dotenv;
use App\Engine\PlaybookEvaluator;
echo "Starting SOAR Automation Worker...\n";
// Load environment variables
if (file_exists(__DIR__ . '/../.env')) {
$dotenv = Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->load();
}
$evaluator = new PlaybookEvaluator();
while (true) {
try {
$evaluator->evaluateUnprocessedAlerts();
} catch (Exception $e) {
echo "Error in worker loop: " . $e->getMessage() . "\n";
}
// Sleep for 5 seconds before checking for new alerts again
sleep(5);
}
@@ -0,0 +1,16 @@
{
"name": "porawit/soar-wazuh",
"description": "SOAR integration with Wazuh",
"type": "project",
"require": {
"guzzlehttp/guzzle": "^7.0",
"vlucas/phpdotenv": "^5.5",
"bramus/router": "~1.6",
"monolog/monolog": "^3.0"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,70 @@
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
role VARCHAR(20) DEFAULT 'analyst',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS cases (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
status ENUM('open', 'investigating', 'resolved', 'closed') DEFAULT 'open',
severity ENUM('low', 'medium', 'high', 'critical') DEFAULT 'low',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS alerts (
id INT AUTO_INCREMENT PRIMARY KEY,
wazuh_alert_id VARCHAR(100) NOT NULL,
rule_id INT NOT NULL,
rule_level INT NOT NULL,
description TEXT,
agent_id VARCHAR(50),
agent_name VARCHAR(100),
agent_ip VARCHAR(50),
full_log TEXT,
raw_data JSON,
case_id INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (case_id) REFERENCES cases(id) ON DELETE SET NULL
);
CREATE TABLE IF NOT EXISTS playbooks (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
description TEXT,
trigger_rule_id INT, -- If this rule ID triggers, run playbook
trigger_level INT, -- OR if alert level >= this, run playbook
is_active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS playbook_actions (
id INT AUTO_INCREMENT PRIMARY KEY,
playbook_id INT NOT NULL,
action_type VARCHAR(50) NOT NULL, -- e.g., 'wazuh_active_response', 'virustotal_scan', 'slack_notify'
action_params JSON, -- e.g., {"command": "firewall-drop", "target": "agent"}
sequence INT DEFAULT 1,
FOREIGN KEY (playbook_id) REFERENCES playbooks(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS action_logs (
id INT AUTO_INCREMENT PRIMARY KEY,
alert_id INT,
playbook_id INT,
action_id INT,
status ENUM('pending', 'success', 'failed') DEFAULT 'pending',
result_message TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (alert_id) REFERENCES alerts(id) ON DELETE CASCADE,
FOREIGN KEY (playbook_id) REFERENCES playbooks(id) ON DELETE SET NULL,
FOREIGN KEY (action_id) REFERENCES playbook_actions(id) ON DELETE SET NULL
);
CREATE TABLE IF NOT EXISTS ai_remediation_cache (
rule_id INT PRIMARY KEY,
recommendation TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
@@ -0,0 +1,28 @@
$script = @'
$ErrorActionPreference = 'Stop'
Write-Host "[*] Searching for Sysmon Service path..."
$sysmonSvc = Get-CimInstance Win32_Service -Filter "Name like 'Sysmon%'" | Select-Object -First 1
if (-not $sysmonSvc) { Write-Host "Error: Sysmon service is not installed on this machine!" -ForegroundColor Red; exit 1 }
$sysmonExe = $sysmonSvc.PathName -replace '"', ''
Write-Host "[*] Found Sysmon at $sysmonExe"
Write-Host "[*] Downloading latest SwiftOnSecurity config..."
$xmlPath = "$env:TEMP\sysmon_soar.xml"
Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/SwiftOnSecurity/sysmon-config/master/sysmonconfig-export.xml' -OutFile $xmlPath
[xml]$xml = Get-Content $xmlPath
Write-Host "[*] Patching Network & DNS Logging rules..."
$xml.SelectNodes('//RuleGroup/NetworkConnect') | ForEach-Object { $_.ParentNode.RemoveChild($_) | Out-Null }
$xml.SelectNodes('//RuleGroup/DnsQuery') | ForEach-Object { $_.ParentNode.RemoveChild($_) | Out-Null }
$newNet = $xml.CreateElement('NetworkConnect')
$newNet.SetAttribute('onmatch', 'exclude')
$xml.SelectSingleNode('//EventFiltering').AppendChild($newNet) | Out-Null
$newDns = $xml.CreateElement('DnsQuery')
$newDns.SetAttribute('onmatch', 'exclude')
$xml.SelectSingleNode('//EventFiltering').AppendChild($newDns) | Out-Null
$xml.Save($xmlPath)
Write-Host "[*] Applying configuration to Sysmon..."
Start-Process -FilePath $sysmonExe -ArgumentList "-c `"$xmlPath`"" -Wait -NoNewWindow
'@
$bytes = [System.Text.Encoding]::Unicode.GetBytes($script)
$b64 = [Convert]::ToBase64String($bytes)
$bat = "@echo off`ncolor 0B`npowershell -NoProfile -ExecutionPolicy Bypass -EncodedCommand $b64`npause"
Set-Content "auto_update_sysmon.bat" $bat
@@ -0,0 +1,6 @@
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
</IfModule>
@@ -0,0 +1,360 @@
<?php
// เปิดโชว์ Error ชั่วคราวเพื่อหาสาเหตุ 500
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../vendor/autoload.php';
use Bramus\Router\Router;
use Dotenv\Dotenv;
use App\Controllers\DashboardController;
use App\Controllers\WazuhWebhookController;
// Load environment variables
if (file_exists(__DIR__ . '/../.env')) {
$dotenv = Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->load();
}
require_once __DIR__ . '/../src/Engine/Language.php';
// Handle Language Switch
if (isset($_GET['lang'])) {
$lang = in_array($_GET['lang'], ['en', 'th']) ? $_GET['lang'] : 'en';
setcookie('lang', $lang, time() + (86400 * 365), "/");
$redirect = strtok($_SERVER["REQUEST_URI"], '?');
header("Location: " . $redirect);
exit;
}
// Initialize Router
$router = new Router();
// Set base path dynamically to support subfolders (e.g. /ksh_soar)
$basePath = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
$basePath = str_replace('/public', '', $basePath);
if ($basePath === '/') {
$basePath = '';
}
$router->setBasePath($basePath);
// API / Webhook Routes
$router->mount('/api', function() use ($router) {
$router->post('/webhook/wazuh', function() {
$controller = new WazuhWebhookController();
$controller->handle();
});
$router->mount('/agent', function() use ($router) {
$router->get('/specs', function() {
$controller = new \App\Controllers\AgentController();
$controller->getSpecs();
});
$router->get('/quick-details', function() {
$controller = new \App\Controllers\AgentController();
$controller->getEndpointQuickDetails();
});
$router->get('/network', function() {
$controller = new \App\Controllers\AgentController();
$controller->getNetworkInspector();
});
$router->get('/processes', function() {
$controller = new \App\Controllers\AgentController();
$controller->getProcesses();
});
$router->get('/all-metadata', function() {
$controller = new \App\Controllers\AgentController();
$controller->getAllAgentsMetadata();
});
});
$router->post('/test-notification', function() {
require_once __DIR__ . '/../src/Integrations/Notifier.php';
header('Content-Type: application/json');
$type = $_POST['type'] ?? '';
$msg = "🛠️ [Test Message] This is a test notification from KSH SOAR.";
$success = false;
if ($type === 'line') {
if (empty($_ENV['LINE_NOTIFY_TOKEN'])) {
echo json_encode(['status' => 'error', 'message' => 'LINE_NOTIFY_TOKEN is not set in .env']);
return;
}
$success = \App\Integrations\Notifier::sendLineNotify($msg);
} else if ($type === 'telegram') {
if (empty($_ENV['TELEGRAM_BOT_TOKEN']) || empty($_ENV['TELEGRAM_CHAT_ID'])) {
echo json_encode(['status' => 'error', 'message' => 'Telegram tokens are not set in .env']);
return;
}
$appName = $_ENV['APP_NAME'] ?? 'KSH SOAR';
$tgMsg = "🧪 <b>[{$appName}] MOCKUP SECURITY ALERT</b>\n";
$tgMsg .= "━━━━━━━━━━━━━━━━━━━━\n";
$tgMsg .= "⚠️ <b>Risk Level:</b> <code>12</code> (High)\n";
$tgMsg .= "🆔 <b>Rule ID:</b> <code>5716</code>\n";
$tgMsg .= "🖥 <b>Agent:</b> <code>WEB-SERVER-01</code>\n";
$tgMsg .= "🌐 <b>IP Address:</b> <code>192.168.1.100</code>\n";
$tgMsg .= "━━━━━━━━━━━━━━━━━━━━\n";
$tgMsg .= "📝 <b>Description:</b>\n<i>เข้าสู่ระบบล้มเหลวหลายครั้งติดต่อกัน (อาจมีการ Brute-force)</i>\n\n";
$tgMsg .= "📍 <b>Action Taken:</b>\n";
$tgMsg .= "✅ Auto-created Investigation Case <b>#105</b>\n";
$tgMsg .= "🤖 AI Remediation Analysis queued.\n\n";
$tgMsg .= "✅ <b>System Integration Test Successful!</b>";
$success = \App\Integrations\Notifier::sendTelegram($tgMsg);
} else {
echo json_encode(['status' => 'error', 'message' => 'Invalid type']);
return;
}
if ($success) {
echo json_encode(['status' => 'success', 'message' => ucfirst($type) . ' notification sent successfully!']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Failed to send notification. Please check your tokens.']);
}
});
$router->post('/clear-all-alerts', function() {
$controller = new DashboardController();
$controller->clearAllAlerts();
});
$router->post('/virustotal-check', function() {
header('Content-Type: application/json');
$type = $_POST['type'] ?? '';
$value = $_POST['value'] ?? '';
$apiKey = $_ENV['VIRUSTOTAL_API_KEY'] ?? '';
if (empty($apiKey)) {
echo json_encode(['status' => 'error', 'message' => 'VIRUSTOTAL_API_KEY is not configured in .env']);
return;
}
if (empty($value)) {
echo json_encode(['status' => 'error', 'message' => 'No value provided for scanning.']);
return;
}
$url = "";
if ($type === 'hash') {
$url = "https://www.virustotal.com/api/v3/files/" . urlencode($value);
} else if ($type === 'ip') {
$url = "https://www.virustotal.com/api/v3/ip_addresses/" . urlencode($value);
} else {
echo json_encode(['status' => 'error', 'message' => 'Invalid scan type.']);
return;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"x-apikey: {$apiKey}"
]);
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpcode == 200) {
$data = json_decode($response, true);
$stats = $data['data']['attributes']['last_analysis_stats'] ?? null;
if ($stats) {
$malicious = $stats['malicious'] ?? 0;
$suspicious = $stats['suspicious'] ?? 0;
$total = array_sum($stats);
$html = "<div class='text-sm mt-2'>";
if ($malicious > 0) {
$html .= "<div class='bg-rose-100 text-rose-800 px-3 py-2 rounded font-bold'><i class='fas fa-biohazard mr-2'></i> Malicious: {$malicious} / {$total} engines detected this as a threat!</div>";
} else if ($suspicious > 0) {
$html .= "<div class='bg-amber-100 text-amber-800 px-3 py-2 rounded font-bold'><i class='fas fa-exclamation-triangle mr-2'></i> Suspicious: {$suspicious} / {$total} engines flagged this.</div>";
} else {
$html .= "<div class='bg-emerald-100 text-emerald-800 px-3 py-2 rounded font-bold'><i class='fas fa-shield-alt mr-2'></i> Clean: 0 / {$total} engines detected threats.</div>";
}
$vtLink = $type === 'hash' ? "https://www.virustotal.com/gui/file/{$value}" : "https://www.virustotal.com/gui/ip-address/{$value}";
$html .= "<a href='{$vtLink}' target='_blank' class='block mt-2 text-xs text-blue-600 underline hover:text-blue-800'><i class='fas fa-external-link-alt mr-1'></i> View full report on VirusTotal</a>";
$html .= "</div>";
echo json_encode(['status' => 'success', 'html' => $html]);
} else {
echo json_encode(['status' => 'error', 'message' => 'Could not parse VirusTotal analysis stats.']);
}
} else if ($httpcode == 404) {
echo json_encode(['status' => 'success', 'html' => "<div class='bg-slate-100 text-slate-600 px-3 py-2 rounded text-sm mt-2'><i class='fas fa-search mr-2'></i> No match found on VirusTotal.</div>"]);
} else {
echo json_encode(['status' => 'error', 'message' => "VirusTotal API Error (HTTP {$httpcode})"]);
}
});
$router->post('/ai-remediation', function() {
header('Content-Type: application/json');
$ruleId = $_POST['rule_id'] ?? '';
$ruleDesc = $_POST['rule_desc'] ?? '';
$level = (int)($_POST['level'] ?? 0);
try {
$db = \App\Database\Connection::getInstance();
// Create cache table automatically if it doesn't exist
$db->query("CREATE TABLE IF NOT EXISTS ai_remediation_cache (
rule_id INT PRIMARY KEY,
recommendation TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");
$force = isset($_POST['force']) && $_POST['force'] == 'true';
// 1. Check cache first to save API calls
if (!$force) {
$stmt = $db->prepare("SELECT recommendation FROM ai_remediation_cache WHERE rule_id = ?");
$stmt->execute([$ruleId]);
$cachedHtml = $stmt->fetchColumn();
if ($cachedHtml) {
// Return cached response (you can add a small badge to indicate it's from cache if you want)
$cachedHtml .= "<div class='mt-2 text-[10px] text-indigo-400 text-right italic'><i class='fas fa-bolt mr-1'></i> Loaded from Cache</div>";
echo json_encode(['status' => 'success', 'html' => $cachedHtml]);
return;
}
}
// 2. Setup Gemini API request
$apiKey = $_ENV['GEMINI_API_KEY'] ?? '';
if (empty($apiKey)) {
echo json_encode(['status' => 'error', 'message' => 'GEMINI_API_KEY is not configured in .env file.']);
return;
}
$prompt = "You are a senior cybersecurity SOC analyst. Analyze the following Wazuh alert and provide a concise, actionable 3-step remediation guideline.
Rule ID: {$ruleId}
Level: {$level}
Description: {$ruleDesc}
Requirements:
- Answer in Thai language.
- Output ONLY valid HTML: an unordered list <ul> with 3 <li> items. Add 'list-disc pl-4 space-y-2 mt-1' class to the <ul>.
- Wrap keywords in <strong> tags.
- Do NOT wrap the output in markdown code blocks (no ```html).";
$url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=" . $apiKey;
$payload = [
"contents" => [
["parts" => [["text" => $prompt]]]
]
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Bypass local cert issues
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200 && $response) {
$data = json_decode($response, true);
$aiText = $data['candidates'][0]['content']['parts'][0]['text'] ?? '';
// Clean up possible markdown tags returned by the model
$aiText = str_replace(['```html', '```'], '', $aiText);
$html = "<div class='text-sm leading-relaxed text-indigo-900'>" . trim($aiText) . "</div>";
// 3. Save to database cache
$stmt = $db->prepare("INSERT INTO ai_remediation_cache (rule_id, recommendation) VALUES (?, ?) ON DUPLICATE KEY UPDATE recommendation = VALUES(recommendation)");
$stmt->execute([$ruleId, $html]);
echo json_encode(['status' => 'success', 'html' => $html]);
} else {
$errorMsg = 'Failed to reach Gemini API (HTTP ' . $httpCode . ')';
if ($response) {
$errData = json_decode($response, true);
if (isset($errData['error']['message'])) $errorMsg = $errData['error']['message'];
}
echo json_encode(['status' => 'error', 'message' => $errorMsg]);
}
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
}
});
$router->get('/dashboard/charts', function() {
$controller = new DashboardController();
$controller->getChartData();
});
$router->get('/realtime', function() {
$controller = new DashboardController();
$controller->getRealtimeUpdates();
});
});
// Web Routes
$router->get('/', function() {
$controller = new DashboardController();
$controller->index();
});
$router->get('/ai-history', function() {
$controller = new DashboardController();
$controller->aiHistory();
});
$router->get('/sysmon', function() {
$controller = new \App\Controllers\SysmonController();
$controller->index();
});
$router->post('/clear-alerts', function() {
$controller = new DashboardController();
$controller->clearOldAlerts();
});
$router->get('/search', function() {
$controller = new \App\Controllers\SearchController();
$controller->index();
});
$router->post('/api/search/ssp', function() {
$controller = new \App\Controllers\SearchController();
$controller->ssp();
});
$router->get('/settings', function() {
$controller = new DashboardController();
$controller->settings();
});
$router->get('/agents', function() {
$controller = new \App\Controllers\AgentController();
$controller->index();
});
$router->get('/api/agents/(\d+)/details', function($id) {
$controller = new \App\Controllers\AgentController();
$controller->getDetails($id);
});
$router->get('/api/agents/remote-list', function() {
$controller = new \App\Controllers\AgentController();
$controller->getRemoteList();
});
// 404 Handler
$router->set404(function() {
header('HTTP/1.1 404 Not Found');
echo "404 Not Found";
});
// Run Router
$router->run();
Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

@@ -0,0 +1,58 @@
<?php
// Let's create a quick test script to check what the Wazuh API returns for agents and syscollector
require_once __DIR__ . '/../vendor/autoload.php';
use Dotenv\Dotenv;
if (file_exists(__DIR__ . '/../.env')) {
$dotenv = Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->load();
}
$apiUrl = $_ENV['WAZUH_API_URL'] ?? 'https://127.0.0.1:55000';
$apiUser = $_ENV['WAZUH_API_USER'] ?? 'wazuh-wui';
$apiPass = $_ENV['WAZUH_API_PASSWORD'] ?? 'wazuh-wui';
// 1. Get Token
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl . '/security/user/authenticate');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$apiUser:$apiPass");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
die("Auth failed: $response");
}
$token = json_decode($response, true)['data']['token'] ?? null;
if (!$token) die("No token");
echo "Token: OK\n";
// 2. Get Agents
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl . '/agents?limit=2');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $token"]);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
curl_close($ch);
echo "Agents:\n" . substr($response, 0, 500) . "...\n";
// 3. Get Hardware
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl . '/syscollector/hardware'); // Does this work globally?
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $token"]);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
curl_close($ch);
echo "Hardware:\n" . substr($response, 0, 500) . "...\n";
@@ -0,0 +1,45 @@
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use Dotenv\Dotenv;
if (file_exists(__DIR__ . '/../.env')) {
$dotenv = Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->load();
}
$apiUrl = $_ENV['WAZUH_API_URL'] ?? 'https://127.0.0.1:55000';
$apiUser = $_ENV['WAZUH_API_USER'] ?? 'wazuh-wui';
$apiPass = $_ENV['WAZUH_API_PASSWORD'] ?? 'wazuh-wui';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl . '/security/user/authenticate');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$apiUser:$apiPass");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
$token = json_decode($response, true)['data']['token'] ?? null;
curl_close($ch);
if (!$token) die("No token");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl . '/syscollector/000/hardware');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $token"]);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$hwResponse = curl_exec($ch);
curl_close($ch);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl . '/syscollector/000/netif');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $token"]);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$netResponse = curl_exec($ch);
curl_close($ch);
echo "HW: " . substr($hwResponse, 0, 500) . "\n\n";
echo "NET: " . substr($netResponse, 0, 500) . "\n";
@@ -0,0 +1,22 @@
$ErrorActionPreference = 'Stop'
Write-Host "[*] Searching for Sysmon Service path..."
$sysmonSvc = Get-CimInstance Win32_Service -Filter "Name like 'Sysmon%'" | Select-Object -First 1
if (-not $sysmonSvc) { Write-Host "Error: Sysmon service is not installed on this machine!" -ForegroundColor Red; exit 1 }
$sysmonExe = $sysmonSvc.PathName -replace '"', ''
Write-Host "[*] Found Sysmon at $sysmonExe"
Write-Host "[*] Downloading latest SwiftOnSecurity config..."
$xmlPath = "$env:TEMP\sysmon_soar.xml"
Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/SwiftOnSecurity/sysmon-config/master/sysmonconfig-export.xml' -OutFile $xmlPath
[xml]$xml = Get-Content $xmlPath
Write-Host "[*] Patching Network & DNS Logging rules..."
$xml.SelectNodes('//RuleGroup/NetworkConnect') | ForEach-Object { $_.ParentNode.RemoveChild($_) | Out-Null }
$xml.SelectNodes('//RuleGroup/DnsQuery') | ForEach-Object { $_.ParentNode.RemoveChild($_) | Out-Null }
$newNet = $xml.CreateElement('NetworkConnect')
$newNet.SetAttribute('onmatch', 'exclude')
$xml.SelectSingleNode('//EventFiltering').AppendChild($newNet) | Out-Null
$newDns = $xml.CreateElement('DnsQuery')
$newDns.SetAttribute('onmatch', 'exclude')
$xml.SelectSingleNode('//EventFiltering').AppendChild($newDns) | Out-Null
$xml.Save($xmlPath)
Write-Host "[*] Applying configuration to Sysmon..."
Start-Process -FilePath $sysmonExe -ArgumentList "-c `"$xmlPath`"" -Wait -NoNewWindow
@@ -0,0 +1,514 @@
<?php
namespace App\Controllers;
use App\Database\Connection;
class AgentController
{
private function getBaseUrl()
{
$basePath = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
$basePath = str_replace('/public', '', $basePath);
return $basePath === '/' ? '' : $basePath;
}
private function getWazuhToken()
{
$apiUrl = $_ENV['WAZUH_API_URL'] ?? 'https://127.0.0.1:55000';
$apiUser = $_ENV['WAZUH_API_USER'] ?? 'wazuh-wui';
$apiPass = $_ENV['WAZUH_API_PASSWORD'] ?? 'wazuh-wui';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl . '/security/user/authenticate');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$apiUser:$apiPass");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200 && $response) {
$data = json_decode($response, true);
return $data['data']['token'] ?? null;
}
return null;
}
private function fetchFromWazuhApi($endpoint, $token)
{
$apiUrl = $_ENV['WAZUH_API_URL'] ?? 'https://127.0.0.1:55000';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl . $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $token"]);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
curl_close($ch);
return $response ? json_decode($response, true) : null;
}
public function index()
{
$baseUrl = $this->getBaseUrl();
$appName = $_ENV['APP_NAME'] ?? 'KSH SOAR';
$token = $this->getWazuhToken();
$agents = [];
$stats = [
'total' => 0,
'active' => 0,
'disconnected' => 0,
'never_connected' => 0
];
if ($token) {
$response = $this->fetchFromWazuhApi('/agents?select=id,name,ip,status,os.name,os.version,version,dateAdd,lastKeepAlive', $token);
if (isset($response['data']['affected_items'])) {
$agents = $response['data']['affected_items'];
foreach ($agents as $agent) {
$stats['total']++;
$status = strtolower($agent['status'] ?? '');
if ($status === 'active') {
$stats['active']++;
} elseif ($status === 'disconnected') {
$stats['disconnected']++;
} elseif ($status === 'never connected' || $status === 'never_connected') {
$stats['never_connected']++;
}
}
}
}
// Fetch real active Disk/RAM alerts from local DB (Last 24 hours, latest per agent)
$db = Connection::getInstance();
$query = "
SELECT a1.*
FROM alerts a1
INNER JOIN (
SELECT agent_name, MAX(id) as max_id
FROM alerts
WHERE (description LIKE '%disk space%'
OR description LIKE '%partition usage%'
OR description LIKE '%out of memory%'
OR description LIKE '%memory usage%')
AND created_at >= NOW() - INTERVAL 24 HOUR
GROUP BY agent_name
) a2 ON a1.id = a2.max_id
ORDER BY a1.id DESC
LIMIT 20
";
try {
$resourceAlerts = $db->query($query)->fetchAll();
} catch (\Exception $e) {
$resourceAlerts = [];
}
require_once __DIR__ . '/../../views/agents.php';
}
private function fetchCustomInventory($agentId, $location)
{
$indexerUrl = $_ENV['WAZUH_INDEXER_URL'] ?? 'https://127.0.0.1:9200';
$indexerUser = $_ENV['WAZUH_INDEXER_USER'] ?? 'admin';
$indexerPass = $_ENV['WAZUH_INDEXER_PASSWORD'] ?? 'admin';
$url = rtrim($indexerUrl, '/') . "/wazuh-alerts-*/_search";
$payload = json_encode([
'size' => 1,
'sort' => ['@timestamp' => 'desc'],
'query' => ['bool' => ['must' => [
['match' => ['agent.id' => $agentId]],
['match' => ['location' => $location]]
]]]
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_USERPWD, "$indexerUser:$indexerPass");
$response = curl_exec($ch);
curl_close($ch);
if ($response) {
$data = json_decode($response, true);
if (isset($data['hits']['hits'][0]['_source']['full_log'])) {
$log = $data['hits']['hits'][0]['_source']['full_log'];
$log = preg_replace('/^ossec: output: \'' . preg_quote($location, '/') . '\':\s*/', '', $log);
// ป้องกัน json_decode พังถ้ารูปแบบผิด
$json = json_decode($log, true);
return $json !== null ? $json : $log;
}
}
return null;
}
public function getRemoteList()
{
error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');
try {
$token = $this->getWazuhToken();
if (!$token) {
echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
return;
}
// Fetch all agents
$agentsResponse = $this->fetchFromWazuhApi('/agents?select=id,name,status&limit=10000', $token);
$agents = $agentsResponse['data']['affected_items'] ?? [];
// Bulk fetch from Indexer
$indexerUrl = $_ENV['WAZUH_INDEXER_URL'] ?? 'https://127.0.0.1:9200';
$indexerUser = $_ENV['WAZUH_INDEXER_USER'] ?? 'admin';
$indexerPass = $_ENV['WAZUH_INDEXER_PASSWORD'] ?? 'admin';
$url = rtrim($indexerUrl, '/') . "/wazuh-alerts-*/_search";
$payload = json_encode([
'size' => 10000,
'sort' => ['@timestamp' => 'desc'],
'query' => ['terms' => ['location' => ['teamviewer_inventory', 'anydesk_inventory']]],
'_source' => ['agent.id', 'location', 'full_log']
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_USERPWD, "$indexerUser:$indexerPass");
$response = curl_exec($ch);
curl_close($ch);
$metadata = [];
if ($response) {
$data = json_decode($response, true);
if (isset($data['hits']['hits'])) {
foreach ($data['hits']['hits'] as $hit) {
$src = $hit['_source'];
$aid = $src['agent']['id'] ?? '';
$loc = $src['location'] ?? '';
$log = $src['full_log'] ?? '';
if (!$aid) continue;
if (!isset($metadata[$aid])) {
$metadata[$aid] = ['tv' => null, 'ad' => null];
}
if ($loc === 'teamviewer_inventory' && $metadata[$aid]['tv'] === null) {
$log = preg_replace('/^ossec: output: \'teamviewer_inventory\':\s*/', '', $log);
$json = json_decode($log, true);
$metadata[$aid]['tv'] = ($json && isset($json['TeamViewerID']) && $json['TeamViewerID'] !== 'Not Found') ? $json['TeamViewerID'] : null;
}
if ($loc === 'anydesk_inventory' && $metadata[$aid]['ad'] === null) {
$log = preg_replace('/^ossec: output: \'anydesk_inventory\':\s*/', '', $log);
$json = json_decode($log, true);
$metadata[$aid]['ad'] = ($json && isset($json['AnyDeskID']) && $json['AnyDeskID'] !== 'Not Found') ? $json['AnyDeskID'] : null;
}
}
}
}
// Merge data
$results = [];
foreach ($agents as $ag) {
if ($ag['id'] === '000') continue; // Skip Wazuh server
$aid = $ag['id'];
$tv = $metadata[$aid]['tv'] ?? null;
$ad = $metadata[$aid]['ad'] ?? null;
// Prefer TeamViewer over AnyDesk if both exist
$remoteId = $tv ? $tv : ($ad ? $ad : '-');
$remoteType = $tv ? 'teamviewer' : ($ad ? 'anydesk' : null);
$results[] = [
'id' => $aid,
'name' => $ag['name'] ?? 'Unknown',
'status' => strtolower($ag['status'] ?? 'disconnected'),
'remote_id' => $remoteId,
'remote_type' => $remoteType
];
}
echo json_encode(['status' => 'success', 'data' => $results]);
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
} catch (\Error $e) {
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
}
public function getDetails($id)
{
header('Content-Type: application/json');
$token = $this->getWazuhToken();
if (!$token) {
echo json_encode(['status' => 'error', 'message' => 'Failed to authenticate with Wazuh API']);
return;
}
// Fetch syscollector hardware
$hwResponse = $this->fetchFromWazuhApi("/syscollector/$id/hardware", $token);
// Fetch syscollector network interfaces and addresses
$netIfaceResponse = $this->fetchFromWazuhApi("/syscollector/$id/netiface", $token);
$netAddrResponse = $this->fetchFromWazuhApi("/syscollector/$id/netaddr", $token);
// Fetch custom inventories from Indexer
$diskInfo = $this->fetchCustomInventory($id, 'disk_inventory');
$tvInfo = $this->fetchCustomInventory($id, 'teamviewer_inventory');
$adInfo = $this->fetchCustomInventory($id, 'anydesk_inventory');
echo json_encode([
'status' => 'success',
'hardware' => $hwResponse['data']['affected_items'] ?? [],
'netiface' => $netIfaceResponse['data']['affected_items'] ?? [],
'netaddr' => $netAddrResponse['data']['affected_items'] ?? [],
'disk_info' => $diskInfo,
'tv_info' => $tvInfo,
'ad_info' => $adInfo
]);
}
public function getEndpointQuickDetails()
{
header('Content-Type: application/json');
$token = $this->getWazuhToken();
if (!$token) {
echo json_encode(['status' => 'error', 'message' => 'Failed to authenticate with Wazuh API']);
return;
}
$agentId = $_GET['agent_id'] ?? '';
if (!$agentId) {
echo json_encode(['status' => 'error', 'message' => 'Missing agent_id parameter']);
return;
}
try {
$hwResponse = $this->fetchFromWazuhApi("/syscollector/{$agentId}/hardware", $token);
$packagesResponse = $this->fetchFromWazuhApi("/syscollector/{$agentId}/packages?limit=5000", $token);
$hotfixesResponse = $this->fetchFromWazuhApi("/syscollector/{$agentId}/hotfixes?limit=2000", $token);
// Fetch custom inventories from Indexer to match full dashboard needs
$diskInfo = $this->fetchCustomInventory($agentId, 'disk_inventory');
$tvInfo = $this->fetchCustomInventory($agentId, 'teamviewer_inventory');
$adInfo = $this->fetchCustomInventory($agentId, 'anydesk_inventory');
$modelInfo = $this->fetchCustomInventory($agentId, 'model_inventory');
$manufacturerInfo = $this->fetchCustomInventory($agentId, 'manufacturer_inventory');
echo json_encode([
'status' => 'success',
'hardware' => $hwResponse['data']['affected_items'][0] ?? null,
'packages' => $packagesResponse['data']['affected_items'] ?? [],
'hotfixes' => $hotfixesResponse['data']['affected_items'] ?? [],
'disk_info' => $diskInfo,
'tv_info' => $tvInfo,
'ad_info' => $adInfo,
'model_info' => $modelInfo,
'manufacturer_info' => $manufacturerInfo
]);
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
}
public function getNetworkInspector()
{
header('Content-Type: application/json');
$token = $this->getWazuhToken();
if (!$token) {
echo json_encode(['status' => 'error', 'message' => 'Failed to authenticate with Wazuh API']);
return;
}
$agentId = $_GET['agent_id'] ?? '';
if (!$agentId) {
echo json_encode(['status' => 'error', 'message' => 'Agent ID is required']);
return;
}
try {
// Fetch interfaces and open ports from Wazuh Syscollector
$netIfaceRaw = $this->fetchFromWazuhApi("/syscollector/$agentId/netiface", $token);
$netAddrRaw = $this->fetchFromWazuhApi("/syscollector/$agentId/netaddr", $token);
$portsResponse = $this->fetchFromWazuhApi("/syscollector/$agentId/ports?limit=50", $token);
$netiface = [];
$addresses = [];
// Group addresses by interface name
if (isset($netAddrRaw['data']['affected_items'])) {
foreach ($netAddrRaw['data']['affected_items'] as $addr) {
if (isset($addr['iface']) && isset($addr['address'])) {
// Only grab IPv4 format addresses (contains dot)
if (strpos($addr['address'], '.') !== false) {
$addresses[$addr['iface']][] = $addr['address'];
}
}
}
}
if (isset($netIfaceRaw['data']['affected_items'])) {
foreach ($netIfaceRaw['data']['affected_items'] as $iface) {
$name = $iface['name'] ?? 'Unknown';
// Skip loopback interfaces
if (strtolower($name) === 'lo' || strtolower($name) === 'loopback') continue;
$netiface[] = [
'name' => $name,
'mac' => $iface['mac'] ?? 'N/A',
'ipv4' => isset($addresses[$name]) ? implode(', ', $addresses[$name]) : 'N/A'
];
}
}
// Format ports
$ports = [];
if (isset($portsResponse['data']['affected_items'])) {
foreach ($portsResponse['data']['affected_items'] as $p) {
if (isset($p['state']) && strtolower($p['state']) === 'listening') {
$ports[] = [
'protocol' => $p['protocol'] ?? 'N/A',
'local_ip' => $p['local']['ip'] ?? 'N/A',
'local_port' => $p['local']['port'] ?? 'N/A',
'process' => $p['process'] ?? 'Unknown'
];
}
}
}
// Fetch Sysmon Network Connections (Event ID 3) from local DB (last 24h for charts, top 100 for table)
$db = \App\Database\Connection::getInstance();
$yesterday = date('Y-m-d H:i:s', strtotime('-24 hours'));
// Raw events for table (latest 100)
$stmt = $db->prepare("
SELECT raw_data, created_at, description
FROM alerts
WHERE agent_id = ?
AND (description LIKE '%Event 3%' OR description LIKE '%Event 22%')
ORDER BY created_at DESC
LIMIT 100
");
$stmt->execute([$agentId]);
$sysmonRaw = $stmt->fetchAll();
$sysmonEvents = [];
foreach ($sysmonRaw as $row) {
$raw = json_decode($row['raw_data'], true);
$eventData = $raw['data']['win']['eventdata'] ?? null;
$desc = $row['description'] ?? '';
if ($eventData) {
if (strpos($desc, 'Event 3') !== false) {
$sysmonEvents[] = [
'type' => 'network',
'timestamp' => $row['created_at'],
'protocol' => $eventData['protocol'] ?? 'TCP',
'process' => basename(str_replace('\\', '/', $eventData['image'] ?? $eventData['Image'] ?? 'Unknown')),
'full_path' => $eventData['image'] ?? $eventData['Image'] ?? 'Unknown',
'dst_ip' => $eventData['destinationIp'] ?? $eventData['DestinationIp'] ?? 'N/A',
'dst_port' => $eventData['destinationPort'] ?? $eventData['DestinationPort'] ?? 'N/A',
'payload' => 'Protocol: ' . ($eventData['protocol'] ?? $eventData['Protocol'] ?? 'TCP')
];
} elseif (strpos($desc, 'Event 22') !== false) {
$sysmonEvents[] = [
'type' => 'dns',
'timestamp' => $row['created_at'],
'protocol' => 'DNS',
'process' => basename(str_replace('\\', '/', $eventData['image'] ?? $eventData['Image'] ?? 'Unknown')),
'full_path' => $eventData['image'] ?? $eventData['Image'] ?? 'Unknown',
'dst_ip' => 'DNS Server',
'dst_port' => '53',
'payload' => 'Query: ' . ($eventData['queryName'] ?? $eventData['QueryName'] ?? 'Unknown')
];
}
}
}
// Total connections 24h
$stmtTotal = $db->prepare("SELECT COUNT(*) FROM alerts WHERE agent_id = ? AND (description LIKE '%Event 3%' OR description LIKE '%Event 22%') AND created_at >= ?");
$stmtTotal->execute([$agentId, $yesterday]);
$totalConnections = $stmtTotal->fetchColumn();
// Suspicious alerts (Level >= 7) 24h
$stmtSuspicious = $db->prepare("SELECT COUNT(*) FROM alerts WHERE agent_id = ? AND rule_level >= 7 AND created_at >= ?");
$stmtSuspicious->execute([$agentId, $yesterday]);
$suspiciousCount = $stmtSuspicious->fetchColumn();
// Timeline (Last 6 hours)
$sixHoursAgo = date('Y-m-d H:i:s', strtotime('-6 hours'));
$stmtTimeline = $db->prepare("
SELECT DATE_FORMAT(created_at, '%H:00') as hr, COUNT(*) as cnt
FROM alerts
WHERE agent_id = ?
AND (description LIKE '%Event 3%' OR description LIKE '%Event 22%')
AND created_at >= ?
GROUP BY hr
ORDER BY MIN(created_at) ASC
");
$stmtTimeline->execute([$agentId, $sixHoursAgo]);
$timeline = $stmtTimeline->fetchAll(\PDO::FETCH_ASSOC);
// Top Processes (Extract from JSON inside MySQL for last 24h)
// Since JSON extraction might be slow or complex, we will just parse the last 500 events in PHP to build the donut chart
$stmtTopProc = $db->prepare("
SELECT raw_data
FROM alerts
WHERE agent_id = ?
AND (description LIKE '%Event 3%' OR description LIKE '%Event 22%')
AND created_at >= ?
LIMIT 500
");
$stmtTopProc->execute([$agentId, $yesterday]);
$topProcRaw = $stmtTopProc->fetchAll();
$processCounts = [];
foreach ($topProcRaw as $row) {
$raw = json_decode($row['raw_data'], true);
$process = basename(str_replace('\\', '/', $raw['data']['win']['eventdata']['image'] ?? $raw['data']['win']['eventdata']['Image'] ?? 'Unknown'));
if (!isset($processCounts[$process])) $processCounts[$process] = 0;
$processCounts[$process]++;
}
arsort($processCounts);
$topProcesses = array_slice($processCounts, 0, 5);
echo json_encode([
'status' => 'success',
'netiface' => $netiface,
'ports' => $ports,
'sysmon' => $sysmonEvents,
'stats' => [
'open_ports' => count($ports),
'total_connections_24h' => $totalConnections,
'suspicious_alerts_24h' => $suspiciousCount
],
'timeline' => $timeline,
'top_processes' => $topProcesses
]);
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
}
}
@@ -0,0 +1,277 @@
<?php
namespace App\Controllers;
use App\Database\Connection;
use App\Engine\DataCleaner;
class DashboardController
{
private function getWazuhToken()
{
$apiUrl = $_ENV['WAZUH_API_URL'] ?? 'https://127.0.0.1:55000';
$apiUser = $_ENV['WAZUH_API_USER'] ?? 'wazuh-wui';
$apiPass = $_ENV['WAZUH_API_PASSWORD'] ?? 'wazuh-wui';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl . '/security/user/authenticate');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$apiUser:$apiPass");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200 && $response) {
$data = json_decode($response, true);
return $data['data']['token'] ?? null;
}
return null;
}
private function fetchFromWazuhApi($endpoint, $token)
{
$apiUrl = $_ENV['WAZUH_API_URL'] ?? 'https://127.0.0.1:55000';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl . $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $token"]);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
curl_close($ch);
return $response ? json_decode($response, true) : null;
}
private function getBaseUrl() {
$baseUrl = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
$baseUrl = str_replace('/public', '', $baseUrl);
if ($baseUrl === '/') $baseUrl = '';
return $baseUrl;
}
public function index()
{
$cleaner = new \App\Engine\DataCleaner();
$cleaner->runDailyIfPending();
$db = Connection::getInstance();
$totalAgents = 0;
try {
$token = $this->getWazuhToken();
if ($token) {
$res = $this->fetchFromWazuhApi('/agents?limit=1', $token);
if (isset($res['data']['total_affected_items'])) {
$totalAgents = $res['data']['total_affected_items'];
}
}
} catch (\Exception $e) {}
$stats = [
'total_alerts' => $db->query("SELECT COUNT(*) FROM alerts")->fetchColumn(),
'total_agents' => $totalAgents,
'high_alerts' => $db->query("SELECT COUNT(*) FROM alerts WHERE rule_level >= 12")->fetchColumn(),
];
$recent_alerts = $db->query("SELECT * FROM alerts ORDER BY created_at DESC LIMIT 1000")->fetchAll();
$minAlertLevel = $_ENV['MIN_ALERT_LEVEL'] ?? 7;
$baseUrl = $this->getBaseUrl();
require_once __DIR__ . '/../../views/dashboard.php';
}
public function clearOldAlerts()
{
$cleaner = new \App\Engine\DataCleaner();
$deleted = $cleaner->forceRun();
$baseUrl = $this->getBaseUrl();
header('Location: ' . $baseUrl . '/?cleared=' . $deleted);
exit;
}
public function clearAllAlerts()
{
header('Content-Type: application/json');
$submittedPassword = $_POST['password'] ?? '';
$reason = trim($_POST['reason'] ?? '');
$envPassword = $_ENV['CLEAR_ALERTS_PASSWORD'] ?? '';
if (empty($reason)) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Please provide a reason for clearing alerts.']);
return;
}
if (empty($envPassword)) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'CLEAR_ALERTS_PASSWORD is not configured in .env file.']);
return;
}
if ($submittedPassword !== $envPassword) {
http_response_code(401);
echo json_encode(['status' => 'error', 'message' => 'Incorrect password.']);
return;
}
try {
$db = Connection::getInstance();
// Create log table if not exists
$db->query("CREATE TABLE IF NOT EXISTS alert_deletion_logs (
id INT AUTO_INCREMENT PRIMARY KEY,
reason TEXT NOT NULL,
deleted_count INT DEFAULT 0,
date_range VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");
// Get stats before deleting
$stats = $db->query("SELECT COUNT(*) as cnt, MIN(created_at) as min_date, MAX(created_at) as max_date FROM alerts")->fetch();
$deletedCount = $stats['cnt'] ?? 0;
$minDate = $stats['min_date'] ? date('Y-m-d H:i', strtotime($stats['min_date'])) : 'N/A';
$maxDate = $stats['max_date'] ? date('Y-m-d H:i', strtotime($stats['max_date'])) : 'N/A';
$dateRange = $minDate . ' to ' . $maxDate;
if ($deletedCount > 0) {
// Log the action
$stmt = $db->prepare("INSERT INTO alert_deletion_logs (reason, deleted_count, date_range) VALUES (?, ?, ?)");
$stmt->execute([$reason, $deletedCount, $dateRange]);
}
// Delete
$stmt = $db->query("DELETE FROM alerts");
// Reset auto increment so ID starts from 1 again
$db->query("ALTER TABLE alerts AUTO_INCREMENT = 1");
echo json_encode(['status' => 'success', 'deleted' => $deletedCount, 'message' => 'Successfully deleted ' . $deletedCount . ' alerts.']);
} catch (\Exception $e) {
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
}
public function aiHistory()
{
$db = Connection::getInstance();
// Ensure table exists just in case they visit this page first
$db->query("CREATE TABLE IF NOT EXISTS ai_remediation_cache (
rule_id INT PRIMARY KEY,
recommendation TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");
$stmt = $db->query("
SELECT c.rule_id, c.recommendation, c.created_at,
(SELECT description FROM alerts WHERE rule_id = c.rule_id ORDER BY id DESC LIMIT 1) as rule_desc,
(SELECT raw_data FROM alerts WHERE rule_id = c.rule_id ORDER BY id DESC LIMIT 1) as raw_data
FROM ai_remediation_cache c
ORDER BY c.created_at DESC
");
$histories = $stmt->fetchAll();
$baseUrl = $this->getBaseUrl();
require_once __DIR__ . '/../../views/ai_history.php';
}
public function settings()
{
$baseUrl = $this->getBaseUrl();
$db = Connection::getInstance();
// Ensure table exists just in case they visit settings before clearing
$db->query("CREATE TABLE IF NOT EXISTS alert_deletion_logs (
id INT AUTO_INCREMENT PRIMARY KEY,
reason TEXT NOT NULL,
deleted_count INT DEFAULT 0,
date_range VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");
$deletionLogs = $db->query("SELECT * FROM alert_deletion_logs ORDER BY created_at DESC")->fetchAll();
require_once __DIR__ . '/../../views/settings.php';
}
public function getRealtimeUpdates()
{
header('Content-Type: application/json');
try {
$db = Connection::getInstance();
$lastAlertId = isset($_GET['last_alert_id']) ? (int)$_GET['last_alert_id'] : 0;
// Get stats
$totalAlerts = $db->query("SELECT COUNT(*) FROM alerts")->fetchColumn();
$openCases = $db->query("SELECT COUNT(*) FROM cases WHERE status = 'open'")->fetchColumn();
$highAlerts = $db->query("SELECT COUNT(*) FROM alerts WHERE rule_level >= 12")->fetchColumn();
// Get new alerts since last ID
$stmt = $db->prepare("SELECT id, rule_id, rule_level, description, agent_name, created_at, raw_data FROM alerts WHERE id > ? ORDER BY id ASC");
$stmt->execute([$lastAlertId]);
$newAlerts = $stmt->fetchAll(\PDO::FETCH_ASSOC);
echo json_encode([
'status' => 'success',
'stats' => [
'total_alerts' => $totalAlerts,
'open_cases' => $openCases,
'high_alerts' => $highAlerts
],
'new_alerts' => $newAlerts
]);
} catch (\Exception $e) {
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
}
public function getChartData()
{
header('Content-Type: application/json');
try {
$db = Connection::getInstance();
// Chart 1: Alerts by Rule Level (Doughnut)
$levels = $db->query("SELECT rule_level, COUNT(*) as count FROM alerts GROUP BY rule_level ORDER BY rule_level ASC")->fetchAll();
$levelLabels = [];
$levelData = [];
foreach ($levels as $row) {
$levelLabels[] = "Level " . $row['rule_level'];
$levelData[] = (int)$row['count'];
}
// Chart 2: Top 5 Agents by Alerts (Bar)
$agents = $db->query("SELECT agent_name, COUNT(*) as count FROM alerts GROUP BY agent_name ORDER BY count DESC LIMIT 5")->fetchAll();
$agentLabels = [];
$agentData = [];
foreach ($agents as $row) {
$agentLabels[] = $row['agent_name'];
$agentData[] = (int)$row['count'];
}
echo json_encode([
'levels' => [
'labels' => $levelLabels,
'data' => $levelData
],
'agents' => [
'labels' => $agentLabels,
'data' => $agentData
]
]);
} catch (\Exception $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
}
}
@@ -0,0 +1,110 @@
<?php
namespace App\Controllers;
use App\Database\Connection;
use PDO;
class SearchController
{
public function index()
{
$pageTitle = 'Historical Search';
// Support subfolder deployment
$baseUrl = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
$baseUrl = str_replace('/public', '', $baseUrl);
if ($baseUrl === '/') $baseUrl = '';
$appName = $_ENV['APP_NAME'] ?? 'KSH SOAR';
require_once __DIR__ . '/../../views/search.php';
}
public function ssp()
{
header('Content-Type: application/json');
try {
$db = Connection::getInstance();
// DataTables parameters
$draw = isset($_POST['draw']) ? (int)$_POST['draw'] : 1;
$start = isset($_POST['start']) ? (int)$_POST['start'] : 0;
$length = isset($_POST['length']) ? (int)$_POST['length'] : 10;
$searchValue = isset($_POST['search']['value']) ? $_POST['search']['value'] : '';
$startDate = isset($_POST['startDate']) ? $_POST['startDate'] : '';
$endDate = isset($_POST['endDate']) ? $_POST['endDate'] : '';
// Determine sorting
$orderColumnIndex = isset($_POST['order'][0]['column']) ? (int)$_POST['order'][0]['column'] : 0;
$orderDir = isset($_POST['order'][0]['dir']) && $_POST['order'][0]['dir'] === 'asc' ? 'ASC' : 'DESC';
// Map DataTables column index to actual database columns
$columns = [
0 => 'created_at',
1 => 'rule_level',
2 => 'description',
3 => 'agent_name'
];
$orderBy = isset($columns[$orderColumnIndex]) ? $columns[$orderColumnIndex] : 'created_at';
// Total records without filtering
$totalRecords = $db->query("SELECT COUNT(*) FROM alerts")->fetchColumn();
// Build WHERE clause for search and date filters
$whereConditions = [];
$params = [];
if (!empty($searchValue)) {
$whereConditions[] = "(description LIKE ? OR agent_name LIKE ? OR rule_id LIKE ?)";
$likeSearch = "%{$searchValue}%";
array_push($params, $likeSearch, $likeSearch, $likeSearch);
}
if (!empty($startDate)) {
$whereConditions[] = "created_at >= ?";
$params[] = $startDate . " 00:00:00";
}
if (!empty($endDate)) {
$whereConditions[] = "created_at <= ?";
$params[] = $endDate . " 23:59:59";
}
$whereClause = "";
if (count($whereConditions) > 0) {
$whereClause = "WHERE " . implode(" AND ", $whereConditions);
}
// Total records with filtering
$filteredRecordsQuery = "SELECT COUNT(*) FROM alerts {$whereClause}";
$stmt = $db->prepare($filteredRecordsQuery);
$stmt->execute($params);
$totalFiltered = $stmt->fetchColumn();
// Fetch actual data
$dataQuery = "SELECT id, rule_id, rule_level, description, agent_name, created_at, raw_data
FROM alerts
{$whereClause}
ORDER BY {$orderBy} {$orderDir}
LIMIT {$start}, {$length}";
$stmt = $db->prepare($dataQuery);
$stmt->execute($params);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Return JSON expected by DataTables
echo json_encode([
"draw" => $draw,
"recordsTotal" => (int)$totalRecords,
"recordsFiltered" => (int)$totalFiltered,
"data" => $data
]);
} catch (\Exception $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
}
}
@@ -0,0 +1,62 @@
<?php
namespace App\Controllers;
use App\Database\Connection;
class SysmonController
{
private function getBaseUrl()
{
$baseUrl = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
$baseUrl = str_replace('/public', '', $baseUrl);
if ($baseUrl === '/') $baseUrl = '';
return $baseUrl;
}
public function index()
{
$db = Connection::getInstance();
$baseUrl = $this->getBaseUrl();
// 1. Get total Sysmon alerts today
$todayStart = date('Y-m-d 00:00:00');
$stmtTotal = $db->prepare("SELECT COUNT(*) FROM alerts WHERE raw_data LIKE '%sysmon%' AND created_at >= ?");
$stmtTotal->execute([$todayStart]);
$totalSysmonToday = $stmtTotal->fetchColumn();
// 2. Get top 5 agents with Sysmon alerts
$stmtTopAgents = $db->query("
SELECT agent_name, COUNT(*) as cnt
FROM alerts
WHERE raw_data LIKE '%sysmon%'
GROUP BY agent_name
ORDER BY cnt DESC
LIMIT 5
");
$topAgents = $stmtTopAgents->fetchAll();
// 3. Get top 5 Sysmon rules triggered
$stmtTopRules = $db->query("
SELECT rule_id, description, COUNT(*) as cnt
FROM alerts
WHERE raw_data LIKE '%sysmon%'
GROUP BY rule_id, description
ORDER BY cnt DESC
LIMIT 5
");
$topRules = $stmtTopRules->fetchAll();
// 4. Get recent Sysmon alerts for the table
$stmtRecent = $db->query("
SELECT *
FROM alerts
WHERE raw_data LIKE '%sysmon%'
ORDER BY created_at DESC
LIMIT 1000
");
$recentAlerts = $stmtRecent->fetchAll();
require_once __DIR__ . '/../../views/sysmon.php';
}
}
@@ -0,0 +1,202 @@
<?php
namespace App\Controllers;
use App\Database\Connection;
use Exception;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
class WazuhWebhookController
{
private $logger;
public function __construct()
{
$this->logger = new Logger('wazuh_webhook');
$this->logger->pushHandler(new StreamHandler(__DIR__ . '/../../storage/wazuh_alerts.log', Logger::INFO));
}
public function handle()
{
header('Content-Type: application/json');
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if (!$data || !isset($data['rule'])) {
$this->logger->warning("Invalid payload received", ['payload' => $input]);
http_response_code(400);
echo json_encode(['error' => 'Invalid Wazuh alert payload']);
return;
}
try {
$db = Connection::getInstance();
// Extract alert details
$wazuhAlertId = $data['id'] ?? uniqid();
$ruleId = $data['rule']['id'] ?? 0;
$ruleLevel = $data['rule']['level'] ?? 0;
// Filter by MIN_ALERT_LEVEL
$minAlertLevel = (int)($_ENV['MIN_ALERT_LEVEL'] ?? 7);
if ($ruleLevel < $minAlertLevel) {
// Drop alert quietly
$this->logger->info("Alert dropped due to low level", ['rule_level' => $ruleLevel, 'min_level' => $minAlertLevel]);
echo json_encode(['status' => 'ignored', 'message' => "Alert level {$ruleLevel} is below threshold {$minAlertLevel}"]);
return;
}
// Filter by EXCLUDE_RULE_IDS
$excludeIdsRaw = $_ENV['EXCLUDE_RULE_IDS'] ?? '';
if (!empty($excludeIdsRaw)) {
$excludeIds = array_map('trim', explode(',', $excludeIdsRaw));
if (in_array((string)$ruleId, $excludeIds)) {
$this->logger->info("Alert dropped due to excluded Rule ID", ['rule_id' => $ruleId]);
echo json_encode(['status' => 'ignored', 'message' => "Rule ID {$ruleId} is in EXCLUDE_RULE_IDS list"]);
return;
}
}
$agentId = $data['agent']['id'] ?? '000';
$agentName = $data['agent']['name'] ?? 'unknown';
$agentIp = $data['agent']['ip'] ?? '0.0.0.0';
$fullLog = $data['full_log'] ?? '';
$rawData = json_encode($data);
// Translate description to Thai
$englishDesc = $data['rule']['description'] ?? '';
$description = $this->translateDescription($ruleId, $englishDesc);
// Check if case needs to be created or linked
$caseId = null;
$shouldNotify = false;
if ($ruleLevel >= 12) {
$stmt = $db->prepare("INSERT INTO cases (title, severity) VALUES (?, ?)");
$severity = 'high';
if ($ruleLevel >= 14) $severity = 'critical';
$stmt->execute(["[AUTO] Alert Level {$ruleLevel} on {$agentName}", $severity]);
$caseId = $db->lastInsertId();
$shouldNotify = true;
}
// Insert Alert
$stmt = $db->prepare("
INSERT INTO alerts (
wazuh_alert_id, rule_id, rule_level, description,
agent_id, agent_name, agent_ip, full_log, raw_data, case_id
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
$stmt->execute([
$wazuhAlertId, $ruleId, $ruleLevel, $description,
$agentId, $agentName, $agentIp, $fullLog, $rawData, $caseId
]);
$alertId = $db->lastInsertId();
$this->logger->info("Alert saved", ['alert_id' => $alertId, 'rule' => $ruleId]);
// Execute Playbook: Notify SOC Team if High Risk
if ($shouldNotify) {
$icon = ($ruleLevel >= 14) ? "🔥" : "🚨";
$appName = $_ENV['APP_NAME'] ?? 'KSH SOAR';
// Get AI Analysis quickly (with 5 sec timeout)
$aiText = $this->analyzeWithGemini($ruleId, $ruleLevel, $description);
$msg = "{$icon} <b>[{$appName}] แจ้งเตือนภัยคุกคาม!</b>\n";
$msg .= "━━━━━━━━━━━━━━━━━━━━\n";
$msg .= "⚠️ <b>ระดับความเสี่ยง:</b> <code>Level {$ruleLevel}</code> " . ($ruleLevel >= 14 ? "(🔥 Critical)" : "(🚨 High)") . "\n";
$msg .= "🆔 <b>Rule ID:</b> <code>{$ruleId}</code>\n";
$msg .= "🖥 <b>เครื่อง (Agent):</b> <code>{$agentName}</code>\n";
$msg .= "🌐 <b>IP Address:</b> <code>{$agentIp}</code>\n";
$msg .= "━━━━━━━━━━━━━━━━━━━━\n";
$msg .= "📝 <b>รายละเอียด:</b>\n<i>{$description}</i>\n\n";
$msg .= "🤖 <b>การวิเคราะห์จาก AI:</b>\n💡 <i>{$aiText}</i>\n\n";
$msg .= "📍 <b>การจัดการเบื้องต้น:</b>\n";
$msg .= "✅ เปิดเคสสืบสวนอัตโนมัติ <b>#{$caseId}</b>\n\n";
$msg .= "🔍 <a href=\"{$_ENV['APP_URL']}/\">คลิกที่นี่เพื่อเปิด Dashboard</a>";
require_once __DIR__ . '/../Integrations/Notifier.php';
$notified = \App\Integrations\Notifier::notifyAll($msg);
// Log the initial action
$statusMsg = $notified ? "Successfully sent High-Risk notification to Line/Telegram" : "Failed or No Token set for Line/Telegram notification";
$logStmt = $db->prepare("INSERT INTO action_logs (alert_id, status, result_message) VALUES (?, ?, ?)");
$logStmt->execute([$alertId, $notified ? 'success' : 'failed', $statusMsg]);
}
echo json_encode(['status' => 'success', 'alert_id' => $alertId, 'case_id' => $caseId]);
} catch (Exception $e) {
$this->logger->error("Database error", ['message' => $e->getMessage()]);
http_response_code(500);
echo json_encode(['error' => 'Internal server error']);
}
}
private function analyzeWithGemini($ruleId, $level, $desc)
{
$apiKey = $_ENV['GEMINI_API_KEY'] ?? '';
if (empty($apiKey)) {
return "<i>(ไม่มีการตั้งค่า API Key สำหรับ AI)</i>";
}
$prompt = "You are a cybersecurity SOC analyst. Briefly analyze this Wazuh alert and provide a 1-2 sentence summary in Thai of what it means and what to do. DO NOT use markdown like **, just plain text.
Rule ID: {$ruleId}
Level: {$level}
Description: {$desc}";
$url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=" . $apiKey;
$payload = [
"contents" => [
["parts" => [["text" => $prompt]]]
]
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 5 sec timeout to avoid blocking webhook
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200 && $response) {
$data = json_decode($response, true);
$text = $data['candidates'][0]['content']['parts'][0]['text'] ?? '';
return trim(str_replace(['*', '`', '#'], '', $text)); // Clean up any markdown
}
return "<i>(AI ไม่สามารถวิเคราะห์ได้ในขณะนี้)</i>";
}
private function translateDescription($ruleId, $englishDesc)
{
$dictionary = [
5716 => "เข้าสู่ระบบล้มเหลว (อาจพิมพ์รหัสผิด)",
5720 => "ใส่รหัสผ่านผิดหลายครั้งติดต่อกัน (ระวังโดนสุ่มรหัส)",
5710 => "มีความพยายามเข้าสู่ระบบด้วยชื่อผู้ใช้ที่ไม่มีอยู่จริง",
60106 => "เข้าสู่ระบบ Windows ล้มเหลว",
60122 => "เข้าสู่ระบบ Windows สำเร็จ",
5501 => "มีการเข้าสู่ระบบสำเร็จ",
5502 => "มีการออกจากระบบ",
502 => "ระบบ Wazuh Server เริ่มทำงาน",
1002 => "พบสิ่งผิดปกติในระบบ (Unknown)",
// เพิ่ม Rule ID อื่นๆ ที่เจอบ่อยๆ ตรงนี้ได้เลยครับ
];
// ถ้ามีคำแปลใน Dictionary ให้ใช้คำแปล
if (isset($dictionary[$ruleId])) {
return $dictionary[$ruleId];
}
// ถ้าไม่มีคำแปล ให้เอาภาษาอังกฤษเดิมมาแปะท้ายคำว่า [แจ้งเตือน]
return "[แจ้งเตือน] " . $englishDesc;
}
}
@@ -0,0 +1,39 @@
<?php
namespace App\Database;
use PDO;
use PDOException;
use Exception;
class Connection
{
private static ?PDO $instance = null;
public static function getInstance(): PDO
{
if (self::$instance === null) {
$host = $_ENV['DB_HOST'] ?? '127.0.0.1';
$port = $_ENV['DB_PORT'] ?? '3306';
$db = $_ENV['DB_DATABASE'] ?? 'soar';
$user = $_ENV['DB_USERNAME'] ?? 'root';
$pass = $_ENV['DB_PASSWORD'] ?? '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;port=$port;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
self::$instance = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
throw new Exception("Database connection failed: " . $e->getMessage());
}
}
return self::$instance;
}
}
@@ -0,0 +1,82 @@
<?php
namespace App\Engine;
use App\Database\Connection;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Exception;
class DataCleaner
{
private $db;
private $logger;
private $lastRunFile;
public function __construct()
{
$this->db = Connection::getInstance();
$this->logger = new Logger('data_cleaner');
$this->logger->pushHandler(new StreamHandler(__DIR__ . '/../../storage/cleanup.log', Logger::INFO));
$this->lastRunFile = __DIR__ . '/../../storage/last_cleanup.date';
}
/**
* Run cleanup automatically if it hasn't run today
*/
public function runDailyIfPending(): void
{
$today = date('Y-m-d');
$lastRun = '';
if (file_exists($this->lastRunFile)) {
$lastRun = trim(file_get_contents($this->lastRunFile));
}
if ($lastRun !== $today) {
$this->logger->info("Automatic daily cleanup triggered.");
$this->cleanup();
file_put_contents($this->lastRunFile, $today);
}
}
/**
* Force run the cleanup process manually
*/
public function forceRun(): int
{
$this->logger->info("Manual cleanup triggered by user.");
$deletedRows = $this->cleanup();
file_put_contents($this->lastRunFile, date('Y-m-d')); // Update date so it doesn't run again today
return $deletedRows;
}
/**
* Core cleanup logic
*/
private function cleanup(): int
{
$retentionDays = $_ENV['ALERT_RETENTION_DAYS'] ?? 90;
try {
// Delete alerts older than X days, BUT keep alerts that are linked to cases
$stmt = $this->db->prepare("
DELETE FROM alerts
WHERE created_at < NOW() - INTERVAL ? DAY
AND case_id IS NULL
");
$stmt->execute([$retentionDays]);
$deletedCount = $stmt->rowCount();
if ($deletedCount > 0) {
$this->logger->info("Cleanup completed. Deleted {$deletedCount} old alerts.");
}
return $deletedCount;
} catch (Exception $e) {
$this->logger->error("Cleanup failed: " . $e->getMessage());
return 0;
}
}
}
@@ -0,0 +1,126 @@
<?php
namespace App\Engine {
class Language {
private static $dict = [
// Menus
'Dashboard' => 'หน้าหลัก',
'Historical Search' => 'ค้นหาย้อนหลัง',
'AI Knowledge Base' => 'ฐานความรู้ AI',
'System Settings' => 'ตั้งค่าระบบ',
'Settings' => 'ตั้งค่าระบบ',
'MAIN NAVIGATION' => 'เมนูหลัก',
// Dashboard
// Agents
'Agents (Devices)' => 'อุปกรณ์ (Agents)',
'Agents Overview' => 'ภาพรวมอุปกรณ์',
'Total Agents' => 'อุปกรณ์ทั้งหมด',
'Active (Online)' => 'ออนไลน์',
'Disconnected (Offline)' => 'ออฟไลน์',
'Never Connected' => 'ไม่เคยเชื่อมต่อ',
'Resource Warnings' => 'แจ้งเตือนทรัพยากรระบบ',
'Disk/RAM warnings from active alerts' => 'แจ้งเตือน Disk/RAM จากข้อมูล Alerts',
'No resource warnings detected.' => 'ไม่พบการแจ้งเตือนทรัพยากรระบบ',
'Agent Name' => 'ชื่ออุปกรณ์',
'IP Address' => 'ไอพีแอดเดรส',
'OS' => 'ระบบปฏิบัติการ',
'Status' => 'สถานะ',
'Specs' => 'สเปคเครื่อง',
'Remote' => 'รีโมท',
'Agent Specifications' => 'สเปคของอุปกรณ์',
'Hardware & Network details' => 'รายละเอียดฮาร์ดแวร์และเครือข่าย',
'CPU' => 'ซีพียู (CPU)',
'RAM Total' => 'แรมทั้งหมด (RAM Total)',
'Disk Storage (Drive C)' => 'พื้นที่เก็บข้อมูล (Drive C)',
'Remote Access' => 'ข้อมูลการเชื่อมต่อระยะไกล (Remote)',
'Network Interfaces' => 'การเชื่อมต่อเครือข่าย',
'MAC Address' => 'MAC Address',
'Close' => 'ปิด',
'Loading...' => 'กำลังโหลด...',
'Failed to load specifications.' => 'ไม่สามารถโหลดสเปคได้',
'View Specs' => 'ดูสเปค',
'System Overview' => 'ภาพรวมระบบ',
'Open Cases' => 'เคสที่เปิดอยู่',
'High Severity (12+)' => 'ความเสี่ยงสูง (12+)',
'Clear Old Alerts' => 'ลบข้อมูลเก่า',
'Dashboard Overview' => 'ภาพรวมระบบ',
'System Active' => 'ระบบทำงานปกติ',
'Total Alerts' => 'การแจ้งเตือนทั้งหมด',
'High Risk Alerts' => 'ความเสี่ยงสูง',
'Alerts' => 'รายการ',
'Last 30 Days' => 'ช่วง 30 วันที่ผ่านมา',
'Level 12+' => 'ระดับ 12 ขึ้นไป',
'Recent Activity Stream' => 'กิจกรรมล่าสุด',
'ID' => 'รหัส',
'Timestamp' => 'วัน-เวลา',
'Time' => 'วัน-เวลา',
'Level' => 'ระดับ',
'Agent' => 'เครื่องต้นทาง',
'Description' => 'รายละเอียด',
'Action' => 'จัดการ',
'View' => 'ดูข้อมูล',
// Search
'Historical Alert Search' => 'ค้นหาการแจ้งเตือนย้อนหลัง',
'Search Criteria' => 'เงื่อนไขการค้นหา',
'Keyword' => 'คำค้นหา',
'e.g. login failed, root, syscheck' => 'เช่น login failed, root, syscheck',
'Minimum Level' => 'ระดับความรุนแรงขั้นต่ำ',
'All Levels' => 'ทุกระดับ',
'Date Range' => 'ช่วงเวลา',
'Last 24 Hours' => '24 ชั่วโมงที่ผ่านมา',
'Last 7 Days' => '7 วันที่ผ่านมา',
'Last 30 Days' => '30 วันที่ผ่านมา',
'Custom Range' => 'กำหนดเอง',
'Search' => 'ค้นหา',
'Search Results' => 'ผลลัพธ์การค้นหา',
// AI History
'Rule ID' => 'รหัสกฎ (Rule ID)',
'AI Recommendation' => 'คำแนะนำจาก AI',
'Cached Date' => 'วันที่บันทึก',
'No AI insights cached yet.' => 'ยังไม่มีข้อมูลวิเคราะห์จาก AI',
// Settings
'Core Integration' => 'การเชื่อมต่อหลัก',
'Wazuh Manager API URL' => 'URL ของ Wazuh Manager API',
'Wazuh Indexer URL' => 'URL ของ Wazuh Indexer',
'System Name (APP_NAME)' => 'ชื่อระบบ (APP_NAME)',
'Rule & Retention Policies' => 'นโยบายการเก็บข้อมูลและกฎ',
'Alert Retention Policy' => 'ระยะเวลาเก็บข้อมูลการแจ้งเตือน',
'Alert Level Threshold' => 'ระดับขั้นต่ำที่บันทึก (Threshold)',
'Resource Alert Threshold (RAM & Disk)' => 'เกณฑ์แจ้งเตือนทรัพยากร (RAM และ Disk)',
'RAM Alert Threshold (%)' => 'เกณฑ์การใช้ RAM (%)',
'Disk Alert Threshold (%)' => 'เกณฑ์การใช้ Disk (%)',
'Excluded Rule IDs (Ignored Alerts)' => 'ละเว้นรหัสกฎ (ไม่บันทึกข้อมูล)',
'Notification Playbooks' => 'ช่องทางการแจ้งเตือน',
'Data Management' => 'การจัดการข้อมูล',
'Clear All Alerts' => 'ลบข้อมูลการแจ้งเตือนทั้งหมด',
'Delete All Alerts' => 'ลบข้อมูลทั้งหมด',
'Deletion History' => 'ประวัติการลบข้อมูล',
'Date Deleted' => 'วันที่ลบ',
'Reason' => 'เหตุผล',
'Records Deleted' => 'จำนวนที่ลบ',
'Data Date Range' => 'ช่วงวันที่ของข้อมูลที่ลบ',
'Configuration Management' => 'การจัดการการตั้งค่าระบบ'
];
public static function translate($key) {
$lang = $_COOKIE['lang'] ?? 'en';
if ($lang === 'th' && isset(self::$dict[$key])) {
return self::$dict[$key];
}
return $key;
}
}
}
namespace {
if (!function_exists('__')) {
function __($key) {
return \App\Engine\Language::translate($key);
}
}
}
@@ -0,0 +1,112 @@
<?php
namespace App\Engine;
use App\Database\Connection;
use App\Integrations\WazuhAPI;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Exception;
class PlaybookEvaluator
{
private $db;
private $logger;
public function __construct()
{
$this->db = Connection::getInstance();
$this->logger = new Logger('playbook_engine');
$this->logger->pushHandler(new StreamHandler(__DIR__ . '/../../automation.log', Logger::INFO));
}
public function evaluateUnprocessedAlerts()
{
// Simple queue mechanism: look for alerts that haven't been evaluated
// In a real app, you might use a separate queue table
$stmt = $this->db->query("
SELECT a.* FROM alerts a
LEFT JOIN action_logs l ON a.id = l.alert_id
WHERE l.id IS NULL
ORDER BY a.created_at ASC
LIMIT 50
");
$alerts = $stmt->fetchAll();
foreach ($alerts as $alert) {
$this->processAlert($alert);
}
}
private function processAlert($alert)
{
$this->logger->info("Evaluating Alert ID: {$alert['id']} (Rule {$alert['rule_id']})");
// Find matching active playbooks
$stmt = $this->db->prepare("
SELECT * FROM playbooks
WHERE is_active = 1
AND (trigger_rule_id = ? OR (? >= trigger_level AND trigger_level IS NOT NULL))
");
$stmt->execute([$alert['rule_id'], $alert['rule_level']]);
$playbooks = $stmt->fetchAll();
if (empty($playbooks)) {
$this->logAction($alert['id'], null, null, 'success', 'No playbook matched.');
return;
}
foreach ($playbooks as $playbook) {
$this->executePlaybook($alert, $playbook);
}
}
private function executePlaybook($alert, $playbook)
{
$this->logger->info("Triggering Playbook ID: {$playbook['id']} for Alert {$alert['id']}");
$stmt = $this->db->prepare("SELECT * FROM playbook_actions WHERE playbook_id = ? ORDER BY sequence ASC");
$stmt->execute([$playbook['id']]);
$actions = $stmt->fetchAll();
foreach ($actions as $action) {
try {
$this->runAction($alert, $action);
$this->logAction($alert['id'], $playbook['id'], $action['id'], 'success', "Action {$action['action_type']} completed.");
} catch (Exception $e) {
$this->logAction($alert['id'], $playbook['id'], $action['id'], 'failed', $e->getMessage());
$this->logger->error("Action Failed", ['error' => $e->getMessage()]);
}
}
}
private function runAction($alert, $action)
{
$params = json_decode($action['action_params'], true) ?? [];
switch ($action['action_type']) {
case 'wazuh_active_response':
$api = new WazuhAPI();
$command = $params['command'] ?? 'firewall-drop';
$api->runActiveResponse($alert['agent_id'], $command);
break;
case 'slack_notify':
// TODO: Implement Slack integration
break;
default:
throw new Exception("Unknown action type: {$action['action_type']}");
}
}
private function logAction($alertId, $playbookId, $actionId, $status, $message)
{
$stmt = $this->db->prepare("
INSERT INTO action_logs (alert_id, playbook_id, action_id, status, result_message)
VALUES (?, ?, ?, ?, ?)
");
$stmt->execute([$alertId, $playbookId, $actionId, $status, $message]);
}
}
@@ -0,0 +1,64 @@
<?php
namespace App\Integrations;
class Notifier
{
public static function sendLineNotify($message)
{
$token = $_ENV['LINE_NOTIFY_TOKEN'] ?? '';
if (empty($token)) return false;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://notify-api.line.me/api/notify");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['message' => "\n" . $message]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer {$token}",
"Content-Type: application/x-www-form-urlencoded"
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $result !== false && $httpcode == 200;
}
public static function sendTelegram($message)
{
$token = $_ENV['TELEGRAM_BOT_TOKEN'] ?? '';
$chatId = $_ENV['TELEGRAM_CHAT_ID'] ?? '';
if (empty($token) || empty($chatId)) return false;
$url = "https://api.telegram.org/bot{$token}/sendMessage";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'chat_id' => $chatId,
'text' => $message,
'parse_mode' => 'HTML'
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $result !== false && $httpcode == 200;
}
public static function notifyAll($message)
{
$lineSent = self::sendLineNotify($message);
$telegramSent = self::sendTelegram($message);
return $lineSent || $telegramSent;
}
}
@@ -0,0 +1,109 @@
<?php
namespace App\Integrations;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
class WazuhAPI
{
private Client $client;
private string $baseUrl;
private string $token;
private string $user;
private string $password;
public function __construct()
{
$this->baseUrl = $_ENV['WAZUH_API_URL'] ?? 'https://127.0.0.1:55000';
$this->user = $_ENV['WAZUH_API_USER'] ?? 'wazuh-wui';
$this->password = $_ENV['WAZUH_API_PASSWORD'] ?? 'wazuh-wui';
$this->initClient();
}
private function initClient()
{
$this->client = new Client([
'base_uri' => $this->baseUrl,
'verify' => false,
'timeout' => 20
]);
$this->authenticate();
}
private function authenticate()
{
// Try to load token from file cache to share between web and CLI
$tokenFile = __DIR__ . '/../../storage/wazuh_token.txt';
if (file_exists($tokenFile) && (time() - filemtime($tokenFile)) < 800) { // Token usually valid for ~900s
$this->token = trim(file_get_contents($tokenFile));
} else {
try {
$response = $this->client->get('/security/user/authenticate', [
'auth' => [$this->user, $this->password]
]);
$data = json_decode($response->getBody()->getContents(), true);
$this->token = $data['data']['token'] ?? '';
file_put_contents($tokenFile, $this->token);
} catch (GuzzleException $e) {
throw new \Exception("Wazuh Authentication Failed: " . $e->getMessage());
}
}
}
private function request(string $method, string $uri, array $options = [])
{
$options['headers'] = array_merge($options['headers'] ?? [], [
'Authorization' => "Bearer {$this->token}",
'Content-Type' => 'application/json'
]);
try {
$response = $this->client->request($method, $uri, $options);
return json_decode($response->getBody()->getContents(), true);
} catch (\GuzzleHttp\Exception\ClientException $e) {
// If 401 Unauthorized, token might have expired, try to re-auth once
if ($e->getResponse()->getStatusCode() == 401) {
@unlink(__DIR__ . '/../../storage/wazuh_token.txt');
$this->authenticate();
$options['headers']['Authorization'] = "Bearer {$this->token}";
$response = $this->client->request($method, $uri, $options);
return json_decode($response->getBody()->getContents(), true);
}
throw $e;
} catch (GuzzleException $e) {
throw new \Exception("Wazuh API Request Failed ({$uri}): " . $e->getMessage());
}
}
public function runActiveResponse($agentId, $command, $customData = [])
{
return $this->request('PUT', '/active-response', [
'json' => [
'command' => $command,
'arguments' => ['-'],
'custom' => !empty($customData) ? $customData : false,
'agents_list' => [$agentId]
]
]);
}
public function getAgents($limit = 1000)
{
return $this->request('GET', "/agents?limit={$limit}");
}
public function getSyscollector($agentId, $type, $limit = 1000)
{
// Some syscollector endpoints (like hardware, os) do not support the 'limit' parameter
if (in_array($type, ['hardware', 'os'])) {
return $this->request('GET', "/syscollector/{$agentId}/{$type}");
}
// Valid types: netiface, netaddr, netproto, packages, hotfixes, processes
return $this->request('GET', "/syscollector/{$agentId}/{$type}?limit={$limit}");
}
}
@@ -0,0 +1,174 @@
<?php
namespace App\Integrations;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
class WazuhIndexer
{
private Client $client;
public function __construct()
{
$baseUrl = $_ENV['WAZUH_INDEXER_URL'] ?? 'https://127.0.0.1:9200';
$user = $_ENV['WAZUH_INDEXER_USER'] ?? 'admin';
$password = $_ENV['WAZUH_INDEXER_PASSWORD'] ?? 'admin';
$this->client = new Client([
'base_uri' => $baseUrl,
'verify' => false,
'auth' => [$user, $password],
'timeout' => 6,
'headers' => [
'Content-Type' => 'application/json'
]
]);
}
public function checkConnection(): string
{
try {
$response = $this->client->get('/');
return 'OK';
} catch (\GuzzleHttp\Exception\ClientException $e) {
if ($e->getResponse()->getStatusCode() == 401) return 'AUTH_FAILED';
return 'CONNECTION_ERROR';
} catch (GuzzleException $e) {
return 'CONNECTION_ERROR';
}
}
public function getCustomInventory($agentId, $location)
{
try {
$payload = [
'size' => 1,
'sort' => ['@timestamp' => 'desc'],
'query' => [
'bool' => [
'must' => [
['match' => ['agent.id' => $agentId]],
['match' => ['location' => $location]]
]
]
]
];
$response = $this->client->post('/wazuh-alerts-*/_search', ['json' => $payload]);
$data = json_decode($response->getBody()->getContents(), true);
if (isset($data['hits']['hits'][0]['_source']['full_log'])) {
$log = $data['hits']['hits'][0]['_source']['full_log'];
$log = preg_replace('/^ossec: output: \'' . preg_quote($location, '/') . '\':\s*/', '', $log);
$json = json_decode($log, true);
return $json !== null ? $json : $log;
}
return null;
} catch (GuzzleException $e) {
return null;
}
}
public function getMetadata()
{
try {
$payload = [
'size' => 10000,
'sort' => ['@timestamp' => 'desc'],
'query' => [
'terms' => [
'location' => [
'teamviewer_inventory',
'anydesk_inventory',
'disk_inventory',
'model_inventory',
'manufacturer_inventory'
]
]
],
'_source' => ['agent.id', 'location', 'full_log', 'agent.labels']
];
$response = $this->client->post('/wazuh-alerts-*/_search', ['json' => $payload]);
$data = json_decode($response->getBody()->getContents(), true);
$metadata = [];
if (isset($data['hits']['hits'])) {
foreach ($data['hits']['hits'] as $hit) {
$this->parseHit($hit, $metadata);
}
}
return $metadata;
} catch (GuzzleException $e) {
return [];
}
}
private function parseHit($hit, &$metadata)
{
$src = $hit['_source'];
$aid = $src['agent']['id'] ?? '';
$loc = $src['location'] ?? '';
$log = $src['full_log'] ?? '';
$labels = $src['agent']['labels'] ?? null;
if (!$aid) return;
if (!isset($metadata[$aid])) {
$metadata[$aid] = [
'tv' => null, 'ad' => null, 'asset_id' => null,
'location' => null, 'disk_c_total' => null,
'disk_c_free' => null, 'model' => null, 'manufacturer' => null
];
}
if ($labels) {
if ($metadata[$aid]['asset_id'] === null && isset($labels['asset_id'])) $metadata[$aid]['asset_id'] = $labels['asset_id'];
if ($metadata[$aid]['location'] === null && isset($labels['location'])) $metadata[$aid]['location'] = $labels['location'];
}
if ($loc === 'teamviewer_inventory' && $metadata[$aid]['tv'] === null) {
$log = preg_replace('/^ossec: output: \'teamviewer_inventory\':\s*/', '', $log);
$json = json_decode($log, true);
$metadata[$aid]['tv'] = ($json && isset($json['TeamViewerID']) && $json['TeamViewerID'] !== 'Not Found') ? $json['TeamViewerID'] : 'None';
}
if ($loc === 'anydesk_inventory' && $metadata[$aid]['ad'] === null) {
$log = preg_replace('/^ossec: output: \'anydesk_inventory\':\s*/', '', $log);
$json = json_decode($log, true);
$metadata[$aid]['ad'] = ($json && isset($json['AnyDeskID']) && $json['AnyDeskID'] !== 'Not Found') ? $json['AnyDeskID'] : 'None';
}
if ($loc === 'disk_inventory' && $metadata[$aid]['disk_c_total'] === null) {
$log = preg_replace('/^ossec: output: \'disk_inventory\':\s*/', '', $log);
$json = json_decode($log, true);
if ($json && !is_array($json) && is_object((object)$json)) $json = [$json];
if (is_array($json)) {
foreach ($json as $disk) {
$dLetter = $disk['DriveLetter'] ?? $disk['Drive'] ?? $disk['DeviceID'] ?? $disk['Name'] ?? '';
if (strpos(strtoupper($dLetter), 'C') !== false) {
$t = $disk['Total_GB'] ?? $disk['SizeGB'] ?? (isset($disk['Size']) ? round($disk['Size'] / 1073741824, 2) : 0);
$f = $disk['Free_GB'] ?? $disk['FreeGB'] ?? (isset($disk['FreeSpace']) ? round($disk['FreeSpace'] / 1073741824, 2) : 0);
$metadata[$aid]['disk_c_total'] = $t ?: 'N/A';
$metadata[$aid]['disk_c_free'] = $f ?: 'N/A';
break;
}
}
}
}
if ($loc === 'model_inventory' && $metadata[$aid]['model'] === null) {
$log = preg_replace('/^ossec: output: \'model_inventory\':\s*/', '', $log);
$json = json_decode($log, true);
$metadata[$aid]['model'] = ($json && isset($json['PCModel'])) ? $json['PCModel'] : 'Unknown';
}
if ($loc === 'manufacturer_inventory' && $metadata[$aid]['manufacturer'] === null) {
$log = preg_replace('/^ossec: output: \'manufacturer_inventory\':\s*/', '', $log);
$json = json_decode($log, true);
$metadata[$aid]['manufacturer'] = ($json && isset($json['PCManufacturer'])) ? $json['PCManufacturer'] : 'Unknown';
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,455 @@
// Remote Panel Logic
let remoteDataLoaded = false;
function toggleRemotePanel() {
const panel = document.getElementById('remotePanel');
const backdrop = document.getElementById('remoteBackdrop');
if (panel.classList.contains('translate-x-full')) {
// Open
panel.classList.remove('translate-x-full');
backdrop.classList.remove('hidden');
setTimeout(() => backdrop.classList.remove('opacity-0'), 10);
if (!remoteDataLoaded) {
loadRemoteList();
}
} else {
// Close
panel.classList.add('translate-x-full');
backdrop.classList.add('opacity-0');
setTimeout(() => backdrop.classList.add('hidden'), 300);
}
}
function loadRemoteList() {
const container = document.getElementById('remoteListContainer');
container.innerHTML = '<div class="text-center text-slate-400 mt-10"><i class="fas fa-spinner fa-spin text-2xl mb-2"></i><br>Loading remote IDs...</div>';
fetch('<?= $baseUrl ?>/api/agents/remote-list')
.then(res => res.text())
.then(text => {
let res;
try {
res = JSON.parse(text);
} catch (e) {
console.error("JSON Parse Error:", e, "Response Text:", text);
container.innerHTML = '<div class="text-center text-rose-500 mt-10 text-xs text-left p-4 overflow-auto"><i class="fas fa-bug mb-2"></i><br>Parse error. Server returned:<br><code>' + text.substring(0, 200).replace(/</g, "&lt;") + '</code></div>';
return;
}
try {
if (res.status === 'success') {
remoteDataLoaded = true;
renderRemoteList(res.data);
} else {
container.innerHTML = '<div class="text-center text-rose-500 mt-10"><i class="fas fa-exclamation-triangle text-2xl mb-2"></i><br>' + (res.message || 'Failed to load data.') + '</div>';
}
} catch (e) {
console.error("Render Error:", e);
container.innerHTML = '<div class="text-center text-rose-500 mt-10"><i class="fas fa-bug mb-2"></i><br>UI Error: ' + e.message + '</div>';
}
})
.catch(err => {
console.error("Fetch Error:", err);
container.innerHTML = '<div class="text-center text-rose-500 mt-10"><i class="fas fa-exclamation-triangle text-2xl mb-2"></i><br>Connection error: ' + err.message + '</div>';
});
}
function toggleRemoteGroup(listId, iconId) {
const list = document.getElementById(listId);
const icon = document.getElementById(iconId);
if (list.classList.contains('hidden')) {
list.classList.remove('hidden');
icon.classList.remove('fa-chevron-down');
icon.classList.add('fa-chevron-up');
} else {
list.classList.add('hidden');
icon.classList.remove('fa-chevron-up');
icon.classList.add('fa-chevron-down');
}
}
function renderRemoteList(data) {
const container = document.getElementById('remoteListContainer');
container.innerHTML = '';
if (data.length === 0) {
container.innerHTML = '<div class="text-center text-slate-400 mt-10">No agents found.</div>';
return;
}
// Sort alphabetically by name
data.sort((a, b) => a.name.localeCompare(b.name));
const onlineAgents = data.filter(a => a.status === 'active');
const offlineAgents = data.filter(a => a.status !== 'active');
// Build HTML for Online Group (Expanded by default)
const onlineHtml = `
<div class="group-online border-b border-slate-200">
<button onclick="toggleRemoteGroup('online-list', 'online-icon')" class="w-full flex justify-between items-center bg-slate-50 p-3 text-xs font-bold text-slate-700 hover:bg-slate-100 transition-colors">
<div class="flex items-center">
<span class="w-2 h-2 rounded-full bg-emerald-500 mr-2 shadow-[0_0_5px_rgba(16,185,129,0.5)]"></span>
ออนไลน์ (<span id="online-count">${onlineAgents.length}</span>)
</div>
<i id="online-icon" class="fas fa-chevron-up text-slate-400 transition-transform text-[10px]"></i>
</button>
<div id="online-list" class="transition-all duration-300">
${onlineAgents.map(ag => createRemoteItemHtml(ag, true)).join('')}
</div>
</div>
`;
// Build HTML for Offline Group (Collapsed by default)
const offlineHtml = `
<div class="group-offline border-b border-slate-200">
<button onclick="toggleRemoteGroup('offline-list', 'offline-icon')" class="w-full flex justify-between items-center bg-slate-50 p-3 text-xs font-bold text-slate-700 hover:bg-slate-100 transition-colors">
<div class="flex items-center">
<span class="w-2 h-2 rounded-full bg-slate-400 mr-2"></span>
ออฟไลน์ (<span id="offline-count">${offlineAgents.length}</span>)
</div>
<i id="offline-icon" class="fas fa-chevron-down text-slate-400 transition-transform text-[10px]"></i>
</button>
<div id="offline-list" class="transition-all duration-300 hidden">
${offlineAgents.map(ag => createRemoteItemHtml(ag, false)).join('')}
</div>
</div>
`;
container.innerHTML = onlineHtml + offlineHtml;
filterRemoteList();
}
function createRemoteItemHtml(ag, isOnline) {
const dotColor = isOnline ? 'bg-emerald-500 shadow-[0_0_5px_rgba(16,185,129,0.5)]' : 'bg-slate-300';
let displayId = ag.remote_id ? ag.remote_id.toString() : '-';
let programIcon = '<i class="fas fa-desktop text-slate-300"></i>';
if (ag.remote_type === 'teamviewer') {
programIcon = '<i class="fas fa-network-wired text-blue-500" title="TeamViewer"></i>';
} else if (ag.remote_type === 'anydesk') {
programIcon = '<i class="fas fa-network-wired text-rose-500" title="AnyDesk"></i>';
}
return `
<div class="remote-item flex items-center justify-between px-3 py-2 border-b border-slate-50 hover:bg-slate-50 cursor-default bg-white transition-colors">
<div class="flex items-center space-x-2 w-5/12">
<div class="relative flex-shrink-0 text-center w-5">
${programIcon}
</div>
<span class="text-slate-700 text-xs font-medium truncate name-field" title="${ag.name}">${ag.name}</span>
</div>
<div class="flex items-center justify-end space-x-3 w-7/12">
<span class="font-mono text-slate-600 text-xs id-field whitespace-nowrap">${displayId}</span>
<span class="w-2.5 h-2.5 rounded-full flex-shrink-0 ${dotColor}" title="${isOnline ? 'ออนไลน์' : 'ออฟไลน์'}"></span>
</div>
</div>
`;
}
function filterRemoteList() {
const input = document.getElementById('remoteSearch').value.toLowerCase();
const hideNoRemote = document.getElementById('hideNoRemote').checked;
const items = document.querySelectorAll('.remote-item');
let onlineVisible = 0;
let offlineVisible = 0;
items.forEach(item => {
const name = item.querySelector('.name-field').innerText.toLowerCase();
const id = item.querySelector('.id-field').innerText.trim().toLowerCase();
const isOnline = item.parentElement.id === 'online-list';
const hasNoId = (id === '-' || id === '');
const matchSearch = name.includes(input) || id.includes(input) || input.replace(/\s/g, '') === id.replace(/\s/g, '');
if (matchSearch) {
if (hideNoRemote && hasNoId) {
item.style.display = 'none';
} else {
item.style.display = 'flex';
if (isOnline) onlineVisible++; else offlineVisible++;
}
} else {
item.style.display = 'none';
}
});
document.getElementById('online-count').innerText = onlineVisible;
document.getElementById('offline-count').innerText = offlineVisible;
}
$(document).ready(function() {
$('#agentsTable').DataTable({
pageLength: 10,
language: {
search: "_INPUT_",
searchPlaceholder: "Search agents..."
},
dom: '<"flex flex-col md:flex-row justify-between items-center mb-4"lf>rt<"flex flex-col md:flex-row justify-between items-center mt-4"ip>'
});
});
window.viewSpecs = function(agentId, agentName) {
Swal.fire({
title: '<?= __('Hardware Specs') ?> - ' + agentName,
html: '<div class="text-center py-4"><i class="fas fa-spinner fa-spin text-3xl text-slate-300"></i></div>',
showConfirmButton: false,
showCloseButton: true,
width: '800px',
customClass: { popup: 'rounded-xl shadow-2xl' }
});
$.ajax({
url: `<?= $baseUrl ?>/api/agents/${agentId}/details`,
method: 'GET',
success: function(res) {
if (res.status === 'success') {
const tmpl = document.getElementById('specsTemplate').innerHTML;
Swal.update({ html: tmpl });
const modal = Swal.getHtmlContainer();
const hw = (res.hardware && res.hardware.length > 0) ? res.hardware[0] : {};
// CPU
if (hw.cpu && hw.cpu.name) {
const cores = hw.cpu.cores ? ` (${hw.cpu.cores} Cores)` : '';
modal.querySelector('#spec-cpu').innerText = hw.cpu.name + cores;
} else {
modal.querySelector('#spec-cpu').innerText = '-';
}
// RAM
if (hw.ram && hw.ram.total) {
const totalMB = hw.ram.total / 1024;
const gb = (totalMB / 1024).toFixed(2);
let usageHtml = `${gb} GB`;
if (hw.ram.free !== undefined) {
const freeMB = hw.ram.free / 1024;
const usageMB = Math.max(0, totalMB - freeMB);
const pct = Math.round((usageMB / totalMB) * 100);
const alertThresh = <?= $_ENV['ALERT_RAM_PERCENT'] ?? 85 ?>;
const colorClass = pct >= alertThresh ? 'text-rose-600 font-bold' : (pct >= alertThresh - 15 ? 'text-orange-500' : 'text-emerald-600');
usageHtml = `${gb} GB <span class="ml-2 text-xs px-2 py-0.5 bg-slate-100 rounded-full ${colorClass}">${pct}% Used</span>`;
}
modal.querySelector('#spec-ram').innerHTML = usageHtml;
} else {
modal.querySelector('#spec-ram').innerText = '-';
}
// Disk
const diskContainer = modal.querySelector('#spec-disk');
let diskTotal = 0, diskFree = 0, diskUsed = 0;
if (res.disk_info) {
let diskData = res.disk_info;
if (typeof diskData === 'string') {
try { diskData = JSON.parse(diskData); } catch (e) {}
}
if (diskData && !Array.isArray(diskData) && typeof diskData === 'object') {
diskData = [diskData];
}
if (diskData && Array.isArray(diskData)) {
diskData = diskData.filter(disk => {
let d = String(disk.DriveLetter || disk.Drive || disk.DeviceID || disk.Name || '');
return d.toUpperCase().includes('C');
});
if (diskData.length > 0) {
let dInfo = diskData[0];
diskTotal = parseFloat(dInfo.Total_GB || dInfo.TotalSpace || dInfo.SizeGB || (dInfo.Size ? dInfo.Size / 1073741824 : 0));
diskFree = parseFloat(dInfo.Free_GB || dInfo.FreeGB || (dInfo.FreeSpace ? dInfo.FreeSpace / 1073741824 : 0));
// If parsed values are extraordinarily large (e.g., FreeSpace was just a number in bytes but not named FreeSpace)
// or if TotalSpace was in bytes
if (dInfo.TotalSpace && dInfo.TotalSpace > 100000) diskTotal = diskTotal / 1073741824;
if (dInfo.FreeSpace && dInfo.FreeSpace > 100000) diskFree = diskFree / 1073741824;
diskUsed = parseFloat(dInfo.Used_GB || (diskTotal - diskFree));
diskUsed = Math.max(0, diskUsed);
}
}
}
if (diskTotal > 0) {
const pct = Math.round((diskUsed / diskTotal) * 100);
const alertThresh = <?= $_ENV['ALERT_DISK_PERCENT'] ?? 85 ?>;
let colorClass = 'bg-emerald-500';
if (pct >= alertThresh) colorClass = 'bg-rose-500';
else if (pct >= alertThresh - 15) colorClass = 'bg-orange-500';
diskContainer.innerHTML = `
<div class="flex justify-between text-xs mb-1">
<span class="font-bold text-slate-700">Capacity: ${diskTotal.toFixed(2)} GB</span>
<span class="text-slate-500">${diskUsed.toFixed(2)} GB Used (${diskFree.toFixed(2)} GB Free)</span>
</div>
<div class="w-full bg-slate-200 rounded-full h-2.5">
<div class="${colorClass} h-2.5 rounded-full transition-all duration-500" style="width: ${pct}%"></div>
</div>
`;
} else {
diskContainer.innerHTML = '<div class="text-slate-400 text-xs italic">No disk information available</div>';
}
// Remote Access
const remoteContainer = modal.querySelector('#spec-remote');
remoteContainer.innerHTML = '';
let tvInfo = null;
if (res.tv_info) {
let t = Array.isArray(res.tv_info) ? res.tv_info[0] : res.tv_info;
tvInfo = (t && t.TeamViewerID && t.TeamViewerID !== 'Not Found') ? t.TeamViewerID : null;
}
let adInfo = null;
if (res.ad_info) {
let a = Array.isArray(res.ad_info) ? res.ad_info[0] : res.ad_info;
adInfo = (a && a.AnyDeskID && a.AnyDeskID !== 'Not Found') ? a.AnyDeskID : null;
}
if (tvInfo || adInfo) {
if (tvInfo) {
let tvId = tvInfo.toString();
if (tvId.match(/^\d{9,10}$/)) {
tvId = tvId.replace(/(\d{1,2})(\d{3})(\d{3})(\d{3})?/, "$1 $2 $3 $4").trim();
}
remoteContainer.innerHTML += `
<div class="bg-blue-50 p-3 rounded-lg border border-blue-100 flex items-center justify-between">
<div class="flex items-center text-blue-700 font-bold text-xs"><i class="fas fa-desktop mr-2"></i> TeamViewer</div>
<div class="font-mono text-sm text-slate-800 bg-white px-2 py-1 rounded shadow-sm">${tvId}</div>
</div>
`;
}
if (adInfo) {
let adId = adInfo.toString();
if (adId.match(/^\d{9,10}$/)) {
adId = adId.replace(/(\d{3})(\d{3})(\d{3})?/, "$1 $2 $3").trim();
}
remoteContainer.innerHTML += `
<div class="bg-rose-50 p-3 rounded-lg border border-rose-100 flex items-center justify-between">
<div class="flex items-center text-rose-700 font-bold text-xs"><i class="fas fa-desktop mr-2"></i> AnyDesk</div>
<div class="font-mono text-sm text-slate-800 bg-white px-2 py-1 rounded shadow-sm">${adId}</div>
</div>
`;
}
} else {
remoteContainer.innerHTML = '<div class="col-span-2 text-slate-400 text-xs italic">No remote access ID found</div>';
}
// Network
const netContainer = modal.querySelector('#spec-network');
netContainer.innerHTML = '';
let networkArray = [];
if (res.netiface && Array.isArray(res.netiface)) {
res.netiface.forEach(iface => {
let ips = [];
if (res.netaddr && Array.isArray(res.netaddr)) {
res.netaddr.forEach(addr => {
if (addr.iface === iface.name && addr.address) {
ips.push(addr.address);
}
});
}
networkArray.push({
name: iface.name,
mac: iface.mac,
state: iface.state,
ips: ips
});
});
}
if (networkArray.length > 0) {
let validIfaces = networkArray.filter(n => n.mac && n.mac !== '00:00:00:00:00:00' && n.ips && n.ips.length > 0);
validIfaces.forEach(iface => {
let stateText = iface.state ? iface.state.toLowerCase() : 'unknown';
if (stateText === 'unknown') stateText = (iface.ips.length > 0 ? 'up' : 'down');
iface._stateText = stateText;
let isExtra = false;
let n = iface.name.toLowerCase();
const extraWords = ['virtual', 'vmware', 'vbox', 'vethernet', 'bluetooth', 'pseudo', 'vpn', 'loopback', 'docker', 'br-', 'tailscale', 'zerotier', 'hamachi', 'wg', 'local area connection'];
for (let word of extraWords) {
if (n.includes(word)) { isExtra = true; break; }
}
iface._isExtra = isExtra;
});
validIfaces.sort((a, b) => {
if (a._stateText === 'up' && b._stateText !== 'up') return -1;
if (a._stateText !== 'up' && b._stateText === 'up') return 1;
if (!a._isExtra && b._isExtra) return -1;
if (a._isExtra && !b._isExtra) return 1;
return 0;
});
const toggleCb = document.getElementById('toggle-extra-net');
if (toggleCb) toggleCb.checked = false;
if (validIfaces.length > 0) {
validIfaces.forEach(iface => {
let stateBadge = '';
if (iface._stateText === 'up') {
stateBadge = '<span class="flex items-center text-[9px] font-bold text-emerald-600 bg-emerald-100 px-1.5 py-0.5 rounded uppercase"><span class="w-1.5 h-1.5 rounded-full bg-emerald-500 mr-1 animate-pulse"></span>Active</span>';
} else {
stateBadge = '<span class="flex items-center text-[9px] font-bold text-rose-600 bg-rose-100 px-1.5 py-0.5 rounded uppercase"><span class="w-1.5 h-1.5 rounded-full bg-rose-500 mr-1"></span>Offline</span>';
}
const div = document.createElement('div');
div.className = `bg-slate-50 p-2 rounded border border-slate-200 ${iface._isExtra ? 'iface-extra hidden' : ''}`;
div.innerHTML = `
<div class="flex justify-between items-center mb-2 pb-1 border-b border-slate-100">
<div class="font-bold text-slate-800 text-xs uppercase" title="${iface.name}">${iface.name.length > 20 ? iface.name.substring(0,20)+'...' : iface.name}</div>
${stateBadge}
</div>
<div class="flex justify-between text-xs mb-1">
<span class="text-slate-500">IP:</span>
<span class="font-mono text-blue-600 font-medium">${iface.ips.join(', ')}</span>
</div>
<div class="flex justify-between text-xs">
<span class="text-slate-500"><?= __('MAC Address') ?>:</span>
<span class="font-mono text-slate-700">${iface.mac || 'N/A'}</span>
</div>
`;
netContainer.appendChild(div);
});
let visibleCount = validIfaces.filter(i => !i._isExtra).length;
if (visibleCount === 0) {
const placeholder = document.createElement('div');
placeholder.className = 'text-slate-400 text-center py-2 col-span-full iface-placeholder';
placeholder.innerHTML = 'No primary interfaces found. Click "Show All" to view others.';
netContainer.appendChild(placeholder);
if (toggleCb) {
toggleCb.addEventListener('change', function() {
placeholder.style.display = this.checked ? 'none' : 'block';
});
}
}
} else {
netContainer.innerHTML = '<div class="text-slate-400 text-center py-2 col-span-full">No active LAN/WiFi interfaces found</div>';
}
} else {
netContainer.innerHTML = '<div class="text-slate-400 text-center py-2 col-span-full">No network data available</div>';
} } else {
Swal.update({
icon: 'error',
title: 'Error',
html: res.message || '<?= __('Failed to load specifications.') ?>',
showConfirmButton: true
});
}
},
error: function() {
Swal.update({
icon: 'error',
title: 'Error',
html: '<?= __('Failed to connect to the server.') ?>',
showConfirmButton: true
});
}
});
};
@@ -0,0 +1,7 @@
<?php
// Just write a patch to change to single quotes for all queries in AgentController
$content = file_get_contents('src/Controllers/AgentController.php');
$content = str_replace('LIKE \'%\"EventID\":\"3\"%\'', 'LIKE \'%EventID":"3%\'', $content); // wait, that caused syntax error before
// Instead, I will replace the double quotes in PHP with single quotes for the SQL statement
// But that's complicated to str_replace.
@@ -0,0 +1,10 @@
<?php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/src/Engine/Language.php';
use Dotenv\Dotenv;
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();
$controller = new \App\Controllers\AgentController();
$controller->getRemoteList();
?>
@@ -0,0 +1,22 @@
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once __DIR__ . '/vendor/autoload.php';
use Dotenv\Dotenv;
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();
require_once __DIR__ . '/src/Engine/Language.php';
// Mock getWazuhToken so it doesn't fail due to local SSL or connection issue
class MockController extends \App\Controllers\AgentController {
// Let's just run the original method directly
}
$c = new \App\Controllers\AgentController();
ob_start();
$c->getRemoteList();
$out = ob_get_clean();
echo "OUTPUT:\n" . $out;
?>
@@ -0,0 +1,23 @@
[xml]$xml = Get-Content "sysmonconfig.xml"
# Remove all existing NetworkConnect and DnsQuery
$xml.SelectNodes("//NetworkConnect") | ForEach-Object { [void]$_.ParentNode.RemoveChild($_) }
$xml.SelectNodes("//DnsQuery") | ForEach-Object { [void]$_.ParentNode.RemoveChild($_) }
# Create a new RuleGroup
$ruleGroup = $xml.CreateElement("RuleGroup")
$ruleGroup.SetAttribute("name", "AggressiveNetwork")
$ruleGroup.SetAttribute("groupRelation", "or")
$netNode = $xml.CreateElement("NetworkConnect")
$netNode.SetAttribute("onmatch", "exclude")
$netNode.InnerXml = "<DestinationIp condition='is'>127.0.0.1</DestinationIp><SourceIp condition='is'>127.0.0.1</SourceIp><DestinationIp condition='begin with'>192.168.</DestinationIp><DestinationIp condition='begin with'>10.</DestinationIp>"
[void]$ruleGroup.AppendChild($netNode)
$dnsNode = $xml.CreateElement("DnsQuery")
$dnsNode.SetAttribute("onmatch", "exclude")
$dnsNode.InnerXml = "<QueryName condition='end with'>.arpa</QueryName><QueryName condition='end with'>.local</QueryName>"
[void]$ruleGroup.AppendChild($dnsNode)
[void]$xml.Sysmon.EventFiltering.AppendChild($ruleGroup)
$xml.Save("sysmon_tuned.xml")
@@ -0,0 +1,35 @@
@echo off
echo ===================================================
echo Sysmon Configuration Updater for L7 Network Log
echo ===================================================
echo.
set "PS_SCRIPT=%TEMP%\update_sysmon_script.ps1"
echo $ErrorActionPreference = 'Stop' > "%PS_SCRIPT%"
echo $xmlPath = 'C:\sysmon\sysmonconfig.xml' >> "%PS_SCRIPT%"
echo if (-not (Test-Path $xmlPath)) { Write-Host "Error: Could not find $xmlPath"; exit 1 } >> "%PS_SCRIPT%"
echo [xml]$xml = Get-Content -Path $xmlPath >> "%PS_SCRIPT%"
echo Write-Host "[*] Removing old NetworkConnect rules..." >> "%PS_SCRIPT%"
echo $networkNodes = $xml.SelectNodes('//RuleGroup/NetworkConnect') >> "%PS_SCRIPT%"
echo foreach ($node in $networkNodes) { $node.ParentNode.RemoveChild($node) ^| Out-Null } >> "%PS_SCRIPT%"
echo Write-Host "[*] Removing old DnsQuery rules..." >> "%PS_SCRIPT%"
echo $dnsNodes = $xml.SelectNodes('//RuleGroup/DnsQuery') >> "%PS_SCRIPT%"
echo foreach ($node in $dnsNodes) { $node.ParentNode.RemoveChild($node) ^| Out-Null } >> "%PS_SCRIPT%"
echo Write-Host "[*] Adding new aggressive logging rules..." >> "%PS_SCRIPT%"
echo $newNet = $xml.CreateElement('NetworkConnect') >> "%PS_SCRIPT%"
echo $newNet.SetAttribute('onmatch', 'exclude') >> "%PS_SCRIPT%"
echo $xml.SelectSingleNode('//EventFiltering').AppendChild($newNet) ^| Out-Null >> "%PS_SCRIPT%"
echo $newDns = $xml.CreateElement('DnsQuery') >> "%PS_SCRIPT%"
echo $newDns.SetAttribute('onmatch', 'exclude') >> "%PS_SCRIPT%"
echo $xml.SelectSingleNode('//EventFiltering').AppendChild($newDns) ^| Out-Null >> "%PS_SCRIPT%"
echo $xml.Save($xmlPath) >> "%PS_SCRIPT%"
echo Write-Host "[*] Configuration saved to $xmlPath" -ForegroundColor Green >> "%PS_SCRIPT%"
echo Write-Host "[*] Reloading Sysmon config..." >> "%PS_SCRIPT%"
echo ^& sysmon -c $xmlPath >> "%PS_SCRIPT%"
powershell -NoProfile -ExecutionPolicy Bypass -File "%PS_SCRIPT%"
echo.
del "%PS_SCRIPT%"
pause
@@ -0,0 +1,43 @@
@echo off
echo ===================================================
echo Sysmon Configuration Updater for L7 Network Log
echo ===================================================
echo.
:: สร้างไฟล์ Script ชั่วคราว
set "PS_SCRIPT=%TEMP%\update_sysmon_script.ps1"
echo $ErrorActionPreference = 'Stop' > "%PS_SCRIPT%"
echo $possiblePaths = @('C:\sysmon\sysmonconfig.xml', 'C:\Windows\sysmonconfig.xml', 'C:\sysmonconfig.xml', '.\sysmonconfig.xml') >> "%PS_SCRIPT%"
echo $xmlPath = $null >> "%PS_SCRIPT%"
echo foreach ($p in $possiblePaths) { if (Test-Path $p) { $xmlPath = $p; break } } >> "%PS_SCRIPT%"
echo if (-not $xmlPath) { >> "%PS_SCRIPT%"
echo $xmlPath = Read-Host "Could not find sysmonconfig.xml automatically. Please enter the full path to your Sysmon config XML file" >> "%PS_SCRIPT%"
echo if (-not (Test-Path $xmlPath)) { Write-Host "Error: File still not found. Exiting."; exit 1 } >> "%PS_SCRIPT%"
echo } >> "%PS_SCRIPT%"
echo Write-Host "[*] Found configuration at: $xmlPath" -ForegroundColor Cyan >> "%PS_SCRIPT%"
echo [xml]$xml = Get-Content -Path $xmlPath >> "%PS_SCRIPT%"
echo Write-Host "[*] Removing old NetworkConnect rules..." >> "%PS_SCRIPT%"
echo $networkNodes = $xml.SelectNodes('//RuleGroup/NetworkConnect') >> "%PS_SCRIPT%"
echo foreach ($node in $networkNodes) { $node.ParentNode.RemoveChild($node) ^| Out-Null } >> "%PS_SCRIPT%"
echo Write-Host "[*] Removing old DnsQuery rules..." >> "%PS_SCRIPT%"
echo $dnsNodes = $xml.SelectNodes('//RuleGroup/DnsQuery') >> "%PS_SCRIPT%"
echo foreach ($node in $dnsNodes) { $node.ParentNode.RemoveChild($node) ^| Out-Null } >> "%PS_SCRIPT%"
echo Write-Host "[*] Adding new aggressive logging rules..." >> "%PS_SCRIPT%"
echo $newNet = $xml.CreateElement('NetworkConnect') >> "%PS_SCRIPT%"
echo $newNet.SetAttribute('onmatch', 'exclude') >> "%PS_SCRIPT%"
echo $xml.SelectSingleNode('//EventFiltering').AppendChild($newNet) ^| Out-Null >> "%PS_SCRIPT%"
echo $newDns = $xml.CreateElement('DnsQuery') >> "%PS_SCRIPT%"
echo $newDns.SetAttribute('onmatch', 'exclude') >> "%PS_SCRIPT%"
echo $xml.SelectSingleNode('//EventFiltering').AppendChild($newDns) ^| Out-Null >> "%PS_SCRIPT%"
echo $xml.Save($xmlPath) >> "%PS_SCRIPT%"
echo Write-Host "[*] Configuration saved to $xmlPath" -ForegroundColor Green >> "%PS_SCRIPT%"
echo Write-Host "[*] Reloading Sysmon config..." >> "%PS_SCRIPT%"
echo ^& sysmon -c $xmlPath >> "%PS_SCRIPT%"
:: รัน Script ที่สร้างขึ้นมา
powershell -NoProfile -ExecutionPolicy Bypass -File "%PS_SCRIPT%"
echo.
del "%PS_SCRIPT%"
pause
@@ -0,0 +1,22 @@
<?php
// autoload.php @generated by Composer
if (PHP_VERSION_ID < 50600) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, $err);
} elseif (!headers_sent()) {
echo $err;
}
}
throw new RuntimeException($err);
}
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitc448faa2bb4d17063fdd5b5dff1f2609::getLoader();
@@ -0,0 +1,28 @@
name: CI
on:
push:
pull_request:
jobs:
tests:
name: Tests on PHP ${{ matrix.php }} ${{ matrix.dependencies }}
runs-on: ubuntu-20.04
container:
image: shivammathur/node:2004
strategy:
matrix:
php: ['5.6', '7.0', '7.1', '7.2', '7.3', '7.4']
dependencies: ['', '--prefer-lowest --prefer-stable']
steps:
- name: Checkout
uses: actions/checkout@v2.3.4
- uses: shivammathur/setup-php@2.9.0
with:
php-version: ${{ matrix.php }}
- name: Install dependencies
run: composer update --no-interaction --prefer-dist ${{ matrix.dependencies }}
- name: Configure PHPUnit problem matchers
run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
- name: Run tests
run: ./vendor/bin/phpunit
@@ -0,0 +1,6 @@
.DS_Store
/composer.lock
/vendor/
tests-report/
/.idea/
.php_cs.cache
@@ -0,0 +1,57 @@
<?php
/**
* @source https://gist.github.com/codfish/c77d348820c1c6b4ebe4a66dc2291c74
*
* Rules we follow are from PSR-2 as well as the rectified PSR-2 guide.
*
* - https://github.com/FriendsOfPHP/PHP-CS-Fixer
* - https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
* - https://github.com/php-fig-rectified/fig-rectified-standards/blob/master/PSR-2-R-coding-style-guide-additions.md
*
* If something isn't addressed in either of those, some other common community rules are
* used that might not be addressed explicitly in PSR-2 in order to improve code quality
* (so that devs don't need to comment on them in Code Reviews).
*
* For instance: removing trailing white space, removing extra line breaks where
* they're not needed (back to back, beginning or end of function/class, etc.),
* adding trailing commas in the last line of an array, etc.
*/
$finder = PhpCsFixer\Finder::create()
->exclude('node_modules')
->exclude('vendor')
->in(__DIR__);
return PhpCsFixer\Config::create()
->setRules([
'@PSR2' => true,
'array_syntax' => [ 'syntax' => 'long' ],
'binary_operator_spaces' => [ 'align_equals' => false, 'align_double_arrow' => false ],
'cast_spaces' => true,
'combine_consecutive_unsets' => true,
'concat_space' => [ 'spacing' => 'one' ],
'linebreak_after_opening_tag' => true,
'no_blank_lines_after_class_opening' => true,
'no_blank_lines_after_phpdoc' => true,
'no_extra_consecutive_blank_lines' => true,
'no_trailing_comma_in_singleline_array' => true,
'no_whitespace_in_blank_line' => true,
'no_spaces_around_offset' => true,
'no_unused_imports' => true,
'no_useless_else' => true,
'no_useless_return' => true,
'no_whitespace_before_comma_in_array' => true,
'normalize_index_brace' => true,
'phpdoc_indent' => true,
'phpdoc_to_comment' => true,
'phpdoc_trim' => true,
'single_quote' => true,
'ternary_to_null_coalescing' => true,
'trailing_comma_in_multiline_array' => true,
'trim_array_spaces' => true,
'method_argument_space' => ['ensure_fully_multiline' => false],
'no_break_comment' => false,
'blank_line_before_statement' => true,
])
->setFinder($finder);
@@ -0,0 +1,89 @@
# Changelog for `bramus/router`
## 1.next ????.??.??
## 1.6.1 2021.11.19
- Fixed: Fix `trigger404()` to work without custom 404 handler _([#169](https://github.com/bramus/router/pull/169))_ _(@mjoris)_
## 1.6 2021.07.23
- Added: Ability to set multiple 404s, depending on the route prefix _(@uvulpos)_
## 1.5 2020.10.26
- Fixed: Correctly invoke static/non-static class methods _(@bramus)_
- Fixed: Fix PHP 5.3 support _(@cikal)_
- Fixed: Fix arguments in demo _(@khromov)_
- Fixed: Fix #72 _(@acicali)_
- Added: PHP 7.4 support _(@ShaneMcC)_
- Added: Ability to externally trigger a 404 _(@PlanetTheCloud)_
## 1.4.2 2019.02.27
- Fixed: Play nice with emoji in base paths ([ref](https://github.com/bramus/router/commit/8692190532db269882f83d27cea95d4f22a50da2#commitcomment-32492636), [ref](https://github.com/bramus/router/commit/492444d84fde7e54551ff0bf8ca79ff9292094da#commitcomment-32496820)) _(@bramus)_
- Added: Extra Tests _(@bramus)_
## 1.4.1 2019.02.26
- Fixed: Fix bug where Cyrillic charges and Emojis in placeholder were urlencoded (see [#80](https://github.com/bramus/router/issues/80#issuecomment-467154490)) _(@bramus)_
- Fixed: Make `bramus/router` play nice with situations where the entry script and entry URLs are not coupled (see [#82](https://github.com/bramus/router/issues/82#issuecomment-466956078)) _(@bramus)_
- Changed: Changed visibility of `getBasePath` and `getCurrentUri` to being `public` _(@bramus)_
## 1.4 2019.02.18
- Added: Support for Cyrillic chars and Emoji in placeholder values and placeholder names (see [#80](https://github.com/bramus/router/issues/80)) _(@bramus)_
- Added: `composer test` shorthand _(@bramus)_
- Added: Changelog _(@bramus)_
- Changed: Documentation Improvements _(@bramus)_
## 1.3.1 2017.12.22
- Added: Extra Tests _(@bramus)_
- Changed: Documentation Improvements _(@artyuum)_
## 1.3 2017.12.21
- Added: Support `Class@method` callbacks in `set404()` _(@bramus)_
- Changed: Refactored callback invocation _(@bramus)_
- Changed: Documentation Improvements _(@artyuum)_
## 1.2.1 2017.10.06
- Changed: Documentation Improvements _(@bramus)_
## 1.2 2017.10.06
- Added: Support route matching using _“placeholders”_ (e.g. curly braces) _(@ovflowd)_
- Added: Default Namespace Capability using `setNamespace()`, for use with `Class@Method` calls _(@ovflowd)_
- Added: Extra Tests _(@bramus)_
- Bugfix: Make sure callable are actually callable _(@ovflowd)_
- Demo: Added a multilang demo _(@bramus)_
- Changed: Documentation Improvements _(@lai0n)_
## 1.1 2016.05.26
- Added: Return `true` if a route was handled, `false` otherwise _(@tleb)_
- Added: `getBasePath()` _(@ovflowd)_
- Added: Support `Class@Method` calls _(@ovflowd)_
- Changed: Tweak a few method signaturs so that they're protected _(@tleb)_
- Changed: Documentation Improvements _(@tleb)_
## 1.0 2015.02.04
- First 1.x release
## _(Unversioned Releases)_ 2013.04.08 - 2015.02.04
- Initial release with suppport for:
- Static and Dynamic Route Handling
- Shorthands: `get()`, `post()`, `put()`, `delete()`, and `options()`
- Before Route Middlewares / Before Route Middlewares: `before()`
- After Router Middlewares / Run Callback
- Added: Optional Route Patterns
- Added: Subrouting (mount callables onto a subroute/prefix)
- Added: `patch()` shorthand
- Added: Support for `X-HTTP-Method-Override` header
- Bugfix: Use the HTTP version as found in `['SERVER_PROTOCOL']`
- Bugfix: Nested Subpatterns / Multiple Matching _(@jbleuzen)_
@@ -0,0 +1,19 @@
Copyright (c) 2013 Bram(us) Van Damme - http://www.bram.us/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,472 @@
# bramus/router
[![Build Status](https://github.com/bramus/router/workflows/CI/badge.svg)](https://github.com/bramus/router/actions) [![Source](http://img.shields.io/badge/source-bramus/router-blue.svg?style=flat-square)](https://github.com/bramus/router) [![Version](https://img.shields.io/packagist/v/bramus/router.svg?style=flat-square)](https://packagist.org/packages/bramus/router) [![Downloads](https://img.shields.io/packagist/dt/bramus/router.svg?style=flat-square)](https://packagist.org/packages/bramus/router/stats) [![License](https://img.shields.io/packagist/l/bramus/router.svg?style=flat-square)](https://github.com/bramus/router/blob/master/LICENSE)
A lightweight and simple object oriented PHP Router.
Built by Bram(us) Van Damme _([https://www.bram.us](https://www.bram.us))_ and [Contributors](https://github.com/bramus/router/graphs/contributors)
## Features
- Supports `GET`, `POST`, `PUT`, `DELETE`, `OPTIONS`, `PATCH` and `HEAD` request methods
- [Routing shorthands such as `get()`, `post()`, `put()`, …](#routing-shorthands)
- [Static Route Patterns](#route-patterns)
- Dynamic Route Patterns: [Dynamic PCRE-based Route Patterns](#dynamic-pcre-based-route-patterns) or [Dynamic Placeholder-based Route Patterns](#dynamic-placeholder-based-route-patterns)
- [Optional Route Subpatterns](#optional-route-subpatterns)
- [Supports `X-HTTP-Method-Override` header](#overriding-the-request-method)
- [Subrouting / Mounting Routes](#subrouting--mounting-routes)
- [Allowance of `Class@Method` calls](#classmethod-calls)
- [Custom 404 handling](#custom-404)
- [Before Route Middlewares](#before-route-middlewares)
- [Before Router Middlewares / Before App Middlewares](#before-router-middlewares)
- [After Router Middleware / After App Middleware (Finish Callback)](#after-router-middleware--run-callback)
- [Works fine in subfolders](#subfolder-support)
## Prerequisites/Requirements
- PHP 5.3 or greater
- [URL Rewriting](https://gist.github.com/bramus/5332525)
## Installation
Installation is possible using Composer
```
composer require bramus/router ~1.6
```
## Demo
A demo is included in the `demo` subfolder. Serve it using your favorite web server, or using PHP 5.4+'s built-in server by executing `php -S localhost:8080` on the shell. A `.htaccess` for use with Apache is included.
Additionally a demo of a mutilingual router is also included. This can be found in the `demo-multilang` subfolder and can be ran in the same manner as the normal demo.
## Usage
Create an instance of `\Bramus\Router\Router`, define some routes onto it, and run it.
```php
// Require composer autoloader
require __DIR__ . '/vendor/autoload.php';
// Create Router instance
$router = new \Bramus\Router\Router();
// Define routes
// ...
// Run it!
$router->run();
```
### Routing
Hook __routes__ (a combination of one or more HTTP methods and a pattern) using `$router->match(method(s), pattern, function)`:
```php
$router->match('GET|POST', 'pattern', function() { });
```
`bramus/router` supports `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD` _(see [note](#a-note-on-making-head-requests))_, and `OPTIONS` HTTP request methods. Pass in a single request method, or multiple request methods separated by `|`.
When a route matches against the current URL (e.g. `$_SERVER['REQUEST_URI']`), the attached __route handling function__ will be executed. The route handling function must be a [callable](http://php.net/manual/en/language.types.callable.php). Only the first route matched will be handled. When no matching route is found, a 404 handler will be executed.
### Routing Shorthands
Shorthands for single request methods are provided:
```php
$router->get('pattern', function() { /* ... */ });
$router->post('pattern', function() { /* ... */ });
$router->put('pattern', function() { /* ... */ });
$router->delete('pattern', function() { /* ... */ });
$router->options('pattern', function() { /* ... */ });
$router->patch('pattern', function() { /* ... */ });
```
You can use this shorthand for a route that can be accessed using any method:
```php
$router->all('pattern', function() { });
```
Note: Routes must be hooked before `$router->run();` is being called.
Note: There is no shorthand for `match()` as `bramus/router` will internally re-route such requrests to their equivalent `GET` request, in order to comply with RFC2616 _(see [note](#a-note-on-making-head-requests))_.
### Route Patterns
Route Patterns can be static or dynamic:
- __Static Route Patterns__ contain no dynamic parts and must match exactly against the `path` part of the current URL.
- __Dynamic Route Patterns__ contain dynamic parts that can vary per request. The varying parts are named __subpatterns__ and are defined using either Perl-compatible regular expressions (PCRE) or by using __placeholders__
#### Static Route Patterns
A static route pattern is a regular string representing a URI. It will be compared directly against the `path` part of the current URL.
Examples:
- `/about`
- `/contact`
Usage Examples:
```php
// This route handling function will only be executed when visiting http(s)://www.example.org/about
$router->get('/about', function() {
echo 'About Page Contents';
});
```
#### Dynamic PCRE-based Route Patterns
This type of Route Patterns contain dynamic parts which can vary per request. The varying parts are named __subpatterns__ and are defined using regular expressions.
Examples:
- `/movies/(\d+)`
- `/profile/(\w+)`
Commonly used PCRE-based subpatterns within Dynamic Route Patterns are:
- `\d+` = One or more digits (0-9)
- `\w+` = One or more word characters (a-z 0-9 _)
- `[a-z0-9_-]+` = One or more word characters (a-z 0-9 _) and the dash (-)
- `.*` = Any character (including `/`), zero or more
- `[^/]+` = Any character but `/`, one or more
Note: The [PHP PCRE Cheat Sheet](https://courses.cs.washington.edu/courses/cse154/15sp/cheat-sheets/php-regex-cheat-sheet.pdf) might come in handy.
The __subpatterns__ defined in Dynamic PCRE-based Route Patterns are converted to parameters which are passed into the route handling function. Prerequisite is that these subpatterns need to be defined as __parenthesized subpatterns__, which means that they should be wrapped between parens:
```php
// Bad
$router->get('/hello/\w+', function($name) {
echo 'Hello ' . htmlentities($name);
});
// Good
$router->get('/hello/(\w+)', function($name) {
echo 'Hello ' . htmlentities($name);
});
```
Note: The leading `/` at the very beginning of a route pattern is not mandatory, but is recommended.
When multiple subpatterns are defined, the resulting __route handling parameters__ are passed into the route handling function in the order they are defined in:
```php
$router->get('/movies/(\d+)/photos/(\d+)', function($movieId, $photoId) {
echo 'Movie #' . $movieId . ', photo #' . $photoId;
});
```
#### Dynamic Placeholder-based Route Patterns
This type of Route Patterns are the same as __Dynamic PCRE-based Route Patterns__, but with one difference: they don't use regexes to do the pattern matching but they use the more easy __placeholders__ instead. Placeholders are strings surrounded by curly braces, e.g. `{name}`. You don't need to add parens around placeholders.
Examples:
- `/movies/{id}`
- `/profile/{username}`
Placeholders are easier to use than PRCEs, but offer you less control as they internally get translated to a PRCE that matches any character (`.*`).
```php
$router->get('/movies/{movieId}/photos/{photoId}', function($movieId, $photoId) {
echo 'Movie #' . $movieId . ', photo #' . $photoId;
});
```
Note: the name of the placeholder does not need to match with the name of the parameter that is passed into the route handling function:
```php
$router->get('/movies/{foo}/photos/{bar}', function($movieId, $photoId) {
echo 'Movie #' . $movieId . ', photo #' . $photoId;
});
```
### Optional Route Subpatterns
Route subpatterns can be made optional by making the subpatterns optional by adding a `?` after them. Think of blog URLs in the form of `/blog(/year)(/month)(/day)(/slug)`:
```php
$router->get(
'/blog(/\d+)?(/\d+)?(/\d+)?(/[a-z0-9_-]+)?',
function($year = null, $month = null, $day = null, $slug = null) {
if (!$year) { echo 'Blog overview'; return; }
if (!$month) { echo 'Blog year overview'; return; }
if (!$day) { echo 'Blog month overview'; return; }
if (!$slug) { echo 'Blog day overview'; return; }
echo 'Blogpost ' . htmlentities($slug) . ' detail';
}
);
```
The code snippet above responds to the URLs `/blog`, `/blog/year`, `/blog/year/month`, `/blog/year/month/day`, and `/blog/year/month/day/slug`.
Note: With optional parameters it is important that the leading `/` of the subpatterns is put inside the subpattern itself. Don't forget to set default values for the optional parameters.
The code snipped above unfortunately also responds to URLs like `/blog/foo` and states that the overview needs to be shown - which is incorrect. Optional subpatterns can be made successive by extending the parenthesized subpatterns so that they contain the other optional subpatterns: The pattern should resemble `/blog(/year(/month(/day(/slug))))` instead of the previous `/blog(/year)(/month)(/day)(/slug)`:
```php
$router->get('/blog(/\d+(/\d+(/\d+(/[a-z0-9_-]+)?)?)?)?', function($year = null, $month = null, $day = null, $slug = null) {
// ...
});
```
Note: It is highly recommended to __always__ define successive optional parameters.
To make things complete use [quantifiers](http://www.php.net/manual/en/regexp.reference.repetition.php) to require the correct amount of numbers in the URL:
```php
$router->get('/blog(/\d{4}(/\d{2}(/\d{2}(/[a-z0-9_-]+)?)?)?)?', function($year = null, $month = null, $day = null, $slug = null) {
// ...
});
```
### Subrouting / Mounting Routes
Use `$router->mount($baseroute, $fn)` to mount a collection of routes onto a subroute pattern. The subroute pattern is prefixed onto all following routes defined in the scope. e.g. Mounting a callback `$fn` onto `/movies` will prefix `/movies` onto all following routes.
```php
$router->mount('/movies', function() use ($router) {
// will result in '/movies/'
$router->get('/', function() {
echo 'movies overview';
});
// will result in '/movies/id'
$router->get('/(\d+)', function($id) {
echo 'movie id ' . htmlentities($id);
});
});
```
Nesting of subroutes is possible, just define a second `$router->mount()` in the callable that's already contained within a preceding `$router->mount()`.
### `Class@Method` calls
We can route to the class action like so:
```php
$router->get('/(\d+)', '\App\Controllers\User@showProfile');
```
When a request matches the specified route URI, the `showProfile` method on the `User` class will be executed. The defined route parameters will be passed to the class method.
The method can be static (recommended) or non-static (not-recommended). In case of a non-static method, a new instance of the class will be created.
If most/all of your handling classes are in one and the same namespace, you can set the default namespace to use on your router instance via `setNamespace()`
```php
$router->setNamespace('\App\Controllers');
$router->get('/users/(\d+)', 'User@showProfile');
$router->get('/cars/(\d+)', 'Car@showProfile');
```
### Custom 404
The default 404 handler sets a 404 status code and exits. You can override this default 404 handler by using `$router->set404(callable);`
```php
$router->set404(function() {
header('HTTP/1.1 404 Not Found');
// ... do something special here
});
```
You can also define multiple custom routes e.x. you want to define an `/api` route, you can print a custom 404 page:
```php
$router->set404('/api(/.*)?', function() {
header('HTTP/1.1 404 Not Found');
header('Content-Type: application/json');
$jsonArray = array();
$jsonArray['status'] = "404";
$jsonArray['status_text'] = "route not defined";
echo json_encode($jsonArray);
});
```
Also supported are `Class@Method` callables:
```php
$router->set404('\App\Controllers\Error@notFound');
```
The 404 handler will be executed when no route pattern was matched to the current URL.
💡 You can also manually trigger the 404 handler by calling `$router->trigger404()`
```php
$router->get('/([a-z0-9-]+)', function($id) use ($router) {
if (!Posts::exists($id)) {
$router->trigger404();
return;
}
// …
});
```
### Before Route Middlewares
`bramus/router` supports __Before Route Middlewares__, which are executed before the route handling is processed.
Like route handling functions, you hook a handling function to a combination of one or more HTTP request methods and a specific route pattern.
```php
$router->before('GET|POST', '/admin/.*', function() {
if (!isset($_SESSION['user'])) {
header('location: /auth/login');
exit();
}
});
```
Unlike route handling functions, more than one before route middleware is executed when more than one route match is found.
### Before Router Middlewares
Before route middlewares are route specific. Using a general route pattern (viz. _all URLs_), they can become __Before Router Middlewares__ _(in other projects sometimes referred to as before app middlewares)_ which are always executed, no matter what the requested URL is.
```php
$router->before('GET', '/.*', function() {
// ... this will always be executed
});
```
### After Router Middleware / Run Callback
Run one (1) middleware function, name the __After Router Middleware__ _(in other projects sometimes referred to as after app middlewares)_ after the routing was processed. Just pass it along the `$router->run()` function. The run callback is route independent.
```php
$router->run(function() { });
```
Note: If the route handling function has `exit()`ed the run callback won't be run.
### Overriding the request method
Use `X-HTTP-Method-Override` to override the HTTP Request Method. Only works when the original Request Method is `POST`. Allowed values for `X-HTTP-Method-Override` are `PUT`, `DELETE`, or `PATCH`.
### Subfolder support
Out-of-the box `bramus/router` will run in any (sub)folder you place it into … no adjustments to your code are needed. You can freely move your _entry script_ `index.php` around, and the router will automatically adapt itself to work relatively from the current folder's path by mounting all routes onto that __basePath__.
Say you have a server hosting the domain `www.example.org` using `public_html/` as its document root, with this little _entry script_ `index.php`:
```php
$router->get('/', function() { echo 'Index'; });
$router->get('/hello', function() { echo 'Hello!'; });
```
- If your were to place this file _(along with its accompanying `.htaccess` file or the like)_ at the document root level (e.g. `public_html/index.php`), `bramus/router` will mount all routes onto the domain root (e.g. `/`) and thus respond to `https://www.example.org/` and `https://www.example.org/hello`.
- If you were to move this file _(along with its accompanying `.htaccess` file or the like)_ into a subfolder (e.g. `public_html/demo/index.php`), `bramus/router` will mount all routes onto the current path (e.g. `/demo`) and thus repsond to `https://www.example.org/demo` and `https://www.example.org/demo/hello`. There's **no** need for `$router->mount(…)` in this case.
#### Disabling subfolder support
In case you **don't** want `bramus/router` to automatically adapt itself to the folder its being placed in, it's possible to manually override the _basePath_ by calling `setBasePath()`. This is necessary in the _(uncommon)_ situation where your _entry script_ and your _entry URLs_ are not tightly coupled _(e.g. when the entry script is placed into a subfolder that does not need be part of the URLs it responds to)_.
```php
// Override auto base path detection
$router->setBasePath('/');
$router->get('/', function() { echo 'Index'; });
$router->get('/hello', function() { echo 'Hello!'; });
$router->run();
```
If you were to place this file into a subfolder (e.g. `public_html/some/sub/folder/index.php`), it will still mount the routes onto the domain root (e.g. `/`) and thus respond to `https://www.example.org/` and `https://www.example.org/hello` _(given that your `.htaccess` file placed at the document root level rewrites requests to it)_
## Integration with other libraries
Integrate other libraries with `bramus/router` by making good use of the `use` keyword to pass dependencies into the handling functions.
```php
$tpl = new \Acme\Template\Template();
$router->get('/', function() use ($tpl) {
$tpl->load('home.tpl');
$tpl->setdata(array(
'name' => 'Bramus!'
));
});
$router->run(function() use ($tpl) {
$tpl->display();
});
```
Given this structure it is still possible to manipulate the output from within the After Router Middleware
## A note on working with PUT
There's no such thing as `$_PUT` in PHP. One must fake it:
```php
$router->put('/movies/(\d+)', function($id) {
// Fake $_PUT
$_PUT = array();
parse_str(file_get_contents('php://input'), $_PUT);
// ...
});
```
## A note on making HEAD requests
When making `HEAD` requests all output will be buffered to prevent any content trickling into the response body, as defined in [RFC2616 (Hypertext Transfer Protocol -- HTTP/1.1)](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4):
> The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.
To achieve this, `bramus/router` but will internally re-route `HEAD` requests to their equivalent `GET` request and automatically suppress all output.
## Unit Testing & Code Coverage
`bramus/router` ships with unit tests using [PHPUnit](https://github.com/sebastianbergmann/phpunit/).
- If PHPUnit is installed globally run `phpunit` to run the tests.
- If PHPUnit is not installed globally, install it locally throuh composer by running `composer install --dev`. Run the tests themselves by calling `vendor/bin/phpunit`.
The included `composer.json` will also install `php-code-coverage` which allows one to generate a __Code Coverage Report__. Run `phpunit --coverage-html ./tests-report` (XDebug required), a report will be placed into the `tests-report` subfolder.
## Acknowledgements
`bramus/router` is inspired upon [Klein](https://github.com/chriso/klein.php), [Ham](https://github.com/radiosilence/Ham), and [JREAM/route](https://bitbucket.org/JREAM/route) . Whilst Klein provides lots of features it is not object oriented. Whilst Ham is Object Oriented, it's bad at _separation of concerns_ as it also provides templating within the routing class. Whilst JREAM/route is a good starting point it is limited in what it does (only GET routes for example).
## License
`bramus/router` is released under the MIT public license. See the enclosed `LICENSE` for details.
@@ -0,0 +1,31 @@
{
"name": "bramus/router",
"description": "A lightweight and simple object oriented PHP Router",
"keywords": ["router", "routing"],
"homepage": "https://github.com/bramus/router",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Bram(us) Van Damme",
"email": "bramus@bram.us",
"homepage": "http://www.bram.us"
}
],
"require": {
"php": ">=5.3.0"
},
"require-dev": {
"phpunit/phpunit": "~4.8",
"phpunit/php-code-coverage": "~2.0",
"friendsofphp/php-cs-fixer": "~2.14"
},
"autoload": {
"psr-0": {"Bramus": "src/"}
},
"scripts": {
"test": "./vendor/bin/phpunit --colors=always",
"lint": "php-cs-fixer fix --diff --dry-run",
"fix": "php-cs-fixer fix"
}
}
@@ -0,0 +1,4 @@
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
@@ -0,0 +1,82 @@
<?php
// In case one is using PHP 5.4+'s built-in server
$filename = __DIR__ . preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);
if (php_sapi_name() === 'cli-server' && is_file($filename)) {
return false;
}
// Include the Router class
// @note: it's recommended to just use the composer autoloader when working with other packages too
require_once __DIR__ . '/../src/Bramus/Router/Router.php';
/**
* A Multilingual Router
*/
class MultilangRouter extends \Bramus\Router\Router
{
/**
* The Default langauge
* @var string
*/
private $defaultLanguage;
/**
* List of allowed languages
* @var array
*/
private $allowedLanguages = array();
/**
* A Multilingual Router
* @param array $allowedLanguages
* @param string $defaultLanguage
*/
public function __construct(array $allowedLanguages, $defaultLanguage)
{
// Store passed in data
$this->allowedLanguages = $allowedLanguages;
$this->defaultLanguage = (in_array($defaultLanguage, $allowedLanguages) ? $defaultLanguage : $allowedLanguages[0]);
// Visiting the root? Redirect to the default language index
$this->match('GET|POST|PUT|DELETE|HEAD', '/', function () {
header('location: /' . $this->defaultLanguage);
exit();
});
// Create a before handler to make sure the language checks out when visiting anything but the root.
// If the language doesn't check out, redirect to the default language index
$this->before('GET|POST|PUT|DELETE|HEAD', '/([a-z0-9_-]+)(/.*)?', function ($language, $slug = null) {
// The given language does not appear in the array of allowed languages
if (!in_array($language, $this->allowedLanguages)) {
header('location: /' . $this->defaultLanguage);
exit();
}
});
}
}
// Create a Router
$router = new MultilangRouter(
array('en','nl','fr'), //= allowed languages
'nl' // = default language
);
$router->get('/([a-z0-9_-]+)', function ($language) {
exit('This is the ' . htmlentities($language) . ' index');
});
$router->get('/([a-z0-9_-]+)/([a-z0-9_-]+)', function ($language, $slug) {
exit('This is the ' . htmlentities($language) . ' version of ' . htmlentities($slug));
});
$router->get('/([a-z0-9_-]+)/(.*)', function ($language, $slug) {
exit('This is the ' . htmlentities($language) . ' version of ' . htmlentities($slug) . ' (multiple segments allowed)');
});
// Thunderbirds are go!
$router->run();
// EOF
@@ -0,0 +1,4 @@
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
@@ -0,0 +1,134 @@
<?php
// In case one is using PHP 5.4's built-in server
$filename = __DIR__ . preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);
if (php_sapi_name() === 'cli-server' && is_file($filename)) {
return false;
}
// Include the Router class
// @note: it's recommended to just use the composer autoloader when working with other packages too
require_once __DIR__ . '/../src/Bramus/Router/Router.php';
// Create a Router
$router = new \Bramus\Router\Router();
// Custom 404 Handler
$router->set404(function () {
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
echo '404, route not found!';
});
// custom 404
$router->set404('/test(/.*)?', function () {
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
echo '<h1><mark>404, route not found!</mark></h1>';
});
$router->set404('/api(/.*)?', function() {
header('HTTP/1.1 404 Not Found');
header('Content-Type: application/json');
$jsonArray = array();
$jsonArray['status'] = "404";
$jsonArray['status_text'] = "route not defined";
echo json_encode($jsonArray);
});
// Before Router Middleware
$router->before('GET', '/.*', function () {
header('X-Powered-By: bramus/router');
});
// Static route: / (homepage)
$router->get('/', function () {
echo '<h1>bramus/router</h1>
<p>Try these routes:<p>
<ul>
<li><a href="/hello/joe">/hello/<em>name</em></a></li>
<li><a href="/blog">/blog</a></li>
<li><a href="/blog/'.date('Y').'">/blog/<em>year</em></a></li>
<li><a href="/blog/'.date('Y').'/'.date('m').'">/blog/<em>year</em>/<em>month</em></a></li>
<li><a href="/blog/'.date('Y').'/'.date('m').'/'.date('d').'">/blog/<em>year</em>/<em>month</em>/<em>day</em></a></li>
<li><a href="/movies">/movies</a></li>
<li><a href="/movies/23">/movies/<em>id</em></a></li>
</ul>
<br><br>
<p>Custom error routes</p>
<ul>
<li><a href="/something">/*</a> <em>Normal 404</em></li>
<li><a href="/test">/test/*</a> <em>Custom 404</em></li>
<li><a href="/api/getUser">/api/getUser</a> <em>API 404</em></li>
</ul>
';
});
// Static route: /hello
$router->get('/hello', function () {
echo '<h1>bramus/router</h1><p>Visit <code>/hello/<em>name</em></code> to get your Hello World mojo on!</p>';
});
// Dynamic route: /hello/name
$router->get('/hello/(\w+)', function ($name) {
echo 'Hello ' . htmlentities($name);
});
// Dynamic route: /ohai/name/in/parts
$router->get('/ohai/(.*)', function ($url) {
echo 'Ohai ' . htmlentities($url);
});
// Dynamic route with (successive) optional subpatterns: /blog(/year(/month(/day(/slug))))
$router->get('/blog(/\d{4}(/\d{2}(/\d{2}(/[a-z0-9_-]+)?)?)?)?', function ($year = null, $month = null, $day = null, $slug = null) {
if (!$year) {
echo 'Blog overview';
return;
}
if (!$month) {
echo 'Blog year overview (' . $year . ')';
return;
}
if (!$day) {
echo 'Blog month overview (' . $year . '-' . $month . ')';
return;
}
if (!$slug) {
echo 'Blog day overview (' . $year . '-' . $month . '-' . $day . ')';
return;
}
echo 'Blogpost ' . htmlentities($slug) . ' detail (' . $year . '-' . $month . '-' . $day . ')';
});
// Subrouting
$router->mount('/movies', function () use ($router) {
// will result in '/movies'
$router->get('/', function () {
echo 'movies overview';
});
// will result in '/movies'
$router->post('/', function () {
echo 'add movie';
});
// will result in '/movies/id'
$router->get('/(\d+)', function ($id) {
echo 'movie id ' . htmlentities($id);
});
// will result in '/movies/id'
$router->put('/(\d+)', function ($id) {
echo 'Update movie id ' . htmlentities($id);
});
});
// Thunderbirds are go!
$router->run();
// EOF
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false" syntaxCheck="false" bootstrap="tests/bootstrap.php">
<testsuites>
<testsuite name="Router Tests">
<directory>tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
</phpunit>
@@ -0,0 +1,535 @@
<?php
/**
* @author Bram(us) Van Damme <bramus@bram.us>
* @copyright Copyright (c), 2013 Bram(us) Van Damme
* @license MIT public license
*/
namespace Bramus\Router;
/**
* Class Router.
*/
class Router
{
/**
* @var array The route patterns and their handling functions
*/
private $afterRoutes = array();
/**
* @var array The before middleware route patterns and their handling functions
*/
private $beforeRoutes = array();
/**
* @var array [object|callable] The function to be executed when no route has been matched
*/
protected $notFoundCallback = [];
/**
* @var string Current base route, used for (sub)route mounting
*/
private $baseRoute = '';
/**
* @var string The Request Method that needs to be handled
*/
private $requestedMethod = '';
/**
* @var string The Server Base Path for Router Execution
*/
private $serverBasePath;
/**
* @var string Default Controllers Namespace
*/
private $namespace = '';
/**
* Store a before middleware route and a handling function to be executed when accessed using one of the specified methods.
*
* @param string $methods Allowed methods, | delimited
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function before($methods, $pattern, $fn)
{
$pattern = $this->baseRoute . '/' . trim($pattern, '/');
$pattern = $this->baseRoute ? rtrim($pattern, '/') : $pattern;
foreach (explode('|', $methods) as $method) {
$this->beforeRoutes[$method][] = array(
'pattern' => $pattern,
'fn' => $fn,
);
}
}
/**
* Store a route and a handling function to be executed when accessed using one of the specified methods.
*
* @param string $methods Allowed methods, | delimited
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function match($methods, $pattern, $fn)
{
$pattern = $this->baseRoute . '/' . trim($pattern, '/');
$pattern = $this->baseRoute ? rtrim($pattern, '/') : $pattern;
foreach (explode('|', $methods) as $method) {
$this->afterRoutes[$method][] = array(
'pattern' => $pattern,
'fn' => $fn,
);
}
}
/**
* Shorthand for a route accessed using any method.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function all($pattern, $fn)
{
$this->match('GET|POST|PUT|DELETE|OPTIONS|PATCH|HEAD', $pattern, $fn);
}
/**
* Shorthand for a route accessed using GET.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function get($pattern, $fn)
{
$this->match('GET', $pattern, $fn);
}
/**
* Shorthand for a route accessed using POST.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function post($pattern, $fn)
{
$this->match('POST', $pattern, $fn);
}
/**
* Shorthand for a route accessed using PATCH.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function patch($pattern, $fn)
{
$this->match('PATCH', $pattern, $fn);
}
/**
* Shorthand for a route accessed using DELETE.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function delete($pattern, $fn)
{
$this->match('DELETE', $pattern, $fn);
}
/**
* Shorthand for a route accessed using PUT.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function put($pattern, $fn)
{
$this->match('PUT', $pattern, $fn);
}
/**
* Shorthand for a route accessed using OPTIONS.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function options($pattern, $fn)
{
$this->match('OPTIONS', $pattern, $fn);
}
/**
* Mounts a collection of callbacks onto a base route.
*
* @param string $baseRoute The route sub pattern to mount the callbacks on
* @param callable $fn The callback method
*/
public function mount($baseRoute, $fn)
{
// Track current base route
$curBaseRoute = $this->baseRoute;
// Build new base route string
$this->baseRoute .= $baseRoute;
// Call the callable
call_user_func($fn);
// Restore original base route
$this->baseRoute = $curBaseRoute;
}
/**
* Get all request headers.
*
* @return array The request headers
*/
public function getRequestHeaders()
{
$headers = array();
// If getallheaders() is available, use that
if (function_exists('getallheaders')) {
$headers = getallheaders();
// getallheaders() can return false if something went wrong
if ($headers !== false) {
return $headers;
}
}
// Method getallheaders() not available or went wrong: manually extract 'm
foreach ($_SERVER as $name => $value) {
if ((substr($name, 0, 5) == 'HTTP_') || ($name == 'CONTENT_TYPE') || ($name == 'CONTENT_LENGTH')) {
$headers[str_replace(array(' ', 'Http'), array('-', 'HTTP'), ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
/**
* Get the request method used, taking overrides into account.
*
* @return string The Request method to handle
*/
public function getRequestMethod()
{
// Take the method as found in $_SERVER
$method = $_SERVER['REQUEST_METHOD'];
// If it's a HEAD request override it to being GET and prevent any output, as per HTTP Specification
// @url http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4
if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {
ob_start();
$method = 'GET';
}
// If it's a POST request, check for a method override header
elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
$headers = $this->getRequestHeaders();
if (isset($headers['X-HTTP-Method-Override']) && in_array($headers['X-HTTP-Method-Override'], array('PUT', 'DELETE', 'PATCH'))) {
$method = $headers['X-HTTP-Method-Override'];
}
}
return $method;
}
/**
* Set a Default Lookup Namespace for Callable methods.
*
* @param string $namespace A given namespace
*/
public function setNamespace($namespace)
{
if (is_string($namespace)) {
$this->namespace = $namespace;
}
}
/**
* Get the given Namespace before.
*
* @return string The given Namespace if exists
*/
public function getNamespace()
{
return $this->namespace;
}
/**
* Execute the router: Loop all defined before middleware's and routes, and execute the handling function if a match was found.
*
* @param object|callable $callback Function to be executed after a matching route was handled (= after router middleware)
*
* @return bool
*/
public function run($callback = null)
{
// Define which method we need to handle
$this->requestedMethod = $this->getRequestMethod();
// Handle all before middlewares
if (isset($this->beforeRoutes[$this->requestedMethod])) {
$this->handle($this->beforeRoutes[$this->requestedMethod]);
}
// Handle all routes
$numHandled = 0;
if (isset($this->afterRoutes[$this->requestedMethod])) {
$numHandled = $this->handle($this->afterRoutes[$this->requestedMethod], true);
}
// If no route was handled, trigger the 404 (if any)
if ($numHandled === 0) {
$this->trigger404($this->afterRoutes[$this->requestedMethod]);
} // If a route was handled, perform the finish callback (if any)
else {
if ($callback && is_callable($callback)) {
$callback();
}
}
// If it originally was a HEAD request, clean up after ourselves by emptying the output buffer
if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {
ob_end_clean();
}
// Return true if a route was handled, false otherwise
return $numHandled !== 0;
}
/**
* Set the 404 handling function.
*
* @param object|callable|string $match_fn The function to be executed
* @param object|callable $fn The function to be executed
*/
public function set404($match_fn, $fn = null)
{
if (!is_null($fn)) {
$this->notFoundCallback[$match_fn] = $fn;
} else {
$this->notFoundCallback['/'] = $match_fn;
}
}
/**
* Triggers 404 response
*
* @param string $pattern A route pattern such as /about/system
*/
public function trigger404($match = null){
// Counter to keep track of the number of routes we've handled
$numHandled = 0;
// handle 404 pattern
if (count($this->notFoundCallback) > 0)
{
// loop fallback-routes
foreach ($this->notFoundCallback as $route_pattern => $route_callable) {
// matches result
$matches = [];
// check if there is a match and get matches as $matches (pointer)
$is_match = $this->patternMatches($route_pattern, $this->getCurrentUri(), $matches, PREG_OFFSET_CAPTURE);
// is fallback route match?
if ($is_match) {
// Rework matches to only contain the matches, not the orig string
$matches = array_slice($matches, 1);
// Extract the matched URL parameters (and only the parameters)
$params = array_map(function ($match, $index) use ($matches) {
// We have a following parameter: take the substring from the current param position until the next one's position (thank you PREG_OFFSET_CAPTURE)
if (isset($matches[$index + 1]) && isset($matches[$index + 1][0]) && is_array($matches[$index + 1][0])) {
if ($matches[$index + 1][0][1] > -1) {
return trim(substr($match[0][0], 0, $matches[$index + 1][0][1] - $match[0][1]), '/');
}
} // We have no following parameters: return the whole lot
return isset($match[0][0]) && $match[0][1] != -1 ? trim($match[0][0], '/') : null;
}, $matches, array_keys($matches));
$this->invoke($route_callable);
++$numHandled;
}
}
}
if (($numHandled == 0) && (isset($this->notFoundCallback['/']))) {
$this->invoke($this->notFoundCallback['/']);
} elseif ($numHandled == 0) {
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
}
}
/**
* Replace all curly braces matches {} into word patterns (like Laravel)
* Checks if there is a routing match
*
* @param $pattern
* @param $uri
* @param $matches
* @param $flags
*
* @return bool -> is match yes/no
*/
private function patternMatches($pattern, $uri, &$matches, $flags)
{
// Replace all curly braces matches {} into word patterns (like Laravel)
$pattern = preg_replace('/\/{(.*?)}/', '/(.*?)', $pattern);
// we may have a match!
return boolval(preg_match_all('#^' . $pattern . '$#', $uri, $matches, PREG_OFFSET_CAPTURE));
}
/**
* Handle a a set of routes: if a match is found, execute the relating handling function.
*
* @param array $routes Collection of route patterns and their handling functions
* @param bool $quitAfterRun Does the handle function need to quit after one route was matched?
*
* @return int The number of routes handled
*/
private function handle($routes, $quitAfterRun = false)
{
// Counter to keep track of the number of routes we've handled
$numHandled = 0;
// The current page URL
$uri = $this->getCurrentUri();
// Loop all routes
foreach ($routes as $route) {
// get routing matches
$is_match = $this->patternMatches($route['pattern'], $uri, $matches, PREG_OFFSET_CAPTURE);
// is there a valid match?
if ($is_match) {
// Rework matches to only contain the matches, not the orig string
$matches = array_slice($matches, 1);
// Extract the matched URL parameters (and only the parameters)
$params = array_map(function ($match, $index) use ($matches) {
// We have a following parameter: take the substring from the current param position until the next one's position (thank you PREG_OFFSET_CAPTURE)
if (isset($matches[$index + 1]) && isset($matches[$index + 1][0]) && is_array($matches[$index + 1][0])) {
if ($matches[$index + 1][0][1] > -1) {
return trim(substr($match[0][0], 0, $matches[$index + 1][0][1] - $match[0][1]), '/');
}
} // We have no following parameters: return the whole lot
return isset($match[0][0]) && $match[0][1] != -1 ? trim($match[0][0], '/') : null;
}, $matches, array_keys($matches));
// Call the handling function with the URL parameters if the desired input is callable
$this->invoke($route['fn'], $params);
++$numHandled;
// If we need to quit, then quit
if ($quitAfterRun) {
break;
}
}
}
// Return the number of routes handled
return $numHandled;
}
private function invoke($fn, $params = array())
{
if (is_callable($fn)) {
call_user_func_array($fn, $params);
}
// If not, check the existence of special parameters
elseif (stripos($fn, '@') !== false) {
// Explode segments of given route
list($controller, $method) = explode('@', $fn);
// Adjust controller class if namespace has been set
if ($this->getNamespace() !== '') {
$controller = $this->getNamespace() . '\\' . $controller;
}
try {
$reflectedMethod = new \ReflectionMethod($controller, $method);
// Make sure it's callable
if ($reflectedMethod->isPublic() && (!$reflectedMethod->isAbstract())) {
if ($reflectedMethod->isStatic()) {
forward_static_call_array(array($controller, $method), $params);
} else {
// Make sure we have an instance, because a non-static method must not be called statically
if (\is_string($controller)) {
$controller = new $controller();
}
call_user_func_array(array($controller, $method), $params);
}
}
} catch (\ReflectionException $reflectionException) {
// The controller class is not available or the class does not have the method $method
}
}
}
/**
* Define the current relative URI.
*
* @return string
*/
public function getCurrentUri()
{
// Get the current Request URI and remove rewrite base path from it (= allows one to run the router in a sub folder)
$uri = substr(rawurldecode($_SERVER['REQUEST_URI']), strlen($this->getBasePath()));
// Don't take query params into account on the URL
if (strstr($uri, '?')) {
$uri = substr($uri, 0, strpos($uri, '?'));
}
// Remove trailing slash + enforce a slash at the start
return '/' . trim($uri, '/');
}
/**
* Return server base Path, and define it if isn't defined.
*
* @return string
*/
public function getBasePath()
{
// Check if server base path is defined, if not define it.
if ($this->serverBasePath === null) {
$this->serverBasePath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
}
return $this->serverBasePath;
}
/**
* Explicilty sets the server base path. To be used when your entry script path differs from your entry URLs.
* @see https://github.com/bramus/router/issues/82#issuecomment-466956078
*
* @param string
*/
public function setBasePath($serverBasePath)
{
$this->serverBasePath = $serverBasePath;
}
}
@@ -0,0 +1,959 @@
<?php
namespace {
class Handler
{
public function notfound()
{
echo 'route not found';
}
}
class RouterTest extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
// Clear SCRIPT_NAME because bramus/router tries to guess the subfolder the script is run in
$_SERVER['SCRIPT_NAME'] = '/index.php';
// Default request method to GET
$_SERVER['REQUEST_METHOD'] = 'GET';
// Default SERVER_PROTOCOL method to HTTP/1.1
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
}
protected function tearDown()
{
// nothing
}
public function testInit()
{
$this->assertInstanceOf('\Bramus\Router\Router', new \Bramus\Router\Router());
}
public function testUri()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->match('GET', '/about', function () {
echo 'about';
});
// Fake some data
$_SERVER['SCRIPT_NAME'] = '/sub/folder/index.php';
$_SERVER['REQUEST_URI'] = '/sub/folder/about/whatever';
$method = new ReflectionMethod(
'\Bramus\Router\Router',
'getCurrentUri'
);
$method->setAccessible(true);
$this->assertEquals(
'/about/whatever',
$method->invoke(new \Bramus\Router\Router())
);
}
public function testBasePathOverride()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->match('GET', '/about', function () {
echo 'about';
});
// Fake some data
$_SERVER['SCRIPT_NAME'] = '/public/index.php';
$_SERVER['REQUEST_URI'] = '/about';
$router->setBasePath('/');
$this->assertEquals(
'/',
$router->getBasePath()
);
// Test the /about route
ob_start();
$_SERVER['REQUEST_URI'] = '/about';
$router->run();
$this->assertEquals('about', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testBasePathThatContainsEmoji()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->match('GET', '/about', function () {
echo 'about';
});
// Fake some data
$_SERVER['SCRIPT_NAME'] = '/sub/folder/💩/index.php';
$_SERVER['REQUEST_URI'] = '/sub/folder/%F0%9F%92%A9/about';
// Test the /hello/bramus route
ob_start();
$router->run();
$this->assertEquals('about', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testStaticRoute()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->match('GET', '/about', function () {
echo 'about';
});
// Test the /about route
ob_start();
$_SERVER['REQUEST_URI'] = '/about';
$router->run();
$this->assertEquals('about', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testStaticRouteUsingShorthand()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/about', function () {
echo 'about';
});
// Test the /about route
ob_start();
$_SERVER['REQUEST_URI'] = '/about';
$router->run();
$this->assertEquals('about', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testRequestMethods()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'get';
});
$router->post('/', function () {
echo 'post';
});
$router->put('/', function () {
echo 'put';
});
$router->patch('/', function () {
echo 'patch';
});
$router->delete('/', function () {
echo 'delete';
});
$router->options('/', function () {
echo 'options';
});
// Test GET
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('get', ob_get_contents());
// Test POST
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'POST';
$router->run();
$this->assertEquals('post', ob_get_contents());
// Test PUT
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'PUT';
$router->run();
$this->assertEquals('put', ob_get_contents());
// Test PATCH
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'PATCH';
$router->run();
$this->assertEquals('patch', ob_get_contents());
// Test DELETE
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'DELETE';
$router->run();
$this->assertEquals('delete', ob_get_contents());
// Test OPTIONS
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'OPTIONS';
$router->run();
$this->assertEquals('options', ob_get_contents());
// Test HEAD
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'HEAD';
$router->run();
$this->assertEquals('', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testShorthandAll()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->all('/', function () {
echo 'all';
});
$_SERVER['REQUEST_URI'] = '/';
// Test GET
ob_start();
$_SERVER['REQUEST_METHOD'] = 'GET';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test POST
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'POST';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test PUT
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'PUT';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test DELETE
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'DELETE';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test OPTIONS
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'OPTIONS';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test PATCH
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'PATCH';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test HEAD
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'HEAD';
$router->run();
$this->assertEquals('', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRoute()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/(\w+)', function ($name) {
echo 'Hello ' . $name;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus';
$router->run();
$this->assertEquals('Hello bramus', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithMultiple()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/(\w+)/(\w+)', function ($name, $lastname) {
echo 'Hello ' . $name . ' ' . $lastname;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesRoutes()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/{name}/{lastname}', function ($name, $lastname) {
echo 'Hello ' . $name . ' ' . $lastname;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesRoutesWithNonAZCharsInPlaceholderNames()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/{arg1}/{arg2}', function ($arg1, $arg2) {
echo 'Hello ' . $arg1 . ' ' . $arg2;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesRoutesWithCyrillicCharactersInPlaceholderNames()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/{това}/{това}', function ($arg1, $arg2) {
echo 'Hello ' . $arg1 . ' ' . $arg2;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesRoutesWithEmojiInPlaceholderNames()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/{😂}/{😅}', function ($arg1, $arg2) {
echo 'Hello ' . $arg1 . ' ' . $arg2;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesWithCyrillicCharacters()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/bg/{arg}', function ($arg) {
echo 'BG: ' . $arg;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/bg/това';
$router->run();
$this->assertEquals('BG: това', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesWithMultipleCyrillicCharacters()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/bg/{arg}/{arg}', function ($arg1, $arg2) {
echo 'BG: ' . $arg1 . ' - ' . $arg2;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/bg/това/слъг';
$router->run();
$this->assertEquals('BG: това - слъг', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesWithEmoji()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/emoji/{emoji}', function ($emoji) {
echo 'Emoji: ' . $emoji;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/emoji/%F0%9F%92%A9'; // 💩
$router->run();
$this->assertEquals('Emoji: 💩', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesWithEmojiCombinedWithBasePathThatContainsEmoji()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/emoji/{emoji}', function ($emoji) {
echo 'Emoji: ' . $emoji;
});
// Fake some data
$_SERVER['SCRIPT_NAME'] = '/sub/folder/💩/index.php';
$_SERVER['REQUEST_URI'] = '/sub/folder/%F0%9F%92%A9/emoji/%F0%9F%A4%AF'; // 🤯
// Test the /hello/bramus route
ob_start();
$router->run();
$this->assertEquals('Emoji: 🤯', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithOptionalSubpatterns()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello(/\w+)?', function ($name = null) {
echo 'Hello ' . (($name) ? $name : 'stranger');
});
// Test the /hello route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello';
$router->run();
$this->assertEquals('Hello stranger', ob_get_contents());
// Test the /hello/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/hello/bramus';
$router->run();
$this->assertEquals('Hello bramus', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithMultipleSubpatterns()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/(.*)/page([0-9]+)', function ($place, $page) {
echo 'Hello ' . $place . ' page : ' . $page;
});
// Test the /hello/bramus/page3 route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/page3';
$router->run();
$this->assertEquals('Hello hello/bramus page : 3', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithOptionalNestedSubpatterns()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/blog(/\d{4}(/\d{2}(/\d{2}(/[a-z0-9_-]+)?)?)?)?', function ($year = null, $month = null, $day = null, $slug = null) {
if ($year === null) {
echo 'Blog overview';
return;
}
if ($month === null) {
echo 'Blog year overview (' . $year . ')';
return;
}
if ($day === null) {
echo 'Blog month overview (' . $year . '-' . $month . ')';
return;
}
if ($slug === null) {
echo 'Blog day overview (' . $year . '-' . $month . '-' . $day . ')';
return;
}
echo 'Blogpost ' . htmlentities($slug) . ' detail (' . $year . '-' . $month . '-' . $day . ')';
});
// Test the /blog route
ob_start();
$_SERVER['REQUEST_URI'] = '/blog';
$router->run();
$this->assertEquals('Blog overview', ob_get_contents());
// Test the /blog/year route
ob_clean();
$_SERVER['REQUEST_URI'] = '/blog/1983';
$router->run();
$this->assertEquals('Blog year overview (1983)', ob_get_contents());
// Test the /blog/year/month route
ob_clean();
$_SERVER['REQUEST_URI'] = '/blog/1983/12';
$router->run();
$this->assertEquals('Blog month overview (1983-12)', ob_get_contents());
// Test the /blog/year/month/day route
ob_clean();
$_SERVER['REQUEST_URI'] = '/blog/1983/12/26';
$router->run();
$this->assertEquals('Blog day overview (1983-12-26)', ob_get_contents());
// Test the /blog/year/month/day/slug route
ob_clean();
$_SERVER['REQUEST_URI'] = '/blog/1983/12/26/bramus';
$router->run();
$this->assertEquals('Blogpost bramus detail (1983-12-26)', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithNestedOptionalSubpatterns()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello(/\w+(/\w+)?)?', function ($name1 = null, $name2 = null) {
echo 'Hello ' . (($name1) ? $name1 : 'stranger') . ' ' . (($name2) ? $name2 : 'stranger');
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus';
$router->run();
$this->assertEquals('Hello bramus stranger', ob_get_contents());
// Test the /hello/bramus/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/hello/bramus/bramus';
$router->run();
$this->assertEquals('Hello bramus bramus', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithWildcard()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('(.*)', function ($name) {
echo 'Hello ' . $name;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus';
$router->run();
$this->assertEquals('Hello hello/bramus', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithPartialWildcard()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/(.*)', function ($name) {
echo 'Hello ' . $name;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus/sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function test404()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'home';
});
$router->set404(function () {
echo 'route not found';
});
$router->set404('/api(/.*)?', function () {
echo 'api route not found';
});
// Test the /hello route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('home', ob_get_contents());
// Test the /hello/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/foo';
$router->run();
$this->assertEquals('route not found', ob_get_contents());
// Test the custom api 404
ob_clean();
$_SERVER['REQUEST_URI'] = '/api/getUser';
$router->run();
$this->assertEquals('api route not found', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function test404WithClassAtMethod()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'home';
});
$router->set404('Handler@notFound');
// Test the /hello route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('home', ob_get_contents());
// Test the /hello/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/foo';
$router->run();
$this->assertEquals('route not found', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function test404WithClassAtStaticMethod()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'home';
});
$router->set404('Handler@notFound');
// Test the /hello route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('home', ob_get_contents());
// Test the /hello/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/foo';
$router->run();
$this->assertEquals('route not found', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function test404WithManualTrigger()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function() use ($router) {
$router->trigger404();
});
$router->set404(function () {
echo 'route not found';
});
// Test the / route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('route not found', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testBeforeRouterMiddleware()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->before('GET|POST', '/.*', function () {
echo 'before ';
});
$router->get('/', function () {
echo 'root';
});
$router->get('/about', function () {
echo 'about';
});
$router->get('/contact', function () {
echo 'contact';
});
$router->post('/post', function () {
echo 'post';
});
// Test the / route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('before root', ob_get_contents());
// Test the /about route
ob_clean();
$_SERVER['REQUEST_URI'] = '/about';
$router->run();
$this->assertEquals('before about', ob_get_contents());
// Test the /contact route
ob_clean();
$_SERVER['REQUEST_URI'] = '/contact';
$router->run();
$this->assertEquals('before contact', ob_get_contents());
// Test the /post route
ob_clean();
$_SERVER['REQUEST_URI'] = '/post';
$_SERVER['REQUEST_METHOD'] = 'POST';
$router->run();
$this->assertEquals('before post', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testAfterRouterMiddleware()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'home';
});
// Test the / route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run(function () {
echo 'finished';
});
$this->assertEquals('homefinished', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testBasicController()
{
$router = new \Bramus\Router\Router();
$router->get('/show/(.*)', 'RouterTestController@show');
ob_start();
$_SERVER['REQUEST_URI'] = '/show/foo';
$router->run();
$this->assertEquals('foo', ob_get_contents());
// cleanup
ob_end_clean();
}
public function testDefaultNamespace()
{
$router = new \Bramus\Router\Router();
$router->setNamespace('\Hello');
$router->get('/show/(.*)', 'HelloRouterTestController@show');
ob_start();
$_SERVER['REQUEST_URI'] = '/show/foo';
$router->run();
$this->assertEquals('foo', ob_get_contents());
// cleanup
ob_end_clean();
}
public function testSubfolders()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'home';
});
// Test the / route in a fake subfolder
ob_start();
$_SERVER['SCRIPT_NAME'] = '/about/index.php';
$_SERVER['REQUEST_URI'] = '/about/';
$router->run();
$this->assertEquals('home', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testSubrouteMouting()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->mount('/movies', function () use ($router) {
$router->get('/', function () {
echo 'overview';
});
$router->get('/(\d+)', function ($id) {
echo htmlentities($id);
});
});
// Test the /movies route
ob_start();
$_SERVER['REQUEST_URI'] = '/movies';
$router->run();
$this->assertEquals('overview', ob_get_contents());
// Test the /hello/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/movies/1';
$router->run();
$this->assertEquals('1', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testHttpMethodOverride()
{
// Fake the request method to being POST and override it
$_SERVER['REQUEST_METHOD'] = 'POST';
$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'PUT';
$method = new ReflectionMethod(
'\Bramus\Router\Router',
'getRequestMethod'
);
$method->setAccessible(true);
$this->assertEquals(
'PUT',
$method->invoke(new \Bramus\Router\Router())
);
}
public function testControllerMethodReturningFalse()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/false', 'RouterTestController@returnFalse');
$router->get('/static-false', 'RouterTestController@staticReturnFalse');
// Test returnFalse
ob_start();
$_SERVER['REQUEST_URI'] = '/false';
$router->run();
$this->assertEquals('returnFalse', ob_get_contents());
// Test staticReturnFalse
ob_clean();
$_SERVER['REQUEST_URI'] = '/static-false';
$router->run();
$this->assertEquals('staticReturnFalse', ob_get_contents());
// Cleanup
ob_end_clean();
}
}
}
namespace {
class RouterTestController
{
public function show($id)
{
echo $id;
}
public function returnFalse()
{
echo 'returnFalse';
return false;
}
public static function staticReturnFalse()
{
echo 'staticReturnFalse';
return false;
}
}
}
namespace Hello {
class HelloRouterTestController
{
public function show($id)
{
echo $id;
}
}
}
// EOF
@@ -0,0 +1,3 @@
<?php
require 'src/Bramus/Router/Router.php';
@@ -0,0 +1,579 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @see https://www.php-fig.org/psr/psr-0/
* @see https://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
/** @var \Closure(string):void */
private static $includeFile;
/** @var string|null */
private $vendorDir;
// PSR-4
/**
* @var array<string, array<string, int>>
*/
private $prefixLengthsPsr4 = array();
/**
* @var array<string, list<string>>
*/
private $prefixDirsPsr4 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr4 = array();
// PSR-0
/**
* List of PSR-0 prefixes
*
* Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2')))
*
* @var array<string, array<string, list<string>>>
*/
private $prefixesPsr0 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr0 = array();
/** @var bool */
private $useIncludePath = false;
/**
* @var array<string, string>
*/
private $classMap = array();
/** @var bool */
private $classMapAuthoritative = false;
/**
* @var array<string, bool>
*/
private $missingClasses = array();
/** @var string|null */
private $apcuPrefix;
/**
* @var array<string, self>
*/
private static $registeredLoaders = array();
/**
* @param string|null $vendorDir
*/
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
self::initializeIncludeClosure();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
/**
* @return list<string>
*/
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
/**
* @return list<string>
*/
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
/**
* @return array<string, string> Array of classname => path
*/
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array<string, string> $classMap Class to filename map
*
* @return void
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*
* @return void
*/
public function add($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
$paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
$paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
$paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
$paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
$paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
$paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 base directories
*
* @return void
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*
* @return void
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*
* @return void
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*
* @return void
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*
* @return void
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
if (null === $this->vendorDir) {
return;
}
if ($prepend) {
self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
} else {
unset(self::$registeredLoaders[$this->vendorDir]);
self::$registeredLoaders[$this->vendorDir] = $this;
}
}
/**
* Unregisters this instance as an autoloader.
*
* @return void
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
if (null !== $this->vendorDir) {
unset(self::$registeredLoaders[$this->vendorDir]);
}
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return true|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
$includeFile = self::$includeFile;
$includeFile($file);
return true;
}
return null;
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
/**
* Returns the currently registered loaders keyed by their corresponding vendor directories.
*
* @return array<string, self>
*/
public static function getRegisteredLoaders()
{
return self::$registeredLoaders;
}
/**
* @param string $class
* @param string $ext
* @return string|false
*/
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
/**
* @return void
*/
private static function initializeIncludeClosure()
{
if (self::$includeFile !== null) {
return;
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*
* @param string $file
* @return void
*/
self::$includeFile = \Closure::bind(static function($file) {
include $file;
}, null, null);
}
}
@@ -0,0 +1,396 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Autoload\ClassLoader;
use Composer\Semver\VersionParser;
/**
* This class is copied in every Composer installed project and available to all
*
* See also https://getcomposer.org/doc/07-runtime.md#installed-versions
*
* To require its presence, you can require `composer-runtime-api ^2.0`
*
* @final
*/
class InstalledVersions
{
/**
* @var string|null if set (by reflection by Composer), this should be set to the path where this class is being copied to
* @internal
*/
private static $selfDir = null;
/**
* @var mixed[]|null
* @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null
*/
private static $installed;
/**
* @var bool
*/
private static $installedIsLocalDir;
/**
* @var bool|null
*/
private static $canGetVendors;
/**
* @var array[]
* @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static $installedByVendor = array();
/**
* Returns a list of all package names which are present, either by being installed, replaced or provided
*
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackages()
{
$packages = array();
foreach (self::getInstalled() as $installed) {
$packages[] = array_keys($installed['versions']);
}
if (1 === \count($packages)) {
return $packages[0];
}
return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
}
/**
* Returns a list of all package names with a specific type e.g. 'library'
*
* @param string $type
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackagesByType($type)
{
$packagesByType = array();
foreach (self::getInstalled() as $installed) {
foreach ($installed['versions'] as $name => $package) {
if (isset($package['type']) && $package['type'] === $type) {
$packagesByType[] = $name;
}
}
}
return $packagesByType;
}
/**
* Checks whether the given package is installed
*
* This also returns true if the package name is provided or replaced by another package
*
* @param string $packageName
* @param bool $includeDevRequirements
* @return bool
*/
public static function isInstalled($packageName, $includeDevRequirements = true)
{
foreach (self::getInstalled() as $installed) {
if (isset($installed['versions'][$packageName])) {
return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false;
}
}
return false;
}
/**
* Checks whether the given package satisfies a version constraint
*
* e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call:
*
* Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3')
*
* @param VersionParser $parser Install composer/semver to have access to this class and functionality
* @param string $packageName
* @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package
* @return bool
*/
public static function satisfies(VersionParser $parser, $packageName, $constraint)
{
$constraint = $parser->parseConstraints((string) $constraint);
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
return $provided->matches($constraint);
}
/**
* Returns a version constraint representing all the range(s) which are installed for a given package
*
* It is easier to use this via isInstalled() with the $constraint argument if you need to check
* whether a given version of a package is installed, and not just whether it exists
*
* @param string $packageName
* @return string Version constraint usable with composer/semver
*/
public static function getVersionRanges($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
$ranges = array();
if (isset($installed['versions'][$packageName]['pretty_version'])) {
$ranges[] = $installed['versions'][$packageName]['pretty_version'];
}
if (array_key_exists('aliases', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
}
if (array_key_exists('replaced', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
}
if (array_key_exists('provided', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
}
return implode(' || ', $ranges);
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['version'])) {
return null;
}
return $installed['versions'][$packageName]['version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getPrettyVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['pretty_version'])) {
return null;
}
return $installed['versions'][$packageName]['pretty_version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference
*/
public static function getReference($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['reference'])) {
return null;
}
return $installed['versions'][$packageName]['reference'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path.
*/
public static function getInstallPath($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null;
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @return array
* @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}
*/
public static function getRootPackage()
{
$installed = self::getInstalled();
return $installed[0]['root'];
}
/**
* Returns the raw installed.php data for custom implementations
*
* @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect.
* @return array[]
* @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}
*/
public static function getRawData()
{
@trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED);
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
self::$installed = include __DIR__ . '/installed.php';
} else {
self::$installed = array();
}
}
return self::$installed;
}
/**
* Returns the raw data of all installed.php which are currently loaded for custom implementations
*
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
public static function getAllRawData()
{
return self::getInstalled();
}
/**
* Lets you reload the static array from another file
*
* This is only useful for complex integrations in which a project needs to use
* this class but then also needs to execute another project's autoloader in process,
* and wants to ensure both projects have access to their version of installed.php.
*
* A typical case would be PHPUnit, where it would need to make sure it reads all
* the data it needs from this class, then call reload() with
* `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure
* the project in which it runs can then also use this class safely, without
* interference between PHPUnit's dependencies and the project's dependencies.
*
* @param array[] $data A vendor/composer/installed.php data set
* @return void
*
* @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data
*/
public static function reload($data)
{
self::$installed = $data;
self::$installedByVendor = array();
// when using reload, we disable the duplicate protection to ensure that self::$installed data is
// always returned, but we cannot know whether it comes from the installed.php in __DIR__ or not,
// so we have to assume it does not, and that may result in duplicate data being returned when listing
// all installed packages for example
self::$installedIsLocalDir = false;
}
/**
* @return string
*/
private static function getSelfDir()
{
if (self::$selfDir === null) {
self::$selfDir = strtr(__DIR__, '\\', '/');
}
return self::$selfDir;
}
/**
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static function getInstalled()
{
if (null === self::$canGetVendors) {
self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
}
$installed = array();
$copiedLocalDir = false;
if (self::$canGetVendors) {
$selfDir = self::getSelfDir();
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
$vendorDir = strtr($vendorDir, '\\', '/');
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir.'/composer/installed.php')) {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require $vendorDir.'/composer/installed.php';
self::$installedByVendor[$vendorDir] = $required;
$installed[] = $required;
if (self::$installed === null && $vendorDir.'/composer' === $selfDir) {
self::$installed = $required;
self::$installedIsLocalDir = true;
}
}
if (self::$installedIsLocalDir && $vendorDir.'/composer' === $selfDir) {
$copiedLocalDir = true;
}
}
}
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require __DIR__ . '/installed.php';
self::$installed = $required;
} else {
self::$installed = array();
}
}
if (self::$installed !== array() && !$copiedLocalDir) {
$installed[] = self::$installed;
}
return $installed;
}
}
@@ -0,0 +1,21 @@
Copyright (c) Nils Adermann, Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,15 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Attribute' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
'PhpToken' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php',
'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php',
'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php',
);
@@ -0,0 +1,15 @@
<?php
// autoload_files.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php',
'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php',
'7b11c4dc42b3b3023073cb14e519683c' => $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
'37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php',
);
@@ -0,0 +1,10 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Bramus' => array($vendorDir . '/bramus/router/src'),
);
@@ -0,0 +1,23 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/src'),
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-factory/src', $vendorDir . '/psr/http-message/src'),
'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'),
'PhpOption\\' => array($vendorDir . '/phpoption/phpoption/src/PhpOption'),
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'),
'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'),
'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'),
'GrahamCampbell\\ResultType\\' => array($vendorDir . '/graham-campbell/result-type/src'),
'Dotenv\\' => array($vendorDir . '/vlucas/phpdotenv/src'),
'App\\' => array($baseDir . '/src'),
);
@@ -0,0 +1,50 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInitc448faa2bb4d17063fdd5b5dff1f2609
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
/**
* @return \Composer\Autoload\ClassLoader
*/
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
require __DIR__ . '/platform_check.php';
spl_autoload_register(array('ComposerAutoloaderInitc448faa2bb4d17063fdd5b5dff1f2609', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInitc448faa2bb4d17063fdd5b5dff1f2609', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInitc448faa2bb4d17063fdd5b5dff1f2609::getInitializer($loader));
$loader->register(true);
$filesToLoad = \Composer\Autoload\ComposerStaticInitc448faa2bb4d17063fdd5b5dff1f2609::$files;
$requireFile = \Closure::bind(static function ($fileIdentifier, $file) {
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
require $file;
}
}, null, null);
foreach ($filesToLoad as $fileIdentifier => $file) {
$requireFile($fileIdentifier, $file);
}
return $loader;
}
}
@@ -0,0 +1,142 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInitc448faa2bb4d17063fdd5b5dff1f2609
{
public static $files = array (
'6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php',
'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php',
'7b11c4dc42b3b3023073cb14e519683c' => __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php',
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
'37a3dc5111fe8f707ab4c132ef1dbc62' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/functions_include.php',
);
public static $prefixLengthsPsr4 = array (
'S' =>
array (
'Symfony\\Polyfill\\Php80\\' => 23,
'Symfony\\Polyfill\\Mbstring\\' => 26,
'Symfony\\Polyfill\\Ctype\\' => 23,
),
'P' =>
array (
'Psr\\Log\\' => 8,
'Psr\\Http\\Message\\' => 17,
'Psr\\Http\\Client\\' => 16,
'PhpOption\\' => 10,
),
'M' =>
array (
'Monolog\\' => 8,
),
'G' =>
array (
'GuzzleHttp\\Psr7\\' => 16,
'GuzzleHttp\\Promise\\' => 19,
'GuzzleHttp\\' => 11,
'GrahamCampbell\\ResultType\\' => 26,
),
'D' =>
array (
'Dotenv\\' => 7,
),
'A' =>
array (
'App\\' => 4,
),
);
public static $prefixDirsPsr4 = array (
'Symfony\\Polyfill\\Php80\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-php80',
),
'Symfony\\Polyfill\\Mbstring\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring',
),
'Symfony\\Polyfill\\Ctype\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-ctype',
),
'Psr\\Log\\' =>
array (
0 => __DIR__ . '/..' . '/psr/log/src',
),
'Psr\\Http\\Message\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-factory/src',
1 => __DIR__ . '/..' . '/psr/http-message/src',
),
'Psr\\Http\\Client\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-client/src',
),
'PhpOption\\' =>
array (
0 => __DIR__ . '/..' . '/phpoption/phpoption/src/PhpOption',
),
'Monolog\\' =>
array (
0 => __DIR__ . '/..' . '/monolog/monolog/src/Monolog',
),
'GuzzleHttp\\Psr7\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src',
),
'GuzzleHttp\\Promise\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/promises/src',
),
'GuzzleHttp\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/guzzle/src',
),
'GrahamCampbell\\ResultType\\' =>
array (
0 => __DIR__ . '/..' . '/graham-campbell/result-type/src',
),
'Dotenv\\' =>
array (
0 => __DIR__ . '/..' . '/vlucas/phpdotenv/src',
),
'App\\' =>
array (
0 => __DIR__ . '/../..' . '/src',
),
);
public static $prefixesPsr0 = array (
'B' =>
array (
'Bramus' =>
array (
0 => __DIR__ . '/..' . '/bramus/router/src',
),
),
);
public static $classMap = array (
'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
'PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php',
'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
'UnhandledMatchError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php',
'ValueError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/ValueError.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInitc448faa2bb4d17063fdd5b5dff1f2609::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitc448faa2bb4d17063fdd5b5dff1f2609::$prefixDirsPsr4;
$loader->prefixesPsr0 = ComposerStaticInitc448faa2bb4d17063fdd5b5dff1f2609::$prefixesPsr0;
$loader->classMap = ComposerStaticInitc448faa2bb4d17063fdd5b5dff1f2609::$classMap;
}, null, ClassLoader::class);
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,200 @@
<?php return array(
'root' => array(
'name' => 'porawit/soar-wazuh',
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'reference' => null,
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev' => true,
),
'versions' => array(
'bramus/router' => array(
'pretty_version' => '1.6.1',
'version' => '1.6.1.0',
'reference' => '55657b76da8a0a509250fb55b9dd24e1aa237eba',
'type' => 'library',
'install_path' => __DIR__ . '/../bramus/router',
'aliases' => array(),
'dev_requirement' => false,
),
'graham-campbell/result-type' => array(
'pretty_version' => 'v1.1.4',
'version' => '1.1.4.0',
'reference' => 'e01f4a821471308ba86aa202fed6698b6b695e3b',
'type' => 'library',
'install_path' => __DIR__ . '/../graham-campbell/result-type',
'aliases' => array(),
'dev_requirement' => false,
),
'guzzlehttp/guzzle' => array(
'pretty_version' => '7.15.3',
'version' => '7.15.3.0',
'reference' => 'ae311b8f045ea93ce7b1c9cdb7cec06c53f944bc',
'type' => 'library',
'install_path' => __DIR__ . '/../guzzlehttp/guzzle',
'aliases' => array(),
'dev_requirement' => false,
),
'guzzlehttp/promises' => array(
'pretty_version' => '2.5.2',
'version' => '2.5.2.0',
'reference' => '2823687acff28b2dbe67b2508a6b300e2c3fa4ce',
'type' => 'library',
'install_path' => __DIR__ . '/../guzzlehttp/promises',
'aliases' => array(),
'dev_requirement' => false,
),
'guzzlehttp/psr7' => array(
'pretty_version' => '2.13.0',
'version' => '2.13.0.0',
'reference' => 'dad89620b7a6edb60c15858442eb2e408b45d8f4',
'type' => 'library',
'install_path' => __DIR__ . '/../guzzlehttp/psr7',
'aliases' => array(),
'dev_requirement' => false,
),
'monolog/monolog' => array(
'pretty_version' => '3.10.0',
'version' => '3.10.0.0',
'reference' => 'b321dd6749f0bf7189444158a3ce785cc16d69b0',
'type' => 'library',
'install_path' => __DIR__ . '/../monolog/monolog',
'aliases' => array(),
'dev_requirement' => false,
),
'phpoption/phpoption' => array(
'pretty_version' => '1.9.5',
'version' => '1.9.5.0',
'reference' => '75365b91986c2405cf5e1e012c5595cd487a98be',
'type' => 'library',
'install_path' => __DIR__ . '/../phpoption/phpoption',
'aliases' => array(),
'dev_requirement' => false,
),
'porawit/soar-wazuh' => array(
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'reference' => null,
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev_requirement' => false,
),
'psr/http-client' => array(
'pretty_version' => '1.0.3',
'version' => '1.0.3.0',
'reference' => 'bb5906edc1c324c9a05aa0873d40117941e5fa90',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/http-client',
'aliases' => array(),
'dev_requirement' => false,
),
'psr/http-client-implementation' => array(
'dev_requirement' => false,
'provided' => array(
0 => '1.0',
),
),
'psr/http-factory' => array(
'pretty_version' => '1.1.0',
'version' => '1.1.0.0',
'reference' => '2b4765fddfe3b508ac62f829e852b1501d3f6e8a',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/http-factory',
'aliases' => array(),
'dev_requirement' => false,
),
'psr/http-factory-implementation' => array(
'dev_requirement' => false,
'provided' => array(
0 => '1.0',
),
),
'psr/http-message' => array(
'pretty_version' => '2.0',
'version' => '2.0.0.0',
'reference' => '402d35bcb92c70c026d1a6a9883f06b2ead23d71',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/http-message',
'aliases' => array(),
'dev_requirement' => false,
),
'psr/http-message-implementation' => array(
'dev_requirement' => false,
'provided' => array(
0 => '1.0',
),
),
'psr/log' => array(
'pretty_version' => '3.0.2',
'version' => '3.0.2.0',
'reference' => 'f16e1d5863e37f8d8c2a01719f5b34baa2b714d3',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/log',
'aliases' => array(),
'dev_requirement' => false,
),
'psr/log-implementation' => array(
'dev_requirement' => false,
'provided' => array(
0 => '3.0.0',
),
),
'ralouphie/getallheaders' => array(
'pretty_version' => '3.0.3',
'version' => '3.0.3.0',
'reference' => '120b605dfeb996808c31b6477290a714d356e822',
'type' => 'library',
'install_path' => __DIR__ . '/../ralouphie/getallheaders',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/deprecation-contracts' => array(
'pretty_version' => 'v3.7.1',
'version' => '3.7.1.0',
'reference' => 'f3202fa1b5097b0af062dc978b32ecf63404e31d',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/deprecation-contracts',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/polyfill-ctype' => array(
'pretty_version' => 'v1.37.0',
'version' => '1.37.0.0',
'reference' => '141046a8f9477948ff284fa65be2095baafb94f2',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-ctype',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/polyfill-mbstring' => array(
'pretty_version' => 'v1.38.2',
'version' => '1.38.2.0',
'reference' => 'd3d318bad5e7a1bfbd026009c8bfb8d8f99ae6b6',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-mbstring',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/polyfill-php80' => array(
'pretty_version' => 'v1.37.0',
'version' => '1.37.0.0',
'reference' => 'dfb55726c3a76ea3b6459fcfda1ec2d80a682411',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-php80',
'aliases' => array(),
'dev_requirement' => false,
),
'vlucas/phpdotenv' => array(
'pretty_version' => 'v5.6.4',
'version' => '5.6.4.0',
'reference' => '416df702837983f8d5ff48c9c3fee4f5f57b980b',
'type' => 'library',
'install_path' => __DIR__ . '/../vlucas/phpdotenv',
'aliases' => array(),
'dev_requirement' => false,
),
),
);
@@ -0,0 +1,25 @@
<?php
// platform_check.php @generated by Composer
$issues = array();
if (!(PHP_VERSION_ID >= 80100)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 8.1.0". You are running ' . PHP_VERSION . '.';
}
if ($issues) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL);
} elseif (!headers_sent()) {
echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL;
}
}
throw new \RuntimeException(
'Composer detected issues in your platform: ' . implode(' ', $issues)
);
}
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2020-2024 Graham Campbell <hello@gjcampbell.co.uk>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,33 @@
{
"name": "graham-campbell/result-type",
"description": "An Implementation Of The Result Type",
"keywords": ["result", "result-type", "Result", "Result Type", "Result-Type", "Graham Campbell", "GrahamCampbell"],
"license": "MIT",
"authors": [
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
}
],
"require": {
"php": "^7.2.5 || ^8.0",
"phpoption/phpoption": "^1.9.5"
},
"require-dev": {
"phpunit/phpunit": "^8.5.41 || ^9.6.22 || ^10.5.45 || ^11.5.7"
},
"autoload": {
"psr-4": {
"GrahamCampbell\\ResultType\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"GrahamCampbell\\Tests\\ResultType\\": "tests/"
}
},
"config": {
"preferred-install": "dist"
}
}
@@ -0,0 +1,121 @@
<?php
declare(strict_types=1);
/*
* This file is part of Result Type.
*
* (c) Graham Campbell <hello@gjcampbell.co.uk>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace GrahamCampbell\ResultType;
use PhpOption\None;
use PhpOption\Some;
/**
* @template T
* @template E
*
* @extends \GrahamCampbell\ResultType\Result<T,E>
*/
final class Error extends Result
{
/**
* @var E
*/
private $value;
/**
* Internal constructor for an error value.
*
* @param E $value
*
* @return void
*/
private function __construct($value)
{
$this->value = $value;
}
/**
* Create a new error value.
*
* @template F
*
* @param F $value
*
* @return \GrahamCampbell\ResultType\Result<T,F>
*/
public static function create($value)
{
return new self($value);
}
/**
* Get the success option value.
*
* @return \PhpOption\Option<T>
*/
public function success()
{
return None::create();
}
/**
* Map over the success value.
*
* @template S
*
* @param callable(T):S $f
*
* @return \GrahamCampbell\ResultType\Result<S,E>
*/
public function map(callable $f)
{
return self::create($this->value);
}
/**
* Flat map over the success value.
*
* @template S
* @template F
*
* @param callable(T):\GrahamCampbell\ResultType\Result<S,F> $f
*
* @return \GrahamCampbell\ResultType\Result<S,F>
*/
public function flatMap(callable $f)
{
/** @var \GrahamCampbell\ResultType\Result<S,F> */
return self::create($this->value);
}
/**
* Get the error option value.
*
* @return \PhpOption\Option<E>
*/
public function error()
{
return Some::create($this->value);
}
/**
* Map over the error value.
*
* @template F
*
* @param callable(E):F $f
*
* @return \GrahamCampbell\ResultType\Result<T,F>
*/
public function mapError(callable $f)
{
return self::create($f($this->value));
}
}
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
/*
* This file is part of Result Type.
*
* (c) Graham Campbell <hello@gjcampbell.co.uk>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace GrahamCampbell\ResultType;
/**
* @template T
* @template E
*/
abstract class Result
{
/**
* Get the success option value.
*
* @return \PhpOption\Option<T>
*/
abstract public function success();
/**
* Map over the success value.
*
* @template S
*
* @param callable(T):S $f
*
* @return \GrahamCampbell\ResultType\Result<S,E>
*/
abstract public function map(callable $f);
/**
* Flat map over the success value.
*
* @template S
* @template F
*
* @param callable(T):\GrahamCampbell\ResultType\Result<S,F> $f
*
* @return \GrahamCampbell\ResultType\Result<S,F>
*/
abstract public function flatMap(callable $f);
/**
* Get the error option value.
*
* @return \PhpOption\Option<E>
*/
abstract public function error();
/**
* Map over the error value.
*
* @template F
*
* @param callable(E):F $f
*
* @return \GrahamCampbell\ResultType\Result<T,F>
*/
abstract public function mapError(callable $f);
}
@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
/*
* This file is part of Result Type.
*
* (c) Graham Campbell <hello@gjcampbell.co.uk>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace GrahamCampbell\ResultType;
use PhpOption\None;
use PhpOption\Some;
/**
* @template T
* @template E
*
* @extends \GrahamCampbell\ResultType\Result<T,E>
*/
final class Success extends Result
{
/**
* @var T
*/
private $value;
/**
* Internal constructor for a success value.
*
* @param T $value
*
* @return void
*/
private function __construct($value)
{
$this->value = $value;
}
/**
* Create a new error value.
*
* @template S
*
* @param S $value
*
* @return \GrahamCampbell\ResultType\Result<S,E>
*/
public static function create($value)
{
return new self($value);
}
/**
* Get the success option value.
*
* @return \PhpOption\Option<T>
*/
public function success()
{
return Some::create($this->value);
}
/**
* Map over the success value.
*
* @template S
*
* @param callable(T):S $f
*
* @return \GrahamCampbell\ResultType\Result<S,E>
*/
public function map(callable $f)
{
return self::create($f($this->value));
}
/**
* Flat map over the success value.
*
* @template S
* @template F
*
* @param callable(T):\GrahamCampbell\ResultType\Result<S,F> $f
*
* @return \GrahamCampbell\ResultType\Result<S,F>
*/
public function flatMap(callable $f)
{
return $f($this->value);
}
/**
* Get the error option value.
*
* @return \PhpOption\Option<E>
*/
public function error()
{
return None::create();
}
/**
* Map over the error value.
*
* @template F
*
* @param callable(E):F $f
*
* @return \GrahamCampbell\ResultType\Result<T,F>
*/
public function mapError(callable $f)
{
return self::create($this->value);
}
}
@@ -0,0 +1,27 @@
The MIT License (MIT)
Copyright (c) 2011 Michael Dowling <mtdowling@gmail.com>
Copyright (c) 2012 Jeremy Lindblom <jeremeamia@gmail.com>
Copyright (c) 2014 Graham Campbell <hello@gjcampbell.co.uk>
Copyright (c) 2015 Márk Sági-Kazár <mark.sagikazar@gmail.com>
Copyright (c) 2015 Tobias Schultze <webmaster@tubo-world.de>
Copyright (c) 2016 Tobias Nyholm <tobias.nyholm@gmail.com>
Copyright (c) 2016 George Mponos <gmponos@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,94 @@
![Guzzle](.github/logo.png?raw=true)
# Guzzle, PHP HTTP client
[![Latest Version](https://img.shields.io/github/release/guzzle/guzzle.svg?style=flat-square)](https://github.com/guzzle/guzzle/releases)
[![Build Status](https://img.shields.io/github/actions/workflow/status/guzzle/guzzle/ci.yml?label=ci%20build&style=flat-square)](https://github.com/guzzle/guzzle/actions?query=workflow%3ACI)
[![Total Downloads](https://img.shields.io/packagist/dt/guzzlehttp/guzzle.svg?style=flat-square)](https://packagist.org/packages/guzzlehttp/guzzle)
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and
trivial to integrate with web services.
- Simple interface for building query strings, POST requests, streaming large
uploads, streaming large downloads, using HTTP cookies, uploading JSON data,
etc...
- Can send both synchronous and asynchronous requests using the same interface.
- Uses PSR-7 interfaces for requests, responses, and streams. This allows you
to utilize other PSR-7 compatible libraries with Guzzle.
- Supports PSR-18 allowing interoperability between other PSR-18 HTTP Clients.
- Abstracts away the underlying HTTP transport, allowing you to write
environment and transport agnostic code; i.e., no hard dependency on cURL,
PHP streams, sockets, or non-blocking event loops.
- Middleware system allows you to augment and compose client behavior.
```php
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');
echo $response->getStatusCode(); // 200
echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}'
// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
```
## Help and docs
We use GitHub issues only to discuss bugs and new features. For support please refer to:
- [Documentation](docs/index.md)
- [Stack Overflow](https://stackoverflow.com/questions/tagged/guzzle)
- [#guzzle](https://app.slack.com/client/T0D2S9JCT/CE6UAAKL4) channel on [PHP-HTTP Slack](https://slack.httplug.io/)
- [Gitter](https://gitter.im/guzzle/guzzle)
## Installing Guzzle
The recommended way to install Guzzle is through
[Composer](https://getcomposer.org/).
```bash
composer require guzzlehttp/guzzle
```
## Version Guidance
| Version | Status | Packagist | Namespace | Repo | Docs | PSR-7 | PHP Version |
|---------|---------------------|---------------------|--------------|---------------------|---------------------|-------|--------------|
| 3.x | EOL (2016-10-31) | `guzzle/guzzle` | `Guzzle` | [v3][guzzle-3-repo] | [v3][guzzle-3-docs] | No | >=5.3.3,<7.0 |
| 4.x | EOL (2016-10-31) | `guzzlehttp/guzzle` | `GuzzleHttp` | [v4][guzzle-4-repo] | N/A | No | >=5.4,<7.0 |
| 5.x | EOL (2019-10-31) | `guzzlehttp/guzzle` | `GuzzleHttp` | [v5][guzzle-5-repo] | [v5][guzzle-5-docs] | No | >=5.4,<7.4 |
| 6.x | EOL (2023-10-31) | `guzzlehttp/guzzle` | `GuzzleHttp` | [v6][guzzle-6-repo] | [v6][guzzle-6-docs] | Yes | >=5.5,<8.0 |
| 7.x | Latest | `guzzlehttp/guzzle` | `GuzzleHttp` | [v7][guzzle-7-repo] | [v7][guzzle-7-docs] | Yes | >=7.2.5,<8.6 |
[guzzle-3-repo]: https://github.com/guzzle/guzzle3
[guzzle-4-repo]: https://github.com/guzzle/guzzle/tree/4.x
[guzzle-5-repo]: https://github.com/guzzle/guzzle/tree/5.3
[guzzle-6-repo]: https://github.com/guzzle/guzzle/tree/6.5
[guzzle-7-repo]: https://github.com/guzzle/guzzle/tree/7.15
[guzzle-3-docs]: https://github.com/guzzle/guzzle3/tree/master/docs
[guzzle-5-docs]: https://github.com/guzzle/guzzle/tree/5.3/docs
[guzzle-6-docs]: https://github.com/guzzle/guzzle/tree/6.5/docs
[guzzle-7-docs]: https://github.com/guzzle/guzzle/blob/7.15/docs/index.md
## Security
If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/guzzle/security/policy) for more information.
## License
Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information.
## For Enterprise
Available as part of the Tidelift Subscription
The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-guzzle?utm_source=packagist-guzzlehttp-guzzle&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
@@ -0,0 +1,133 @@
{
"name": "guzzlehttp/guzzle",
"description": "Guzzle is a PHP HTTP client library",
"license": "MIT",
"keywords": [
"framework",
"http",
"rest",
"web service",
"curl",
"client",
"HTTP client",
"PSR-7",
"PSR-18"
],
"authors": [
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
},
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
},
{
"name": "Jeremy Lindblom",
"email": "jeremeamia@gmail.com",
"homepage": "https://github.com/jeremeamia"
},
{
"name": "George Mponos",
"email": "gmponos@gmail.com",
"homepage": "https://github.com/gmponos"
},
{
"name": "Tobias Nyholm",
"email": "tobias.nyholm@gmail.com",
"homepage": "https://github.com/Nyholm"
},
{
"name": "Márk Sági-Kazár",
"email": "mark.sagikazar@gmail.com",
"homepage": "https://github.com/sagikazarmark"
},
{
"name": "Tobias Schultze",
"email": "webmaster@tubo-world.de",
"homepage": "https://github.com/Tobion"
}
],
"require": {
"php": "^7.2.5 || ^8.0",
"ext-json": "*",
"guzzlehttp/promises": "^2.5.2",
"guzzlehttp/psr7": "^2.13",
"psr/http-client": "^1.0",
"symfony/deprecation-contracts": "^2.5 || ^3.0",
"symfony/polyfill-php80": "^1.25"
},
"require-dev": {
"ext-curl": "*",
"bamarni/composer-bin-plugin": "^1.8.2",
"guzzle/client-integration-tests": "3.0.3",
"guzzlehttp/test-server": "^0.7",
"php-http/message-factory": "^1.1",
"phpunit/phpunit": "^8.5.52 || ^9.6.34",
"psr/log": "^1.1 || ^2.0 || ^3.0"
},
"provide": {
"psr/http-client-implementation": "1.0"
},
"suggest": {
"ext-curl": "Required for CURL handler support",
"ext-intl": "Required for Internationalized Domain Name (IDN) support",
"psr/log": "Required for using the Log middleware"
},
"repositories": [
{
"type": "package",
"package": {
"name": "guzzle/client-integration-tests",
"version": "v3.0.3",
"require": {
"guzzlehttp/psr7": "^1.7 || ^2.0",
"php": "^7.2.5 || ^8.0",
"php-http/message": "^1.0 || ^2.0",
"phpunit/phpunit": "^7.5.20 || ^8.5.8 || ^9.3.11",
"th3n3rd/cartesian-product": "^0.3"
},
"autoload": {
"psr-4": {
"Http\\Client\\Tests\\": "src/"
}
},
"bin": [
"bin/http_test_server"
],
"dist": {
"type": "zip",
"url": "https://codeload.github.com/guzzle/client-integration-tests/zip/30edbabe49dedd95e3f21d8a25438f767b653d75"
}
}
}
],
"autoload": {
"psr-4": {
"GuzzleHttp\\": "src/"
},
"files": [
"src/functions_include.php"
]
},
"autoload-dev": {
"psr-4": {
"GuzzleHttp\\Tests\\": "tests/"
}
},
"config": {
"allow-plugins": {
"bamarni/composer-bin-plugin": true
},
"preferred-install": "dist",
"sort-packages": true
},
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": false
}
}
}
@@ -0,0 +1,28 @@
<?php
namespace GuzzleHttp;
use Psr\Http\Message\MessageInterface;
final class BodySummarizer implements BodySummarizerInterface
{
/**
* @var int|null
*/
private $truncateAt;
public function __construct(?int $truncateAt = null)
{
$this->truncateAt = $truncateAt;
}
/**
* Returns a summarized message body.
*/
public function summarize(MessageInterface $message): ?string
{
return $this->truncateAt === null
? Psr7\Message::bodySummary($message)
: Psr7\Message::bodySummary($message, $this->truncateAt);
}
}
@@ -0,0 +1,13 @@
<?php
namespace GuzzleHttp;
use Psr\Http\Message\MessageInterface;
interface BodySummarizerInterface
{
/**
* Returns a summarized message body.
*/
public function summarize(MessageInterface $message): ?string;
}
@@ -0,0 +1,84 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* Client interface for sending HTTP requests.
*/
interface ClientInterface
{
/**
* The Guzzle major version.
*/
public const MAJOR_VERSION = 7;
/**
* Send an HTTP request.
*
* @param RequestInterface $request Request to send
* @param array $options Request options to apply to the given
* request and to the transfer.
*
* @throws GuzzleException
*/
public function send(RequestInterface $request, array $options = []): ResponseInterface;
/**
* Asynchronously send an HTTP request.
*
* @param RequestInterface $request Request to send
* @param array $options Request options to apply to the given
* request and to the transfer.
*/
public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface;
/**
* Create and send an HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string $method HTTP method.
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function request(string $method, $uri, array $options = []): ResponseInterface;
/**
* Create and send an asynchronous HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string $method HTTP method
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function requestAsync(string $method, $uri, array $options = []): PromiseInterface;
/**
* Get a client configuration option.
*
* These options include default request options of the client, a "handler"
* (if utilized by the concrete client), and a "base_uri" if utilized by
* the concrete client.
*
* @param string|null $option The config option to retrieve.
*
* @return mixed
*
* @deprecated ClientInterface::getConfig will be removed in guzzlehttp/guzzle:8.0.
*/
public function getConfig(?string $option = null);
}
@@ -0,0 +1,241 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* Client interface for sending HTTP requests.
*/
trait ClientTrait
{
/**
* Create and send an HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string $method HTTP method.
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
abstract public function request(string $method, $uri, array $options = []): ResponseInterface;
/**
* Create and send an HTTP GET request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function get($uri, array $options = []): ResponseInterface
{
return $this->request('GET', $uri, $options);
}
/**
* Create and send an HTTP HEAD request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function head($uri, array $options = []): ResponseInterface
{
return $this->request('HEAD', $uri, $options);
}
/**
* Create and send an HTTP PUT request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function put($uri, array $options = []): ResponseInterface
{
return $this->request('PUT', $uri, $options);
}
/**
* Create and send an HTTP POST request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function post($uri, array $options = []): ResponseInterface
{
return $this->request('POST', $uri, $options);
}
/**
* Create and send an HTTP PATCH request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function patch($uri, array $options = []): ResponseInterface
{
return $this->request('PATCH', $uri, $options);
}
/**
* Create and send an HTTP DELETE request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function delete($uri, array $options = []): ResponseInterface
{
return $this->request('DELETE', $uri, $options);
}
/**
* Create and send an asynchronous HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string $method HTTP method
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
abstract public function requestAsync(string $method, $uri, array $options = []): PromiseInterface;
/**
* Create and send an asynchronous HTTP GET request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function getAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('GET', $uri, $options);
}
/**
* Create and send an asynchronous HTTP HEAD request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function headAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('HEAD', $uri, $options);
}
/**
* Create and send an asynchronous HTTP PUT request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function putAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('PUT', $uri, $options);
}
/**
* Create and send an asynchronous HTTP POST request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function postAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('POST', $uri, $options);
}
/**
* Create and send an asynchronous HTTP PATCH request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function patchAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('PATCH', $uri, $options);
}
/**
* Create and send an asynchronous HTTP DELETE request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function deleteAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('DELETE', $uri, $options);
}
}
@@ -0,0 +1,378 @@
<?php
namespace GuzzleHttp\Cookie;
use GuzzleHttp\Psr7;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Cookie jar that stores cookies as an array
*/
class CookieJar implements CookieJarInterface
{
private const MAX_SET_COOKIE_FIELD_LENGTH = 8190;
private const MAX_SET_COOKIE_FIELDS = 50;
private const MAX_REQUEST_COOKIES = 150;
private const MAX_COOKIE_HEADER_LENGTH = 8190;
/**
* @var SetCookie[] Loaded cookie data
*/
private $cookies = [];
/**
* @var bool
*/
private $strictMode;
/**
* @param bool $strictMode Set to true to throw exceptions when invalid
* cookies are added to the cookie jar.
* @param array $cookieArray Array of SetCookie objects or a hash of
* arrays that can be used with the SetCookie
* constructor
*/
public function __construct(bool $strictMode = false, array $cookieArray = [])
{
$this->strictMode = $strictMode;
foreach ($cookieArray as $cookie) {
if (!$cookie instanceof SetCookie) {
$cookie = new SetCookie($cookie);
}
$this->setCookie($cookie);
}
}
/**
* Create a new Cookie jar from an associative array and domain.
*
* @param array $cookies Cookies to create the jar from
* @param string $domain Domain to set the cookies to
*/
public static function fromArray(array $cookies, string $domain): self
{
$cookieJar = new self();
foreach ($cookies as $name => $value) {
$cookieJar->setCookie(new SetCookie([
'Domain' => $domain,
'Name' => $name,
'Value' => $value,
'Discard' => true,
]));
}
return $cookieJar;
}
/**
* Evaluate if this cookie should be persisted to storage
* that survives between requests.
*
* @param SetCookie $cookie Being evaluated.
* @param bool $allowSessionCookies If we should persist session cookies
*/
public static function shouldPersist(SetCookie $cookie, bool $allowSessionCookies = false): bool
{
if ($cookie->getExpires() || $allowSessionCookies) {
if (!$cookie->getDiscard()) {
return true;
}
}
return false;
}
/**
* Finds and returns the cookie based on the name
*
* @param string $name cookie name to search for
*
* @return SetCookie|null cookie that was found or null if not found
*/
public function getCookieByName(string $name): ?SetCookie
{
foreach ($this->cookies as $cookie) {
if ($cookie->getName() !== null && Psr7\Utils::caselessEquals($cookie->getName(), $name)) {
return $cookie;
}
}
return null;
}
public function toArray(): array
{
return \array_map(static function (SetCookie $cookie): array {
return $cookie->toArray();
}, $this->getIterator()->getArrayCopy());
}
public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void
{
if ($domain === null) {
$this->cookies = [];
return;
} elseif ($path === null) {
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie) use ($domain): bool {
return $cookie->getDomain() === null || !$cookie->matchesDomain($domain);
}
);
} elseif ($name === null) {
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie) use ($path, $domain): bool {
return !($cookie->getDomain() !== null
&& $cookie->matchesPath($path)
&& $cookie->matchesDomain($domain));
}
);
} else {
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie) use ($path, $domain, $name) {
return !($cookie->getDomain() !== null
&& $cookie->getName() === $name
&& $cookie->matchesPath($path)
&& $cookie->matchesDomain($domain));
}
);
}
}
public function clearSessionCookies(): void
{
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie): bool {
return !$cookie->getDiscard() && $cookie->getExpires();
}
);
}
public function setCookie(SetCookie $cookie): bool
{
// If the name string is empty (but not 0), ignore the set-cookie
// string entirely.
$name = $cookie->getName();
if (!$name && $name !== '0') {
return false;
}
// Only allow cookies with set and valid domain, name, value
$result = $cookie->validate();
if ($result !== true) {
if ($this->strictMode) {
throw new \RuntimeException('Invalid cookie: '.$result);
}
$this->removeCookieIfEmpty($cookie);
return false;
}
$maxAge = $cookie->getMaxAge();
if ($maxAge !== null && $maxAge <= 0) {
if ($cookie->getDomain() !== null) {
$this->removeCookie($cookie);
}
return false;
}
// Resolve conflicts with previously set cookies
foreach ($this->cookies as $i => $c) {
// Two cookies are identical, when their path, and domain are
// identical.
if ($c->getPath() !== $cookie->getPath()
|| $c->getDomain() !== $cookie->getDomain()
|| $c->getHostOnly() !== $cookie->getHostOnly()
|| $c->getName() !== $cookie->getName()
) {
continue;
}
// The previously set cookie is a discard cookie and this one is
// not so allow the new cookie to be set
if (!$cookie->getDiscard() && $c->getDiscard()) {
unset($this->cookies[$i]);
continue;
}
// If the new cookie's expiration is further into the future, then
// replace the old cookie
if ($cookie->getExpires() > $c->getExpires()) {
unset($this->cookies[$i]);
continue;
}
// If the value has changed, we better change it
if ($cookie->getValue() !== $c->getValue()) {
unset($this->cookies[$i]);
continue;
}
// The cookie exists, so no need to continue
return false;
}
$this->cookies[] = $cookie;
return true;
}
public function count(): int
{
return \count($this->cookies);
}
/**
* @return \ArrayIterator<int, SetCookie>
*/
public function getIterator(): \ArrayIterator
{
return new \ArrayIterator(\array_values($this->cookies));
}
public function extractCookies(RequestInterface $request, ResponseInterface $response): void
{
if ($cookieHeader = $response->getHeader('Set-Cookie')) {
$accepted = 0;
foreach ($cookieHeader as $cookie) {
if (\strlen($cookie) > self::MAX_SET_COOKIE_FIELD_LENGTH) {
continue;
}
$sc = SetCookie::fromString($cookie);
$domain = $sc->getDomain();
if ($domain === null || $domain === '') {
$sc->setDomain($request->getUri()->getHost());
$sc->setHostOnly(true);
} elseif (\substr($domain, -1) === '.' && '' !== \trim($domain, '.')) {
// Keep pure-dot domains rejected by the dot-only fix.
$sc->setDomain($request->getUri()->getHost());
$sc->setHostOnly(true);
} else {
$sc->setHostOnly(false);
}
if (0 !== \strpos($sc->getPath(), '/')) {
$sc->setPath($this->getCookiePathFromRequest($request));
}
if (!$sc->matchesDomain($request->getUri()->getHost())) {
continue;
}
// Note: At this point `$sc->getDomain()` being a public suffix should
// be rejected, but we don't want to pull in the full PSL dependency.
if ($this->setCookie($sc) && ++$accepted === self::MAX_SET_COOKIE_FIELDS) {
break;
}
}
}
}
/**
* Computes cookie path following RFC 6265 section 5.1.4
*
* @see https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4
*/
private function getCookiePathFromRequest(RequestInterface $request): string
{
$uriPath = $request->getUri()->getPath();
if ('' === $uriPath) {
return '/';
}
if (0 !== \strpos($uriPath, '/')) {
return '/';
}
if ('/' === $uriPath) {
return '/';
}
$lastSlashPos = \strrpos($uriPath, '/');
if (0 === $lastSlashPos || false === $lastSlashPos) {
return '/';
}
return \substr($uriPath, 0, $lastSlashPos);
}
public function withCookieHeader(RequestInterface $request): RequestInterface
{
$values = [];
$headerLength = 8;
$uri = $request->getUri();
$scheme = $uri->getScheme();
$host = $uri->getHost();
$path = $uri->getPath() ?: '/';
foreach ($this->cookies as $cookie) {
if ($cookie->getDomain() !== null
&& $cookie->matchesPath($path)
&& $cookie->matchesDomain($host)
&& !$cookie->isExpired()
&& (!$cookie->getSecure() || $scheme === 'https')
) {
$name = (string) $cookie->getName();
$value = (string) $cookie->getValue();
$separatorLength = $values === [] ? 0 : 2;
$valueLength = \strlen($name) + 1 + \strlen($value);
if ($headerLength + $separatorLength + $valueLength > self::MAX_COOKIE_HEADER_LENGTH) {
break;
}
$values[] = $name.'='.$value;
$headerLength += $separatorLength + $valueLength;
if (\count($values) === self::MAX_REQUEST_COOKIES) {
break;
}
}
}
return $values
? $request->withHeader('Cookie', \implode('; ', $values))
: $request;
}
/**
* If a cookie already exists and the server asks to set it again with a
* null value, the cookie must be deleted.
*/
private function removeCookieIfEmpty(SetCookie $cookie): void
{
$cookieValue = $cookie->getValue();
if (($cookieValue === null || $cookieValue === '') && $cookie->getDomain() !== null) {
$this->removeCookie($cookie);
}
}
private function removeCookie(SetCookie $cookie): void
{
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $stored) use ($cookie): bool {
return !($stored->getName() === $cookie->getName()
&& $stored->getPath() === $cookie->getPath()
&& self::cookieDomainsEqual($stored->getDomain(), $cookie->getDomain())
&& $stored->getHostOnly() === $cookie->getHostOnly());
}
);
}
private static function cookieDomainsEqual(?string $first, ?string $second): bool
{
if ($first === null || $second === null) {
return $first === $second;
}
if (isset($first[0]) && $first[0] === '.') {
$first = \substr($first, 1);
}
if (isset($second[0]) && $second[0] === '.') {
$second = \substr($second, 1);
}
return Psr7\Utils::caselessEquals($first, $second);
}
}
@@ -0,0 +1,80 @@
<?php
namespace GuzzleHttp\Cookie;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Stores HTTP cookies.
*
* It extracts cookies from HTTP requests, and returns them in HTTP responses.
* CookieJarInterface instances automatically expire contained cookies when
* necessary. Subclasses are also responsible for storing and retrieving
* cookies from a file, database, etc.
*
* @see https://docs.python.org/2/library/cookielib.html Inspiration
*
* @extends \IteratorAggregate<SetCookie>
*/
interface CookieJarInterface extends \Countable, \IteratorAggregate
{
/**
* Create a request with added cookie headers.
*
* If no matching cookies are found in the cookie jar, then no Cookie
* header is added to the request and the same request is returned.
*
* @param RequestInterface $request Request object to modify.
*
* @return RequestInterface returns the modified request.
*/
public function withCookieHeader(RequestInterface $request): RequestInterface;
/**
* Extract cookies from an HTTP response and store them in the CookieJar.
*
* @param RequestInterface $request Request that was sent
* @param ResponseInterface $response Response that was received
*/
public function extractCookies(RequestInterface $request, ResponseInterface $response): void;
/**
* Sets a cookie in the cookie jar.
*
* @param SetCookie $cookie Cookie to set.
*
* @return bool Returns true on success or false on failure
*/
public function setCookie(SetCookie $cookie): bool;
/**
* Remove cookies currently held in the cookie jar.
*
* Invoking this method without arguments will empty the whole cookie jar.
* If given a $domain argument only cookies belonging to that domain will
* be removed. If given a $domain and $path argument, cookies belonging to
* the specified path within that domain are removed. If given all three
* arguments, then the cookie with the specified name, path and domain is
* removed.
*
* @param string|null $domain Clears cookies matching a domain
* @param string|null $path Clears cookies matching a domain and path
* @param string|null $name Clears cookies matching a domain, path, and name
*/
public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void;
/**
* Discard all sessions cookies.
*
* Removes cookies that don't have an expire field or a have a discard
* field set to true. To be called when the user agent shuts down according
* to RFC 2965.
*/
public function clearSessionCookies(): void;
/**
* Converts the cookie jar to an array.
*/
public function toArray(): array;
}
@@ -0,0 +1,121 @@
<?php
namespace GuzzleHttp\Cookie;
use GuzzleHttp\Exception\InvalidArgumentException;
/**
* Persists non-session cookies using a JSON formatted file
*/
class FileCookieJar extends CookieJar
{
/**
* @var string filename
*/
private $filename;
/**
* @var bool Control whether to persist session cookies or not.
*/
private $storeSessionCookies;
/**
* Create a new FileCookieJar object
*
* @param string $cookieFile File to store the cookie data
* @param bool $storeSessionCookies Set to true to store session cookies
* in the cookie jar.
*
* @throws \RuntimeException if the file cannot be found or created
*/
public function __construct(string $cookieFile, bool $storeSessionCookies = false)
{
parent::__construct();
$this->filename = $cookieFile;
$this->storeSessionCookies = $storeSessionCookies;
if (\file_exists($cookieFile)) {
$this->load($cookieFile);
}
}
/**
* Saves the file when shutting down
*/
public function __destruct()
{
$this->save($this->filename);
}
/**
* Saves the cookies to a file.
*
* @param string $filename File to save
*
* @throws \RuntimeException if the file cannot be found or created
*/
public function save(string $filename): void
{
$json = [];
/** @var SetCookie $cookie */
foreach ($this as $cookie) {
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
$data = $cookie->toArray();
$data['HostOnly'] = $cookie->getHostOnly();
$json[] = $data;
}
}
$jsonStr = \json_encode($json);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new InvalidArgumentException('json_encode error: '.\json_last_error_msg());
}
/** @var non-empty-string $jsonStr */
if (false === \file_put_contents($filename, $jsonStr, \LOCK_EX)) {
throw new \RuntimeException("Unable to save file {$filename}");
}
}
/**
* Load cookies from a JSON formatted file.
*
* Old cookies are kept unless overwritten by newly loaded ones.
*
* @param string $filename Cookie file to load.
*
* @throws \RuntimeException if the file cannot be loaded.
*/
public function load(string $filename): void
{
$json = \file_get_contents($filename);
if (false === $json) {
throw new \RuntimeException("Unable to load file {$filename}");
}
if ($json === '') {
return;
}
$data = \json_decode($json, true);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new InvalidArgumentException('json_decode error: '.\json_last_error_msg());
}
if (\is_array($data)) {
$cookies = [];
foreach ($data as $cookie) {
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
throw new \RuntimeException("Invalid cookie file: {$filename}");
}
$cookies[] = new SetCookie($cookie);
}
foreach ($cookies as $cookie) {
$this->setCookie($cookie);
}
} elseif (\is_scalar($data) && !empty($data)) {
throw new \RuntimeException("Invalid cookie file: {$filename}");
}
}
}
@@ -0,0 +1,99 @@
<?php
namespace GuzzleHttp\Cookie;
/**
* Persists cookies in the client session
*/
class SessionCookieJar extends CookieJar
{
/**
* @var string session key
*/
private $sessionKey;
/**
* @var bool Control whether to persist session cookies or not.
*/
private $storeSessionCookies;
/**
* Create a new SessionCookieJar object
*
* @param string $sessionKey Session key name to store the cookie
* data in session
* @param bool $storeSessionCookies Set to true to store session cookies
* in the cookie jar.
*/
public function __construct(string $sessionKey, bool $storeSessionCookies = false)
{
parent::__construct();
$this->sessionKey = $sessionKey;
$this->storeSessionCookies = $storeSessionCookies;
$this->load();
}
/**
* Saves cookies to session when shutting down
*/
public function __destruct()
{
$this->save();
}
/**
* Save cookies to the client session
*/
public function save(): void
{
$json = [];
/** @var SetCookie $cookie */
foreach ($this as $cookie) {
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
$data = $cookie->toArray();
$data['HostOnly'] = $cookie->getHostOnly();
$json[] = $data;
}
}
$json = \json_encode($json);
if (false === $json) {
throw new \RuntimeException('Unable to encode cookie data');
}
$_SESSION[$this->sessionKey] = $json;
}
/**
* Load the contents of the client session into the data array
*/
protected function load(): void
{
if (!isset($_SESSION[$this->sessionKey])) {
return;
}
$json = $_SESSION[$this->sessionKey];
if (!\is_string($json)) {
throw new \RuntimeException('Invalid cookie data');
}
$data = \json_decode($json, true);
if (\is_array($data)) {
$cookies = [];
foreach ($data as $cookie) {
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
throw new \RuntimeException('Invalid cookie data');
}
$cookies[] = new SetCookie($cookie);
}
foreach ($cookies as $cookie) {
$this->setCookie($cookie);
}
} elseif (\is_scalar($data) && \strlen((string) $data)) {
throw new \RuntimeException('Invalid cookie data');
}
}
}
@@ -0,0 +1,611 @@
<?php
namespace GuzzleHttp\Cookie;
use GuzzleHttp\Handler\HostValidator;
use GuzzleHttp\Psr7;
/**
* Set-Cookie object
*/
class SetCookie
{
/**
* @var array
*/
private static $defaults = [
'Name' => null,
'Value' => null,
'Domain' => null,
'Path' => '/',
'Max-Age' => null,
'Expires' => null,
'Secure' => false,
'Discard' => false,
'HttpOnly' => false,
];
/**
* @var array Cookie data
*/
private $data;
/**
* @var bool Whether this cookie was set without a Domain attribute
*/
private $hostOnly = false;
/**
* Create a new SetCookie object from a string.
*
* @param string $cookie Set-Cookie header string
*/
public static function fromString(string $cookie): self
{
// Create the default return array
$data = self::$defaults;
// Explode the cookie string using a series of semicolons
$pieces = \array_filter(\array_map(static function (string $piece): string {
return \trim($piece, " \n\r\t\0\x0B");
}, \explode(';', $cookie)));
// The name of the cookie (first kvp) must exist and include an equal sign.
if (!isset($pieces[0]) || \strpos($pieces[0], '=') === false) {
return new self($data);
}
// Add the cookie pieces into the parsed data array
foreach ($pieces as $part) {
$cookieParts = \explode('=', $part, 2);
$key = \trim($cookieParts[0], " \n\r\t\0\x0B");
$value = isset($cookieParts[1])
? \trim($cookieParts[1], " \n\r\t\0\x0B")
: true;
// Only check for non-cookies when cookies have been found
if (!isset($data['Name'])) {
$data['Name'] = $key;
$data['Value'] = $value;
} else {
foreach (\array_keys(self::$defaults) as $search) {
if (Psr7\Utils::caselessEquals($search, $key)) {
if ($search === 'Max-Age') {
if (is_numeric($value)) {
$data[$search] = (int) $value;
}
} elseif ($search === 'Secure' || $search === 'Discard' || $search === 'HttpOnly') {
if ($value) {
$data[$search] = true;
}
} else {
$data[$search] = $value;
}
continue 2;
}
}
if (Psr7\Utils::caselessEquals('HostOnly', $key)) {
continue;
}
$data[$key] = $value;
}
}
return new self($data);
}
/**
* @param array $data Array of cookie data provided by a Cookie parser
*/
public function __construct(array $data = [])
{
$this->data = self::$defaults;
if (\array_key_exists('HostOnly', $data)) {
if (!\is_bool($data['HostOnly'])) {
throw new \InvalidArgumentException('Cookie field "HostOnly" must be a boolean');
}
$this->setHostOnly($data['HostOnly']);
unset($data['HostOnly']);
}
if (isset($data['Name'])) {
$this->setName($data['Name']);
}
if (isset($data['Value'])) {
$this->setValue($data['Value']);
}
if (isset($data['Domain'])) {
$this->setDomain($data['Domain']);
}
if (isset($data['Path'])) {
$this->setPath($data['Path']);
}
if (isset($data['Max-Age'])) {
$this->setMaxAge($data['Max-Age']);
}
if (isset($data['Expires'])) {
$this->setExpires($data['Expires']);
}
if (isset($data['Secure'])) {
$this->setSecure($data['Secure']);
}
if (isset($data['Discard'])) {
$this->setDiscard($data['Discard']);
}
if (isset($data['HttpOnly'])) {
$this->setHttpOnly($data['HttpOnly']);
}
// Set the remaining values that don't have extra validation logic
foreach (array_diff(array_keys($data), array_keys(self::$defaults)) as $key) {
$this->data[$key] = $data[$key];
}
// Extract the Expires value and turn it into a UNIX timestamp if needed
$maxAge = $this->getMaxAge();
if (!$this->getExpires() && $maxAge !== null) {
// Calculate the Expires date
$this->setExpires(self::maxAgeToExpires($maxAge, \time()));
} elseif (null !== ($expires = $this->getExpires()) && !\is_numeric($expires)) {
$this->setExpires($expires);
}
}
private static function maxAgeToExpires(int $maxAge, int $now): int
{
if ($maxAge <= 0) {
return $now - 1;
}
if ($maxAge > \PHP_INT_MAX - $now) {
return \PHP_INT_MAX;
}
return $now + $maxAge;
}
public function __toString()
{
$str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; ';
foreach ($this->data as $k => $v) {
if ($k === 'Domain' && $this->getHostOnly()) {
continue;
}
if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) {
if ($k === 'Expires') {
$str .= 'Expires='.\gmdate('D, d M Y H:i:s \G\M\T', $v).'; ';
} else {
$str .= ($v === true ? $k : "{$k}={$v}").'; ';
}
}
}
return \rtrim($str, '; ');
}
public function toArray(): array
{
$data = $this->data;
if ($this->getHostOnly()) {
$data['HostOnly'] = true;
}
return $data;
}
/**
* Get the cookie name.
*
* @return string
*/
public function getName()
{
return $this->data['Name'];
}
/**
* Set the cookie name.
*
* @param string $name Cookie name
*/
public function setName($name): void
{
if (!is_string($name)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Name'] = (string) $name;
}
/**
* Get the cookie value.
*
* @return string|null
*/
public function getValue()
{
return $this->data['Value'];
}
/**
* Set the cookie value.
*
* @param string $value Cookie value
*/
public function setValue($value): void
{
if (!is_string($value)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Value'] = (string) $value;
}
/**
* Get the domain.
*
* @return string|null
*/
public function getDomain()
{
return $this->data['Domain'];
}
/**
* Set the domain of the cookie.
*
* @param string|null $domain
*/
public function setDomain($domain): void
{
if (!is_string($domain) && null !== $domain) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Domain'] = null === $domain ? null : (string) $domain;
}
/**
* Get whether this cookie is scoped to the origin host only.
*
* @return bool
*/
public function getHostOnly()
{
return $this->hostOnly;
}
/**
* Set whether this cookie is scoped to the origin host only.
*
* @param bool $hostOnly Set to true for host-only cookies
*/
public function setHostOnly(bool $hostOnly): void
{
$this->hostOnly = $hostOnly;
}
/**
* Get the path.
*
* @return string
*/
public function getPath()
{
return $this->data['Path'];
}
/**
* Set the path of the cookie.
*
* @param string $path Path of the cookie
*/
public function setPath($path): void
{
if (!is_string($path)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Path'] = (string) $path;
}
/**
* Maximum lifetime of the cookie in seconds.
*
* @return int|null
*/
public function getMaxAge()
{
return null === $this->data['Max-Age'] ? null : (int) $this->data['Max-Age'];
}
/**
* Set the max-age of the cookie.
*
* @param int|null $maxAge Max age of the cookie in seconds
*/
public function setMaxAge($maxAge): void
{
if (!is_int($maxAge) && null !== $maxAge) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Max-Age'] = $maxAge === null ? null : (int) $maxAge;
}
/**
* The UNIX timestamp when the cookie Expires.
*
* @return string|int|null
*/
public function getExpires()
{
return $this->data['Expires'];
}
/**
* Set the unix timestamp for which the cookie will expire.
*
* @param int|string|null $timestamp Unix timestamp or any English textual datetime description.
*/
public function setExpires($timestamp): void
{
if (!is_int($timestamp) && !is_string($timestamp) && null !== $timestamp) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int, string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
if (null === $timestamp) {
$this->data['Expires'] = null;
} elseif (\is_numeric($timestamp)) {
$this->data['Expires'] = (int) $timestamp;
} else {
// Store unparseable dates as session cookies, not as expired cookies.
$expires = \strtotime((string) $timestamp);
$this->data['Expires'] = $expires === false ? null : $expires;
}
}
/**
* Get whether or not this is a secure cookie.
*
* @return bool
*/
public function getSecure()
{
return $this->data['Secure'];
}
/**
* Set whether or not the cookie is secure.
*
* @param bool $secure Set to true or false if secure
*/
public function setSecure($secure): void
{
if (!is_bool($secure)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Secure'] = (bool) $secure;
}
/**
* Get whether or not this is a session cookie.
*
* @return bool|null
*/
public function getDiscard()
{
return $this->data['Discard'];
}
/**
* Set whether or not this is a session cookie.
*
* @param bool $discard Set to true or false if this is a session cookie
*/
public function setDiscard($discard): void
{
if (!is_bool($discard)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Discard'] = (bool) $discard;
}
/**
* Get whether or not this is an HTTP only cookie.
*
* @return bool
*/
public function getHttpOnly()
{
return $this->data['HttpOnly'];
}
/**
* Set whether or not this is an HTTP only cookie.
*
* @param bool $httpOnly Set to true or false if this is HTTP only
*/
public function setHttpOnly($httpOnly): void
{
if (!is_bool($httpOnly)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['HttpOnly'] = (bool) $httpOnly;
}
/**
* Check if the cookie matches a path value.
*
* A request-path path-matches a given cookie-path if at least one of
* the following conditions holds:
*
* - The cookie-path and the request-path are identical.
* - The cookie-path is a prefix of the request-path, and the last
* character of the cookie-path is %x2F ("/").
* - The cookie-path is a prefix of the request-path, and the first
* character of the request-path that is not included in the cookie-
* path is a %x2F ("/") character.
*
* @param string $requestPath Path to check against
*/
public function matchesPath(string $requestPath): bool
{
$cookiePath = $this->getPath();
// Match on exact matches or when path is the default empty "/"
if ($cookiePath === '/' || $cookiePath === $requestPath) {
return true;
}
// Ensure that the cookie-path is a prefix of the request path.
if (0 !== \strpos($requestPath, $cookiePath)) {
return false;
}
// Match if the last character of the cookie-path is "/"
if (\substr($cookiePath, -1, 1) === '/') {
return true;
}
// Match if the first character not included in cookie path is "/"
return \substr($requestPath, \strlen($cookiePath), 1) === '/';
}
/**
* Check if the cookie matches a domain value.
*
* @param string $domain Domain to check against
*/
public function matchesDomain(string $domain): bool
{
$cookieDomain = $this->getDomain();
if (null === $cookieDomain) {
return !$this->getHostOnly();
}
if ($this->getHostOnly()) {
return Psr7\Utils::asciiToLower($domain) === Psr7\Utils::asciiToLower($cookieDomain);
}
// Remove the leading '.' as per spec in RFC 6265.
// https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.3
$cookieDomain = Psr7\Utils::asciiToLower($cookieDomain);
if ($cookieDomain !== '' && $cookieDomain[0] === '.') {
/** @var string */
$cookieDomain = \substr($cookieDomain, 1);
}
if ('' === $cookieDomain) {
return false;
}
$domain = Psr7\Utils::asciiToLower($domain);
if ($domain === $cookieDomain) {
return true;
}
// A percent-escaped cookie domain can decode to another host spelling.
// Keep it exact-match-only to avoid extending that host's cookie scope.
if (\strpos($cookieDomain, '%') !== false) {
return false;
}
// IP literals and numeric hosts are exact-match-only per RFC 6265.
// Only the exact match above may succeed for those cookie domains.
if (self::isIpAddressOrNumericHost($cookieDomain)) {
return false;
}
// Matching the subdomain according to RFC 6265.
// https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3
if (\filter_var($domain, \FILTER_VALIDATE_IP)) {
return false;
}
return (bool) \preg_match('/\.'.\preg_quote($cookieDomain, '/').'$/D', $domain);
}
private static function isIpAddressOrNumericHost(string $host): bool
{
// Strip one root dot before detection so trailing-dot numeric hosts
// still cannot be matched by subdomains.
if ($host !== '' && \str_ends_with($host, '.')) {
$host = \substr($host, 0, -1);
}
if (\str_starts_with($host, '[') && \str_ends_with($host, ']')) {
$host = \substr($host, 1, -1);
}
if (\filter_var($host, \FILTER_VALIDATE_IP) !== false) {
return true;
}
// Public DNS names do not have an all-numeric rightmost label; treat
// those private/internal hosts as exact-match-only too.
$labels = \explode('.', $host);
$last = (string) \end($labels);
if ($last !== '' && \ctype_digit($last)) {
return true;
}
// Apply the transport's decimal, octal and hexadecimal inet_aton-style
// grammar. Omitting range checks conservatively holds some names to an
// exact match.
return HostValidator::isNumericIpv4Host(\rtrim($host, '.'));
}
/**
* Check if the cookie is expired.
*/
public function isExpired(): bool
{
return $this->getExpires() !== null && \time() > $this->getExpires();
}
/**
* Check if the cookie is valid according to RFC 6265.
*
* @return bool|string Returns true if valid or an error message if invalid
*/
public function validate()
{
$name = $this->getName();
if ($name === '') {
return 'The cookie name must not be empty';
}
// Check if any of the invalid characters are present in the cookie name
if (\preg_match('/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/', $name) !== 0) {
return 'Cookie name must not contain invalid characters: ASCII '
.'Control characters (0-31;127), space, tab and the '
.'following characters: ()<>@,;:\"/?={}';
}
// Value must not be null. 0 and empty string are valid. Empty strings
// are technically against RFC 6265, but known to happen in the wild.
$value = $this->getValue();
if ($value === null) {
return 'The cookie value must not be empty';
}
// Domains must not be empty, but may be omitted. "0" is not a valid
// internet domain, but may be used as server name in a private network.
$domain = $this->getDomain();
if ($domain === '' || (null !== $domain && '' === \ltrim(\trim($domain, " \n\r\t\0\x0B"), '.'))) {
return 'The cookie domain must not be empty';
}
return true;
}
}
@@ -0,0 +1,39 @@
<?php
namespace GuzzleHttp\Exception;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Exception when an HTTP error occurs (4xx or 5xx error)
*/
class BadResponseException extends RequestException
{
public function __construct(
string $message,
RequestInterface $request,
ResponseInterface $response,
?\Throwable $previous = null,
array $handlerContext = []
) {
parent::__construct($message, $request, $response, $previous, $handlerContext);
}
/**
* Current exception and the ones that extend it will always have a response.
*/
public function hasResponse(): bool
{
return true;
}
/**
* This function narrows the return type from the parent class and does not allow it to be nullable.
*/
public function getResponse(): ResponseInterface
{
/** @var ResponseInterface */
return parent::getResponse();
}
}
@@ -0,0 +1,10 @@
<?php
namespace GuzzleHttp\Exception;
/**
* Exception when a client error is encountered (4xx codes)
*/
class ClientException extends BadResponseException
{
}
@@ -0,0 +1,54 @@
<?php
namespace GuzzleHttp\Exception;
use Psr\Http\Client\NetworkExceptionInterface;
use Psr\Http\Message\RequestInterface;
/**
* Exception thrown when a connection cannot be established.
*/
class ConnectException extends TransferException implements NetworkExceptionInterface
{
/**
* @var RequestInterface
*/
private $request;
/**
* @var array
*/
private $handlerContext;
public function __construct(
string $message,
RequestInterface $request,
?\Throwable $previous = null,
array $handlerContext = []
) {
parent::__construct($message, 0, $previous);
$this->request = $request;
$this->handlerContext = $handlerContext;
}
/**
* Get the request that caused the exception
*/
public function getRequest(): RequestInterface
{
return $this->request;
}
/**
* Get contextual information about the error from the underlying handler.
*
* The contents of this array will vary depending on which handler you are
* using. It may also be just an empty array. Relying on this data will
* couple you to a specific handler, but can give more debug information
* when needed.
*/
public function getHandlerContext(): array
{
return $this->handlerContext;
}
}
@@ -0,0 +1,9 @@
<?php
namespace GuzzleHttp\Exception;
use Psr\Http\Client\ClientExceptionInterface;
interface GuzzleException extends ClientExceptionInterface
{
}
@@ -0,0 +1,7 @@
<?php
namespace GuzzleHttp\Exception;
final class InvalidArgumentException extends \InvalidArgumentException implements GuzzleException
{
}
@@ -0,0 +1,154 @@
<?php
namespace GuzzleHttp\Exception;
use GuzzleHttp\BodySummarizer;
use GuzzleHttp\BodySummarizerInterface;
use Psr\Http\Client\RequestExceptionInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* HTTP Request exception
*/
class RequestException extends TransferException implements RequestExceptionInterface
{
/**
* @var RequestInterface
*/
private $request;
/**
* @var ResponseInterface|null
*/
private $response;
/**
* @var array
*/
private $handlerContext;
public function __construct(
string $message,
RequestInterface $request,
?ResponseInterface $response = null,
?\Throwable $previous = null,
array $handlerContext = []
) {
// Set the code of the exception if the response is set and not future.
$code = $response ? $response->getStatusCode() : 0;
parent::__construct($message, $code, $previous);
$this->request = $request;
$this->response = $response;
$this->handlerContext = $handlerContext;
}
/**
* Wrap non-RequestExceptions with a RequestException
*
* @deprecated since 7.11. Create a RequestException directly instead.
*/
public static function wrapException(RequestInterface $request, \Throwable $e): RequestException
{
\trigger_deprecation('guzzlehttp/guzzle', '7.11', '%s::wrapException() is deprecated and will be removed in 8.0. Create a %s directly instead.', self::class, self::class);
return $e instanceof RequestException ? $e : new RequestException($e->getMessage(), $request, null, $e);
}
/**
* Factory method to create a new exception with a normalized error message
*
* @param RequestInterface $request Request sent
* @param ResponseInterface $response Response received
* @param \Throwable|null $previous Previous exception
* @param array $handlerContext Optional handler context
* @param BodySummarizerInterface|null $bodySummarizer Optional body summarizer
*/
public static function create(
RequestInterface $request,
?ResponseInterface $response = null,
?\Throwable $previous = null,
array $handlerContext = [],
?BodySummarizerInterface $bodySummarizer = null
): self {
if (!$response) {
return new self(
'Error completing request',
$request,
null,
$previous,
$handlerContext
);
}
$level = (int) \floor($response->getStatusCode() / 100);
if ($level === 4) {
$label = 'Client error';
$className = ClientException::class;
} elseif ($level === 5) {
$label = 'Server error';
$className = ServerException::class;
} else {
$label = 'Unsuccessful request';
$className = __CLASS__;
}
$uri = \GuzzleHttp\Psr7\Utils::redactUserInfo($request->getUri());
// Client Error: `GET /` resulted in a `404 Not Found` response:
// <html> ... (truncated)
$message = \sprintf(
'%s: `%s %s` resulted in a `%s %s` response',
$label,
$request->getMethod(),
$uri->__toString(),
$response->getStatusCode(),
$response->getReasonPhrase()
);
$summary = ($bodySummarizer ?? new BodySummarizer())->summarize($response);
if ($summary !== null) {
$message .= ":\n{$summary}\n";
}
return new $className($message, $request, $response, $previous, $handlerContext);
}
/**
* Get the request that caused the exception
*/
public function getRequest(): RequestInterface
{
return $this->request;
}
/**
* Get the associated response
*/
public function getResponse(): ?ResponseInterface
{
return $this->response;
}
/**
* Check if a response was received
*/
public function hasResponse(): bool
{
return $this->response !== null;
}
/**
* Get contextual information about the error from the underlying handler.
*
* The contents of this array will vary depending on which handler you are
* using. It may also be just an empty array. Relying on this data will
* couple you to a specific handler, but can give more debug information
* when needed.
*/
public function getHandlerContext(): array
{
return $this->handlerContext;
}
}
@@ -0,0 +1,10 @@
<?php
namespace GuzzleHttp\Exception;
/**
* Exception when a server error is encountered (5xx codes)
*/
class ServerException extends BadResponseException
{
}
@@ -0,0 +1,7 @@
<?php
namespace GuzzleHttp\Exception;
class TooManyRedirectsException extends RequestException
{
}
@@ -0,0 +1,7 @@
<?php
namespace GuzzleHttp\Exception;
class TransferException extends \RuntimeException implements GuzzleException
{
}

Some files were not shown because too many files have changed in this diff Show More