<?php
set_time_limit(0);

header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="export_'.date("Ymd").'.csv"');

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");
session_start();

if(empty($_SESSION['password']) || $_SESSION['password'] != LOGIN_PASSWORD) {
    unset($_SESSION['password']);
    unset($_SESSION['check_result']);
    die("404 Not Found");
}

$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" =>    "不可访问的日期",
);

$servername = "localhost";
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
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);

    echo "数据库连接失败";exit;
    
} else {
    VisitorLogSchema::ensureColumns($conn);
    $map = array();
    $where = 1;
   
    if(!empty($_GET['visit_date'])) {
        $map[] = "DATE_FORMAT(`visit_date`, '%Y-%m-%d') LIKE '" . cloak_db_escape($conn, $_GET['visit_date']) . "'";
    }

    $where .= cloak_visitor_log_apply_result_filter($conn, $_GET['result'] ?? '');
    
    if(!empty($_GET['country'])) {
        $map[] = "country LIKE '" . cloak_db_escape($conn, $_GET['country']) . "'";
    }
    
    if(!empty($_GET['IP'])) {
        $map[] = "IP LIKE '" . cloak_db_escape($conn, $_GET['IP']) . "'";
    }
    
    if(!empty($_GET['domain'])) {
        $map[] = "domain LIKE '%" . cloak_db_escape($conn, $_GET['domain']) . "%'";
    }
    
    if(!empty($_GET['spage'])) {
        $map[] = "page LIKE '%" . cloak_db_escape($conn, $_GET['spage']) . "%'";
    }
    
    if(!empty($map)) {
        $where .= " AND " . join(" AND ", $map);
    }
    // SQL语句
    $sql = "SELECT `id`, `campagin_id`, `visit_md5_code`, `domain`, `visit_date`, `IP`, `country`, `result`, `reason`, `fp_url`, `referer`, `vtimes`, `client`, `browser`, `page`, `language`, `user_agent`, `http_referer`, `accept_language_raw`, `judge_timing`, `fp_hdata`, `device`, `add_time` FROM `visitor_logs` WHERE {$where} ORDER BY `id` DESC";
    
    // 执行查询并输出结果
    $result = mysqli_query($conn, $sql);
    
    
    echo "\xEF\xBB\xBF";
    $fp = fopen('php://output', 'w');
    fputcsv($fp, ['id', 'campagin_id', 'visit_md5_code', 'domain', 'visit_date', 'IP', 'country', 'result', 'reason', 'fp_url', 'referer', 'vtimes', 'client', 'browser', 'page', 'language', 'user_agent', 'http_referer', 'accept_language_raw', 'judge_timing', 'fp_hdata', 'device', 'add_time']);
    while ($row = mysqli_fetch_assoc($result)) {
        $row['country'] = $countries[$row['country']];
        if(isset($reasons[$row['reason']])) {
            $row['reason'] = $reasons[$row['reason']];
        }
        if ($row['result'] === 'wait') {
            $row['result'] = '检测中';
        }
        $row['judge_timing_text'] = cloak_visitor_log_format_timing($row['judge_timing'] ?? '');
        fputcsv($fp, $row);
    }
   fclose($fp);
    exit("");
}