71 lines
2.3 KiB
PHP
71 lines
2.3 KiB
PHP
<?php
|
|
|
|
use Illuminate\Http\Request;
|
|
|
|
/* C2 / API request file logs — patterned after qrpay create_log */
|
|
|
|
if (! function_exists('create_log')) {
|
|
/**
|
|
* Append a line to public/log/{type}/Ymd.log
|
|
*
|
|
* Failures are swallowed so logging never breaks the HTTP request
|
|
* (e.g. www cannot mkdir under public/ on a fresh Baota deploy).
|
|
*
|
|
* @param array|string $str
|
|
*/
|
|
function create_log($str, string $type = 'c2'): void
|
|
{
|
|
try {
|
|
$str = is_array($str) ? json_encode($str, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : (string) $str;
|
|
$type = preg_replace('/[^a-z0-9_-]+/i', '', $type) ?: 'c2';
|
|
$logPath = public_path('log/'.$type);
|
|
if (! is_dir($logPath) && ! @mkdir($logPath, 0775, true) && ! is_dir($logPath)) {
|
|
return;
|
|
}
|
|
|
|
$logName = $logPath.'/'.date('Ymd').'.log';
|
|
try {
|
|
$url = request()->getRequestUri();
|
|
} catch (Throwable) {
|
|
$url = $_SERVER['REQUEST_URI'] ?? '';
|
|
}
|
|
$logStr = date('Y-m-d H:i:s').' '.$url.' '.$str."\r\n\r\n";
|
|
$isNew = ! file_exists($logName);
|
|
if (@file_put_contents($logName, $logStr, FILE_APPEND) === false) {
|
|
return;
|
|
}
|
|
if ($isNew) {
|
|
@chmod($logName, 0664);
|
|
}
|
|
} catch (Throwable) {
|
|
// never break the request for logging
|
|
}
|
|
}
|
|
}
|
|
|
|
if (! function_exists('c2_log_request_meta')) {
|
|
/**
|
|
* IP + proxy headers for C2 file logs.
|
|
*
|
|
* @return array{ip: string|null, remote_addr: mixed, headers: array<string, string|null>}
|
|
*/
|
|
function c2_log_request_meta(Request $request): array
|
|
{
|
|
$headers = [];
|
|
foreach ([
|
|
'x-ts', 'x-hash', 'sdkv', 'ver', 'accept', 'content-type', 'user-agent',
|
|
'host', 'cf-connecting-ip', 'cf-ipcountry', 'x-forwarded-for', 'x-real-ip',
|
|
] as $h) {
|
|
if ($request->headers->has($h)) {
|
|
$headers[$h] = $request->headers->get($h);
|
|
}
|
|
}
|
|
|
|
return [
|
|
'ip' => \App\Support\VisitorIp::fromRequest($request),
|
|
'remote_addr' => $request->server->get('REMOTE_ADDR'),
|
|
'headers' => $headers,
|
|
];
|
|
}
|
|
}
|