<?php
//main db
$db = new SQLite3('.db.db');

//dns
$rows3 = $db->query("SELECT * FROM dns");
$rows = array();
while ($row = $rows3->fetchArray(SQLITE3_ASSOC)) {
	$rows[] = $row['url'];
}

function getresult($url, $port)
{
    global $httpcode;
    $bad_status_codes = [404, 401];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_2; en-US) AppleWebKit/532.8 (KHTML, like Gecko) Chrome/4.0.302.2 Safari/532.8");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    $html = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if (in_array($httpcode, $bad_status_codes)) {
        $html = false;
    } else {
        if (!is_string($html)) {
            $html = true;
        }
    }
    return $html;
}

$httpcode = NULL;
foreach ($rows as $portal) {
    if (!empty($portal)) {
        $url = $portal . "/xmltv.php?" . http_build_query($_POST) . str_replace("%40", "@", $_SERVER["QUERY_STRING"]);
        parse_str($_SERVER["QUERY_STRING"], $result_array);
        $_SERVER["QUERY_STRING"] = http_build_query($result_array);
        $portalseg = explode(":", $portal);
        $res = getresult($url, isset($portalseg[2]) ? $portalseg[2] : "80");
        if (!($res === false || is_string($res) && strpos($res, "{\"user_info\":{\"auth\":0}}") !== false || is_string($res) && strpos($res, "{\"success\": true}") !== false)) {
            header("HTTP/1.1 301 Moved Permanently");
            header("Location: " . $url . "", true, 301);
            exit;
        }
    }
}


?>