<?php

die('nothing to see here anymore.');

if (isset($_GET['src'])) { die(highlight_file(__FILE__, true)); }

$threadValid = false;

// Does thread exist in cache?
if (file_exists('oelvn.txt')) {
    $threadID = file_get_contents('.oelvn.txt');
    // Is cached thread still alive?
    $info = get_headers('http://boards.4chan.org/vg/thread/' . $threadID);
    if ($info && strstr($info[0], '200') !== FALSE) {
        $threadValid = true;
    }
}

// Scrape /vg/ to find the latest thread.
if (!$threadValid) {
    $threadID = null;

    // Thank god for the 4chan API -- regexp'ing HTML is a bitch.
    for ($i = 0; $i < 5; $i++) {
        $threads = @json_decode(@file_get_contents('http://api.4chan.org/vg/' . $i . '.json'), true);

        if ($threads) {
            // Check the thread sbuject on each thread for the term OELVN General, Original English Visual Novel General, EVN General or OEL VN General.
            foreach ($threads['threads'] as $thread) {
                 if (isset($thread['posts'][0]['sub']) && preg_match('#(?:(?:OELVN|Original English Visual Novel|EVN|OEL VN) General|/evn/|/oelvn/)#i', $thread['posts'][0]['sub'], $matches)) {
                    $threadID = $thread['posts'][0]['no'];
                    break(2);
                 }
            }
        }

        // Respect 4chan's API rules: 1 req/second at most.
        sleep(1);
    }
}

if ($threadID) {
    // Cache thread ID.
    file_put_contents('.oelvn.txt', $threadID);
} else {
    die('No OELVNG found. :(');
}

header('HTTP/1.1 303 See Other');
header('Location: http://boards.4chan.org/vg/thread/' . $threadID);
