<?php
/**
    应用功能块.
    基本上全局操作的功能全部在此文件处理.
*/
defined('IN_SYSTEM') === false && exit('PHPnew Blog.');
define('COOKIETIME', 86400); // 用户信息24H

# 检测出用户的访问过程
$history_array = unserialize(fun_authcode(fun_getcookie('user_history'),'DECODE'));
$history_array =  empty($history_array) === true? array():fun_array_sort($history_array,array('m'=>SORT_DESC));
unset($temp_array);

foreach($history_array AS $key => $val){
    $val['ts'] = $val['t'] = fun_enhtml($val['t']);
    $val['t'] =  fun_cutstr($val['t'],30,'');
    $history_array[$key] = $val;
}

# 加载耦合管理代码
$return = app_getallcode();
extract($return);
unset($return);

# 用户登录开始.
$data = app_user();

# 管理员判断
if($data['user_admin'] == 1){
    $data['user_posts'] = $data['user_edits'] = $data['user_deles'] = 1;
    $data['user_admin'] = 1;
}

# 如果是禁止用户,那权限清空
if($data['user_admin'] == 2){
    $data['user_posts'] = $data['user_edits'] = $data['user_deles'] = 0;
    $data['user_admin'] = 2;
}else if(empty($data['user_app']) === false){
    $data['user_posts'] = $data['user_edits'] = $data['user_deles'] = 0;
    $data['user_admin'] = 0;
}
    

# 定义常用用户信息
define('USER_UID', $data['user_id'] + 0);
define('USER_NAME',  $data['user_name']);
define('USER_EMAIL', $data['user_email']);
define('USER_ADMIN', $data['user_admin'] + 0);
define('USER_LOGO', $data['user_logo'] + 0);
define('USER_QQ', $data['useropenid']);
define('USER_EXP', $data['user_exp']+0);
# 同时为用户变量赋值
$user_uid = USER_UID;
$user_name = USER_NAME;
$user_email = USER_EMAIL;
$user_admin = USER_ADMIN;
$user_logo  = USER_LOGO;
$user_qq = USER_QQ;
$user_exp = USER_EXP >= 9999999 ? 9999999: USER_EXP;

# 用户权限变量
$user_posts = $data['user_posts']+0; // 发帖
$user_edits = $data['user_edits']+0; // 编辑
$user_deles = $data['user_deles']+0; // 删除
$user_app =   $data['user_app']+0;   // 是否在审核

# 用户信息在此销毁,以免漏洞产生
unset($data);

# 对于禁止用户, 此段判断可以过滤掉许多危险.
(IS_POST && $user_admin === 2) && fun_message('系统禁止此用户提交任何数据,请联系管理员');

// 系统设置变量释放,更新时间是1024个小时.
$cache_data_tem = cache::read('setting_cache','setting_cache.php',3686400);
if(empty($cache_data_tem) === true){
    $link_array = fun_source('setlink');        
    $cache_data = fun_source('setting');
    cache::write('setting_cache','setting_cache.php',array(1=>$cache_data,2=>$link_array));
}else{
    $cache_data = $cache_data_tem[1];
    $link_array = $cache_data_tem[2];
}

if(empty($cache_data) === true)
    exit('setting error..');

$cache_data['user_exp'] += 0;

# 当大于后台设置的积分时许可发表.
if(empty($cache_data['user_exp']) === false && $user_exp >= $cache_data['user_exp']){
    $user_posts = 1;
}

# 时区相应的配置定义
$timeoffset = empty($cache_data['timeoffset']) === false?$cache_data['timeoffset']:0;
function_exists('date_default_timezone_set') === true?@date_default_timezone_set('Etc/GMT'.($timeoffset > 0 ? '-' : '+').(abs($timeoffset))):ini_set('date.timezone','Etc/GMT'.($timeoffset > 0 ? '-' : '+').(abs($timeoffset)));
$timezone = function_exists('date_default_timezone_set') === true?date_default_timezone_get():date('e');
$timezone = strtr($timezone,array('-'=>'+','+'=>'-'));
define('GET_TIMEOFFSET',$timeoffset*3600);
$timezone_str = date('Y-m-d H:i:s',GET_TIME) ."[$timezone]";

# 系统设置几个值替换
$html['title'] = empty($cache_data['sitename']) === false?$cache_data['sitename']:$html['title'];				//默认网站名字
$html['keywords'] = empty($cache_data['sitekeywords']) === false?$cache_data['sitekeywords']:$html['sitekeywords'];
$html['description'] = empty($cache_data['sitedescription']) === false?$cache_data['sitedescription']:$html['sitedescription'];
$html['generator'] = empty($cache_data['sitegenerator']) === false?$cache_data['sitegenerator']:$html['sitegenerator'];
$html['siteicp'] = empty($cache_data['siteicp']) === false?$cache_data['siteicp']:$html['siteicp'];
#$html['style'] = empty($cache_data['style']) === false?$cache_data['style']:'default';
$html['keywords_header'] = $html['keywords'];

# 文件上传变量处理.
$attch = array();
$attch['maxsize'] = $cache_data['maxsize']+0;
$attch['attch_array'] = explode(',',$cache_data['attch_array']);

if($cache_data['attch_look'] == 1 && USER_UID){
    $attch['attch_look'] = 0;
}else{
    $attch['attch_look'] = $cache_data['attch_look'] + 0;
}

# 伪静态配置
$_CFG['htaccess'] = min($cache_data['htaccess']+0,$_config['default']['htaccess']+0);

# QQ登录变量处理
$qq_config['open'] = empty($cache_data['qq_appid']) === true?0:1; // 是否开启,1(开启) 0(关闭) 
$qq_config['oauth_consumer_key'] = $cache_data['qq_appid']; // APP ID 
$qq_config['oauth_consumer_secret'] = $cache_data['qq_appkey']; // APP KEY
$qq_config['oauth_callback'] = empty($cache_data['qq_callback']) === true?URL_HOST.'index.php?user=qqreg':$cache_data['qq_callback']; // 返回地址
$qq_config['qq_content'] = $cache_data['qq_content']+0;
define('QQKEY',empty($qq_config['oauth_consumer_key']) === true?'6ae4dda5039b45559b7f6a1845d72158':$qq_config['oauth_consumer_key']);
# config配置
empty($_config['default']['ankey']) === true && $_config['default']['ankey'] = URL_HOST;

#公共权限配置变量
$index_editday = $cache_data['editday'];
$index_indexcount = $cache_data['indexcount'];
$main_exp = $cache_data['replay_exp']+0;
$mainpost_exp = $cache_data['post_exp']+0;
$img_maxread = $cache_data['img_maxread']+0;

$cfg_catstop = $cache_data['catstop']+0;
$cfg_replay_time = $cache_data['replay_time'];
$cfg_attch_look  = $cache_data['attch_look']+0;
# 由于设置的是小时, 用相同的方式算法处理.
$cfg_redate = app_regtime($cache_data['redate']);
$cfg_login_redate = app_regtime($cache_data['login_redate']);
$cfg_attch_downtime = app_regtime($cache_data['attch_downtime']);
# 禁止此变量进入全局中.
$cache_data = null;

# 主题分级标识.
$ico_array = array(
    THREAD_TOP => '005.small',
    THREAD_DIGEST => '001.small',
    THREAD_HOT => '002.small',
    THREAD_SHOW => '006.small',
    THREAD_EDIT => '010.small',
);

# 栏目数据
$cat_array = cache::read('main_cats','main_cats.php',86400);
if(empty($cat_array) === true){
    $cat_array = fun_get_cat();
    cache::write('main_cats','main_cats.php',$cat_array);
}

$meun_array = $cat_array['meun'];
unset($cat_array['meun']);

# 常量定义.
define('GET_URL',fun_parse_url(strtr($default_parem['News_url'],array(URL_HOST=>'./'))));
define('ADM_GET_URL',$default_parem['News_url']);


# 应用函数, 全部以app开头
function app_getallcode(){
    if(defined('APP_ADMIN') === true)
        return false;
    $allcode = cache::read('allcode','allcode_cache.php');
    if(empty($allcode) === true){
       $data = fun_source('allcode');
       $allcode = array();
       foreach($data AS $val){
            if(empty($val['codes']) === false)
                $val['codes'] .= "\n <!-- {$val['tags']} -->";
            $allcode[$val['vars']] = $val['codes'];
       }
       unset($data);
       cache::write('allcode','allcode_cache.php',$allcode);
    }
   return $allcode;
}

function app_user($user = false){
    # false 默认返回cookie记录的用户信息. 
    # true 默认会查询数据后才返回, 更准确判断用户.
    # 两种返回值, 请分别判断.
    $user_http_user = empty($_REQUEST['encty']) === false? $_REQUEST['encty']:fun_getcookie('http_user');  // 上传文件时会直接传加密串过来
    
    # 先检测cookie是否存在
    $userdata = $data = array();
    if($user_http_user){
        parse_str(fun_authcode($user_http_user,'DECODE'), $userdata);
    }else{
        if($user === false){
            return array();
        }else{
            return false;
        }
    }
    
    # 直接返回cookie中的信息.
    if($user === false && $userdata['logoip']){
        if($userdata['logoip'] !== fun_get_ip()){
            $userdata = array();
        }
        return $userdata;
    }
    
    # 假如直接命令要验证用户身份. 每次都查数库.
    $usererr = 1;
    if(empty($userdata) === false){
        $http_pass = $userdata['user_pass'];
        $http_name = $userdata['user_name'];
        $http_uid  = $userdata['user_id'];
        
        $data = array();
        if($http_uid){
        $data = mysql::get_one("SELECT `user_id`, `user_name`, `user_pass`, `user_email`, `user_logo`, `user_admin`, `user_regtime`, `user_posts`, `user_edits`, `user_deles`, `user_app`, `useropenid`, `user_exp` FROM DB_user WHERE user_id='$http_uid'");
        }

        # 加强型判断用户信息是否正确.
        if(empty($data['user_pass']) === true || $data['user_pass'] !== $http_pass || $data['user_name'] !== $http_name){
            $usererr = 0;
        }else{
           # 修复为用cookie记录用户登录信息.
           if($user === false){
               $data[0] = $data['user_id'];
               $data['logoip'] = fun_get_ip();
               fun_setcookie('http_user', fun_authcode(fun_http_build_query($data)), COOKIETIME);
           }else{
                #判断是否跟目前的权限一致.
                if(($data['user_id']+0) !== USER_UID){
                    $usererr = 0;
                }else if(($data['user_admin']+0) !== USER_ADMIN){
                    $usererr = 0;
                }else if($data['useropenid'] !== USER_QQ){
                    $usererr = 0;
                }
           }
        }
    }else{
        $usererr = 0;
    }
    
    if($user !== false){
        if($userdata['logoip'] !== fun_get_ip()){
            $usererr = 0;
        }
        
        if($usererr > 0){
           return true; 
        }else{
            return false;
        }
    }else{
        if($usererr === 0){
            fun_setcookie('http_user',null,-3600);
            $data = array();
        }
        return $data;
    }
}

function app_regtime($cfg_redate){
    if(!$cfg_redate)
        return array();
    
    $type = md5($cfg_redate);
    $time_arr = cache::read('setting_endtime_'.$type,'setting_cache.php',3686400);
    if(empty($time_arr) === true){
        $time_arr = array();
        $tem = explode('=',$cfg_redate);
        $tem[0] += 0;
        $tem[1] += 0;
        ($tem[0] >= 24 || $tem[0] <= 0) && $tem[0] = 0;
        ($tem[1] >= 24 || $tem[1] <= 0) && $tem[1] = 24;
        $tem[0] = str_pad($tem[0],2,'0',STR_PAD_LEFT);
        $tem[1] = str_pad($tem[1],2,'0',STR_PAD_LEFT);
        
         while(true){
             if(($tem[0]+0) == ($tem[1]+0))
                 break;
             $time_arr[] = str_pad($tem[0],2,'0',STR_PAD_LEFT);
             $tem[0] == 24?$tem[0] = 0:$tem[0]++;
         }
        if($time_arr)
            cache::write('setting_endtime_'.$type,'setting_cache.php',$time_arr);
    }
    return  $time_arr;
}

function app_thdele($dele){
    global $main_exp,$mainpost_exp;
    $dele +=0;
    if($dele <= 0)
        return false;

    $thread = mysql::get_one("SELECT thread_thum,thread_uid,thread_first FROM DB_thread WHERE thread_id='$dele'");
    
    if(empty($thread['thread_thum']) === false && is_file($thread['thread_thum'])=== true)
        unlink($thread['thread_thum']);
        
    # 删除附件
    $query = mysql::query("SELECT atime,amname FROM `DB_attachments` WHERE tid='$dele'");
	while(($row = mysql::fetch_array($query)) !== false){
		$path = './Data/attachments/' . fun_date('Ym', $row['atime']) . '/' . $row['amname'];
		if(is_file($path) === true){
		     unlink($path);
		}
	} 
    
    # 同步将对所属用户进行减积分操作
    $thread['thread_uid'] += 0;
    if($thread['thread_first'] === '0'){
        mysql::query("UPDATE DB_user SET user_exp = (user_exp - if(user_exp<$mainpost_exp,user_exp,$mainpost_exp)) WHERE user_id = '{$thread['thread_uid']}' LIMIT 1"); // $mainpost_exp减去积分
    }else{
        # 判断是否清空主题回复标签.
        $temtid = $thread['thread_first']+0;
        // thread_replay_count
        mysql::query("UPDATE DB_thread SET thread_replay_count = (thread_replay_count - if(thread_replay_count=0,0,1)) WHERE thread_id = '$temtid' LIMIT 1");
        mysql::query("UPDATE DB_user SET user_exp = (user_exp - if(user_exp<$main_exp,user_exp,$main_exp)) WHERE user_id = '{$thread['thread_uid']}' LIMIT 1"); // $main_exp减去积分
    }
    
    cache::dele('index_new_replay.php');
    cache::dele('default_list.php');
    mysql::query("DELETE FROM DB_thread WHERE thread_id='$dele' OR thread_first='$dele'");
    mysql::query("DELETE FROM DB_attachments WHERE tid='$dele'");
}