function build_query_js()
{
    $page = CurrentPageName();
    $tpl = new templates();
    $from = strtotime("{$_GET["date1"]} {$_GET["time1"]}");
    $to = strtotime("{$_GET["date2"]} {$_GET["time2"]}");
    $interval = $_GET["interval"];
    $t = $_GET["t"];
    $user = $_GET["user"];
    $md5 = md5("WEBSITES:{$from}{$to}{$interval}{$user}{$_GET["searchsites"]}{$_GET["searchuser"]}");
    $_SESSION["SQUID_STATS_DATE1"] = $_GET["date1"];
    $_SESSION["SQUID_STATS_TIME1"] = $_GET["time1"];
    $_SESSION["SQUID_STATS_DATE2"] = $_GET["date2"];
    $_SESSION["SQUID_STATS_TIME2"] = $_GET["time2"];
    $timetext1 = $tpl->time_to_date(strtotime("{$_GET["date1"]} {$_GET["time1"]}"), true);
    $timetext2 = $tpl->time_to_date(strtotime("{$_GET["date2"]} {$_GET["time2"]}"), true);
    $nextFunction = "LoadAjax('WEBFILTERING_STATS_MAIN_GRAPH','{$page}?main=yes&zmd5={$md5}&t={$t}');";
    $nextFunction_encoded = urlencode(base64_encode($nextFunction));
    $q = new mysql_squid_builder();
    $q->CheckReportTable();
    $ligne = mysql_fetch_array($q->QUERY_SQL("SELECT ID,builded FROM reports_cache WHERE `zmd5`='{$md5}'"));
    if (intval($ligne["ID"]) == 0) {
        $array["FROM"] = $from;
        $array["TO"] = $to;
        $array["INTERVAL"] = $interval;
        $array["USER"] = $user;
        $array["categories"] = $_GET["categories"];
        $array["searchuser"] = $_GET["searchuser"];
        $serialize = mysql_escape_string2(serialize($array));
        $title = "{webfiltering}: {$timetext1} - {to} {$timetext2} and {$user} {is} {$array["searchuser"]}";
        $sql = "INSERT IGNORE INTO `reports_cache` (`zmd5`,`title`,`report_type`,`zDate`,`params`) VALUES \n\t\t('{$md5}','{$title}','WEBFILTERING',NOW(),'{$serialize}')";
        $q->QUERY_SQL($sql);
        if (!$q->ok) {
            echo "alert('" . $tpl->javascript_parse_text($q->mysql_errror) . "')";
            return;
        }
        echo "Loadjs('squid.statistics.progress.php?zmd5={$md5}&NextFunction={$nextFunction_encoded}')";
        return;
    }
    if (intval($ligne["builded"] == 0)) {
        echo "\nfunction Start{$t}(){\n\tLoadjs('squid.statistics.progress.php?zmd5={$md5}&NextFunction={$nextFunction_encoded}&t={$t}');\n}\n\nif(document.getElementById('graph-{$t}')){\n\tdocument.getElementById('graph-{$t}').innerHTML='<center><img src=img/loader-big.gif></center>';\n}\nLockPage();\t\nsetTimeout('Start{$t}()',800);\n";
        return;
    }
    echo $nextFunction;
}
function page()
{
    $page = CurrentPageName();
    $tpl = new templates();
    $t = time();
    $title = null;
    $q = new mysql_squid_builder();
    $q->CheckReportTable();
    if ($_GET["zmd5"] == null) {
        $ligne = mysql_fetch_array($q->QUERY_SQL("SELECT title,zmd5 FROM reports_cache WHERE report_type='MEMBERS' ORDER BY zDate DESC LIMIT 0,1"));
        if (!$q->ok) {
            echo $q->mysql_error_html();
        }
        $_GET["zmd5"] = $ligne["zmd5"];
    }
    $nextFunction = "LoadAjax('table-{$t}','{$page}?table1=yes&zmd5={$_GET["zmd5"]}');";
    $content = "<center><img src=img/loader-big.gif></center>";
    $html = "{$title}<div style='width:99%;margin-bottom:10px' id='table-{$t}'>{$content}</div>\t\n\n\t\n\t\n<script>\n\t{$nextFunction}\n</script>";
    echo $tpl->_ENGINE_parse_body($html);
}
function page()
{
    $page = CurrentPageName();
    $tpl = new templates();
    $t = time();
    $title = null;
    echo "<div style='float:right;margin:5px;margin-top:5px'>" . button($tpl->_ENGINE_parse_body("{build_the_query}"), "Loadjs('{$page}?requeteur-js=yes&t={$t}')", 16) . "</div>";
    $content = "<center style='margin:50px'>" . button("{build_the_query}", "Loadjs('{$page}?requeteur-js=yes&t={$t}')", 42) . "</center>";
    $q = new mysql_squid_builder();
    $q->CheckReportTable();
    if ($_GET["zmd5"] == null) {
        $ligne = mysql_fetch_array($q->QUERY_SQL("SELECT title,zmd5 FROM reports_cache WHERE report_type='MEMBERS' ORDER BY zDate DESC LIMIT 0,1"));
        if (!$q->ok) {
            echo $q->mysql_error_html();
        }
    } else {
        $ligne = mysql_fetch_array($q->QUERY_SQL("SELECT title,zmd5 FROM reports_cache WHERE zmd5='{$_GET["zmd5"]}'"));
    }
    if ($ligne["zmd5"] != null) {
        $nextFunction = "LoadAjax('table-{$t}','{$page}?table1=yes&zmd5={$ligne["zmd5"]}');";
        $title = "<div style='font-size:30px;margin-bottom:20px'>" . $tpl->javascript_parse_text($ligne["title"]) . "</div>";
        $content = "<center><img src=img/loader-big.gif></center>";
    }
    $html = "{$title}<div style='width:99%;margin-bottom:10px' id='table-{$t}'>{$content}</div>\t\n\n\t\n\t\n<script>\n\tLoadAjaxTiny('stats-requeteur','{$page}?stats-requeteur=yes&t={$t}');\n\t{$nextFunction}\n</script>";
    echo $tpl->_ENGINE_parse_body($html);
}
function build_query_js()
{
    header("content-type: application/x-javascript");
    squid_stats_default_values();
    $page = CurrentPageName();
    $tpl = new templates();
    $q = new mysql_squid_builder();
    if (isset($_GET["from-zmd5"])) {
        $ligne = mysql_fetch_array($q->QUERY_SQL("SELECT params FROM reports_cache WHERE `zmd5`='{$_GET["from-zmd5"]}'"));
        $params = unserialize($ligne["params"]);
        $from = $params["FROM"];
        $to = $params["TO"];
        $interval = $params["INTERVAL"];
        if ($interval == 0) {
            $interval = "1h";
        }
        $USER_FIELD = $params["USER"];
        $USER_DATA = $_GET["USER_DATA"];
    } else {
        $zmd5 = $_GET["zmd5"];
        $t = time();
        $ligne = mysql_fetch_array($q->QUERY_SQL("SELECT params FROM reports_cache WHERE `zmd5`='{$zmd5}'"));
        if (!$q->ok) {
            echo "alert('" . $tpl->javascript_parse_text("{$q->mysql_error}") . "');";
            return;
        }
        $params = unserialize($ligne["params"]);
        $from = $params["FROM"];
        $to = $params["TO"];
        $interval = $params["INTERVAL"];
        if ($interval == 0) {
            $interval = "1h";
        }
        $USER_FIELD = $params["USER"];
        $USER_DATA = $_GET["USER_DATA"];
    }
    $nextFunction = "Loadjs('{$page}?build-graph-js=yes&zmd5={$zmd5}');";
    $nextFunction_encoded = urlencode(base64_encode($nextFunction));
    $q = new mysql_squid_builder();
    $q->CheckReportTable();
    $timetext1 = $tpl->time_to_date(strtotime($from), true);
    $timetext2 = $tpl->time_to_date(strtotime($to), true);
    $ligne = mysql_fetch_array($q->QUERY_SQL("SELECT ID,builded FROM reports_cache WHERE `zmd5`='{$zmd5}'"));
    if (intval($ligne["ID"]) == 0) {
        $md5 = md5("MEMBERS_UNIQ:{$from}{$to}{$interval}{$USER_FIELD}{$USER_DATA}");
        $nextFunction = "Loadjs('{$page}?build-graph-js=yes&zmd5={$md5}');";
        $nextFunction_encoded = urlencode(base64_encode($nextFunction));
        $array["FROM"] = $from;
        $array["TO"] = $to;
        $array["INTERVAL"] = $interval;
        $array["USER"] = $USER_FIELD;
        $array["SEARCH"] = $USER_DATA;
        $serialize = mysql_escape_string2(serialize($array));
        $title = "{report_member}: {$timetext1} -{$timetext2} - {$USER_DATA}";
        $sql = "INSERT IGNORE INTO `reports_cache` (`zmd5`,`title`,`report_type`,`zDate`,`params`) VALUES\n\t\t('{$md5}','{$title}','MEMBER_UNIQ',NOW(),'{$serialize}')";
        $q->QUERY_SQL($sql);
        if (!$q->ok) {
            echo "alert('" . $tpl->javascript_parse_text($q->mysql_errror) . "')";
            return;
        }
        echo "Loadjs('squid.statistics.progress.php?zmd5={$md5}&NextFunction={$nextFunction_encoded}')";
        return;
    }
    if (intval($ligne["builded"] == 0)) {
        echo "\n\t\tfunction Start{$t}(){\n\t\tLoadjs('squid.statistics.progress.php?zmd5={$md5}&NextFunction={$nextFunction_encoded}&t={$t}');\n\t}\n\n\tLockPage();\n\tsetTimeout('Start{$t}()',800);\n\t";
        return;
    }
    echo $nextFunction;
}
function showlist()
{
    $q = new mysql_squid_builder();
    $table = "mgr_client_list";
    if (!$q->TABLE_EXISTS($table)) {
        $q->CheckReportTable();
    }
    $tpl = new templates();
    $page = 1;
    $FORCE_FILTER = null;
    $total = 0;
    if (isset($_POST["sortname"])) {
        if ($_POST["sortname"] != null) {
            $ORDER = "ORDER BY {$_POST["sortname"]} {$_POST["sortorder"]}";
        }
    }
    if (isset($_POST['page'])) {
        $page = $_POST['page'];
    }
    $searchstring = string_to_flexquery();
    if ($searchstring != null) {
        $sql = "SELECT COUNT(*) as TCOUNT FROM {$table} WHERE 1 {$FORCE_FILTER} {$searchstring}";
        $ligne = mysql_fetch_array($q->QUERY_SQL($sql));
        writelogs($sql, __FUNCTION__, __FILE__, __LINE__);
        if (!$q->ok) {
            json_error_show("{$q->mysql_error}");
        }
        $total = $ligne["TCOUNT"];
    } else {
        $sql = "SELECT COUNT(*) as TCOUNT FROM {$table}";
        $ligne = mysql_fetch_array($q->QUERY_SQL($sql));
        if (!$q->ok) {
            json_error_show("{$q->mysql_error}");
        }
        $total = $ligne["TCOUNT"];
    }
    if (isset($_POST['rp'])) {
        $rp = $_POST['rp'];
    }
    $pageStart = ($page - 1) * $rp;
    $limitSql = "LIMIT {$pageStart}, {$rp}";
    $sql = "SELECT *  FROM {$table} WHERE 1 {$searchstring} {$FORCE_FILTER} {$ORDER} {$limitSql}";
    $results = $q->QUERY_SQL($sql);
    if (!$q->ok) {
        json_error_show("{$q->mysql_error}");
    }
    if (mysql_num_rows($results) == 0) {
        json_error_show("No data, {$sql}");
    }
    $data = array();
    $data['page'] = $page;
    $data['total'] = $total;
    $data['rows'] = array();
    while ($ligne = mysql_fetch_assoc($results)) {
        $md5 = md5(serialize($line));
        $CUR_CNX = numberFormat($ligne["CUR_CNX"], 0, "", " ");
        $RQS = numberFormat($ligne["RQS"], 0, "", " ");
        $TCP_HIT = numberFormat($ligne["TCP_HIT"], 0, "", " ");
        $TCP_MISS = numberFormat($ligne["TCP_MISS"], 0, "", " ");
        $TCP_REDIRECT = numberFormat($ligne["TCP_REDIRECT"], 0, "", " ");
        $TCP_TUNNEL = numberFormat($ligne["TCP_TUNNEL"], 0, "", " ");
        $TAG_NONE = numberFormat($ligne["TAG_NONE"], 0, "", " ");
        $data['rows'][] = array('id' => $md5, 'cell' => array("<span style='font-size:16px'>{$ligne["uid"]}</a></span>", "<span style='font-size:16px'>{$ligne["ipaddr"]}</a></span>", "<span style='font-size:16px'>{$CUR_CNX}</span>", "<span style='font-size:16px'>{$RQS}</span>", "<span style='font-size:16px'>{$TCP_HIT}</span>", "<span style='font-size:16px'>{$TCP_MISS}</span>", "<span style='font-size:16px'>{$TCP_REDIRECT}</span>", "<span style='font-size:16px'>{$TCP_TUNNEL}</span>", "<span style='font-size:16px'>{$TAG_NONE}</span>"));
    }
    echo json_encode($data);
}
function table_list()
{
    $tpl = new templates();
    $MyPage = CurrentPageName();
    $sock = new sockets();
    $q = new mysql_squid_builder();
    if (!$q->TABLE_EXISTS("reports_cache")) {
        $q->CheckReportTable();
    }
    $search = '%';
    if ($_GET["report_type"] != null) {
        $table = "(SELECT title,zmd5,values_size,report_type,zDate FROM reports_cache WHERE report_type='{$_GET["report_type"]}') as t";
    } else {
        $table = "(SELECT title,zmd5,values_size,report_type,zDate FROM reports_cache) as t";
    }
    $page = 1;
    if (isset($_POST["sortname"])) {
        if ($_POST["sortname"] != null) {
            $ORDER = "ORDER BY {$_POST["sortname"]} {$_POST["sortorder"]}";
        }
    }
    if (isset($_POST['page'])) {
        $page = $_POST['page'];
    }
    $searchstring = string_to_flexquery();
    $sql = "SELECT COUNT(*) as TCOUNT FROM {$table} WHERE 1 {$searchstring}";
    $ligne = mysql_fetch_array($q->QUERY_SQL($sql, "artica_backup"));
    $total = $ligne["TCOUNT"];
    if (isset($_POST['rp'])) {
        $rp = $_POST['rp'];
    }
    $pageStart = ($page - 1) * $rp;
    $limitSql = "LIMIT {$pageStart}, {$rp}";
    $sql = "SELECT *  FROM {$table} WHERE 1 {$searchstring} {$ORDER} {$limitSql}";
    $results = $q->QUERY_SQL($sql, "artica_backup");
    if (!$q->ok) {
        json_error_show($q->mysql_error);
    }
    if (mysql_num_rows($results) == 0) {
        json_error_show("no data {$sql}");
    }
    $data = array();
    $data['page'] = $page;
    $data['total'] = $total;
    $data['rows'] = array();
    while ($ligne = mysql_fetch_assoc($results)) {
        $zmd5 = $ligne["zmd5"];
        $title = $tpl->javascript_parse_text($ligne["title"]);
        $values_size = $ligne["values_size"];
        $ahref = null;
        if ($values_size > 1024) {
            $values_size = FormatBytes($values_size / 1024);
        } else {
            $values_size = "{$values_size} Bytes";
        }
        $delete = imgsimple("delete-32.png", null, "Loadjs('squid.statistics.flow.php?remove-cache-js=yes&zmd5={$zmd5}')");
        $csv = imgsimple("csv-32.png", null, "Loadjs('{$MyPage}?csv-js=yes&zmd5={$zmd5}')");
        $ligne["title"] = $tpl->javascript_parse_text($ligne["title"]);
        if ($ligne["report_type"] == "MEMBER_UNIQ") {
            $ahref = "<a href=\"javascript:blur();\" \n\t\t\tOnClick=\"javascript:Loadjs('squid.statistics.report.member.php?zmd5={$zmd5}');\"\n\t\t\tstyle='text-decoration:underline'>";
        }
        if ($ligne["report_type"] == "FLOW") {
            $ahref = "<a href=\"javascript:blur();\"\n\t\t\tOnClick=\"GoToStatsFlow('{$zmd5}');\"\n\t\t\tstyle='text-decoration:underline'>";
        }
        if ($ligne["report_type"] == "MEMBERS") {
            $ahref = "<a href=\"javascript:blur();\"\n\t\t\tOnClick=\"GoToStatsMembers('{$zmd5}');\"\n\t\t\tstyle='text-decoration:underline'>";
        }
        if ($ligne["report_type"] == "WEBSITES") {
            $ahref = "<a href=\"javascript:blur();\"\n\t\t\tOnClick=\"GoToWebsitesStats('{$zmd5}');\"\n\t\t\tstyle='text-decoration:underline'>";
        }
        if ($ligne["report_type"] == "CATEGORIES") {
            $ahref = "<a href=\"javascript:blur();\"\n\t\t\tOnClick=\"GoToStatisticsByCategories('{$zmd5}');\"\n\t\t\tstyle='text-decoration:underline'>";
        }
        if ($ligne["report_type"] == "WEBFILTERING") {
            $ahref = "<a href=\"javascript:blur();\"\n\t\t\tOnClick=\"GoToStatisticsByWebFiltering('{$zmd5}');\"\n\t\t\tstyle='text-decoration:underline'>";
        }
        $data['rows'][] = array('id' => $zmd5, 'cell' => array("<span style='font-size:18px'>{$ahref}{$ligne["title"]}</a></span>", "<span style='font-size:18px'>{$ahref}{$ligne["zDate"]}</a></span>", "<span style='font-size:18px'>{$values_size}</a></span>", "<center>{$csv}</center>", "<center>{$delete}</center>"));
    }
    echo json_encode($data);
}