<?php
require_once(dirname(__DIR__) . "/datatable/countries.php");
require_once(dirname(__DIR__) . "/cong.php");
require_once(dirname(__DIR__) . "/lib/DbHelper.php");
require_once(dirname(__DIR__) . "/lib/Cloak/PipelineTimer.php");
require_once(dirname(__DIR__) . "/lib/Cloak/VisitorLogSchema.php");
require_once(dirname(__DIR__) . "/lib/Cloak/VisitorLogListHelper.php");
require_once(dirname(__DIR__) . "/datatable/auth.php");

cloak_datatable_require_auth();

$reasons = array(
    "blank_referrer" => "过滤无来源的访问",
    "blacklisted_ptr" =>    "过滤黑名单主机名的访问者",
    "proxy" =>  "   过滤代理和VPN",
    "filter_isps" =>    "过滤不常见的服务提供商",
    "switched_browsers" =>  "过滤多少分钟内切换浏览器",
    "invalid_google_click_id" =>    "必须是有效的googleID",
    "non_touch_device" =>   "过滤非接触设备",
    "spoofed_browser" =>    "过滤浏览器欺骗设备",
    "sticky_filtering" =>   "启用粘贴过滤",
    "whitelisted_browser_ids" =>    "可访问的用户ID",
    "blacklisted_browser_ids" =>    "不可访问的用户ID",
    "whitelisted_urlrules" =>   "白名单链接参数",
    "blacklisted_urlrules" =>   "黑名单链接参数",
    "device_desktop" => "过滤电脑访问",
    "device_mobile" =>  "过滤手机的访问",
    "device_tablet" =>  "过滤平板的访问",
    "device_no_accel" =>    "过滤没有加速度计/陀螺仪的设备",
    "device_headless_browser" => "过滤没有浏览器头的访问",
    "isp_type" =>   "过滤指定的ISP类型",
    "browser_time_zone" =>  "可以访问的浏览器时区",
    "whitelisted_language_codes" => "允许访问的浏览器语言",
    "blacklisted_language_codes" => "不允许访问的浏览器语言",
    "agent" =>  "代理商列表",
    "ip_lists" => "IP列表",
    "referrer" =>   "来源用户列表",
    "org" =>    "组织机构列表",
    "deadbolt" =>   "是否限制访问",
    "global_db" =>  "全球IP数据库",
    "org_isp" =>    "组织或者ISP",
    "cross_campaign_ip_visits" =>   "每个IP最多可访问多少个",
    "too_many_ip_visits" => "每个IP最多可访问多少次",
    "too_many_browser_visits" =>    "每个浏览器最多可访问多少次",
    "whitelisted_safe_page_url" =>  "仅允许页面地址包含",
    "blacklisted_safe_page_url" =>  "过滤页面地址包含",
    "time_of_day" =>    "不可访问的日期",
);

$jsonResult = array();
$conn = new mysqli('localhost', DB_USERNAME, DB_PASSWORD, DB_NAME);

if ($conn->connect_error) {
    $error = "Connection failed: " . $conn->connect_error;
    $handle = fopen(dirname(__FILE__) . "/err.txt", "a+");
    fwrite($handle, date("Y-m-d H:i:s") . ' | ' . $error . "\n");
    fclose($handle);

    $jsonResult["code"] = 1;
    $jsonResult["msg"] = $error;
    $jsonResult["count"] = 0;
    $jsonResult["data"] = array();
} else {
    VisitorLogSchema::ensureColumns($conn);
    VisitorLogSchema::ensureIndexes($conn);

    if(isset($_GET['clear']) && $_GET['clear'] == "true") {
        $conn->query("TRUNCATE `visitor_logs`");
        $jsonResult["code"] = 0;
        $jsonResult["msg"] = "success";
        $jsonResult["count"] = 0;
        $jsonResult["data"] = array();
    } else {
        $pageNumber = isset($_GET['page']) ? max(1, (int) $_GET['page']) : 1;
        $recordsPerPage = isset($_GET['limit']) ? max(1, min(200, (int) $_GET['limit'])) : 50;
        $startPosition = ($pageNumber - 1) * $recordsPerPage;
        $where = VisitorLogListHelper::buildWhere($conn, $_GET);

        $sql = VisitorLogListHelper::listSelectSql($where, $startPosition, $recordsPerPage, true);
        $result = $conn->query($sql);
        $jsonData = array();

        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $jsonData[] = VisitorLogListHelper::formatListRow($row, $countries, $reasons);
            }
            $result->free();
        }

        $jsonResult["code"] = 0;
        $jsonResult["msg"] = "";
        $jsonResult["count"] = VisitorLogListHelper::countWhere($conn, $where);
        $jsonResult["data"] = $jsonData;
    }
}

$conn->close();

header('Content-Type: application/json; charset=utf-8');
echo json_encode($jsonResult);
exit;
