<?
if (!defined("_GNUBOARD_")) exit; // 禁止单独访问此页 

// 如果ip地址与缓存ip地址不相同
if (get_cookie('ck_visit_ip') != $_SERVER['REMOTE_ADDR']) {
    set_cookie('ck_visit_ip', $_SERVER['REMOTE_ADDR'], 86400); // 储存一日

    $tmp_row = sql_fetch(" select max(vi_id) as max_vi_id from $g4[visit_table] ");
    $vi_id = $tmp_row[max_vi_id] + 1;

    // 防止改变$_SERVER变量进行注入攻击  SQL Injection  110810更新
    $remote_addr = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
    $referer     = mysql_real_escape_string($_SERVER['HTTP_REFERER']);
    $user_agent  = mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']);
    $sql = " insert $g4[visit_table] ( vi_id, vi_ip, vi_date, vi_time, vi_referer, vi_agent ) values ( '$vi_id', '$remote_addr', '$g4[time_ymd]', '$g4[time_his]', '$referer', '$user_agent' ) ";
    //$sql = " insert $g4[visit_table] ( vi_id, vi_ip, vi_date, vi_time, vi_referer, vi_agent ) values ( '$vi_id', '$_SERVER[REMOTE_ADDR]', '$g4[time_ymd]', '$g4[time_his]', '$_SERVER[HTTP_REFERER]', '$_SERVER[HTTP_USER_AGENT]' ) ";

    $result = sql_query($sql, FALSE);
    // 如果正常 INSERT 合计之后显示的统计
    if ($result) {
        $sql = " insert $g4[visit_sum_table] ( vs_count, vs_date) values ( 1, '$g4[time_ymd]' ) ";
        $result = sql_query($sql, FALSE);
        
        // DUPLICATE 如果发生错误，根据创建的日期执行 UPDATE 
        if (!$result) {
            $sql = " update $g4[visit_sum_table] set vs_count = vs_count + 1 where vs_date = '$g4[time_ymd]' ";
            $result = sql_query($sql);
        }

        // INSERT, UPDATE 如果已有数据则保存到基本数据
        // 防止每个访客都进行一次查询

        // 今天
        $sql = " select vs_count as cnt from $g4[visit_sum_table] where vs_date = '$g4[time_ymd]' ";
        $row = sql_fetch($sql);
        $vi_today = $row[cnt];

        // 昨天
        $sql = " select vs_count as cnt from $g4[visit_sum_table] where vs_date = DATE_SUB('$g4[time_ymd]', INTERVAL 1 DAY) ";
        $row = sql_fetch($sql);
        $vi_yesterday = $row[cnt];

        // 最高
        $sql = " select max(vs_count) as cnt from $g4[visit_sum_table] ";
        $row = sql_fetch($sql);
        $vi_max = $row[cnt];

        // 全部
        //$sql = " select count(*) as cnt from $g4[visit_table] ";
        $sql = " select sum(vs_count) as total from $g4[visit_sum_table] "; 
        $row = sql_fetch($sql);
        $vi_sum = $row[total];

        $visit = "今天:$vi_today,昨天:$vi_yesterday,最高:$vi_max,全部:$vi_sum";

        // 储存到基本数据后 
        // 直接显示访问数据
        // 优化数据查询效率
        sql_query(" update $g4[config_table] set cf_visit = '$visit' ");
    }
}
?>
