<?php
### USER: Yuan (fenanr@hotmail.com)
### DATE 2012/11/30 21:31:28
### TIMEZONE UTC +8 ZH-CN
### /source/ common.inc.php

defined('IN_SYSTEM') === false && exit('PHPnew Blog.');
function_exists('register_shutdown_function') === true && register_shutdown_function('common_function_end');
include(is_file('./Source/Inc/config.inc.php') === true?'./Source/Inc/config.inc.php':'./config.inc.php');
include('./Source/Inc/define.inc.php');
include('./Source/Function/function_global.php');
include('./Source/Function/function_lod.php');
include('./Source/Class/Cache_class.php');
include('./Source/Class/Json_class.php');
if(extension_loaded('mysqli')){
    include('./Source/Class/Mysqli_class.php');
}else{
    include('./Source/Class/Mysql_class.php');
}

if(DBUSER === 'dbuser' && is_file('./Data/install_lock') === false){
    exit('系统检测到你的程序还未安装,请点击链接进行安装 <a href="./install.php">Install</a>');
}
#============================测试段落========================================================


#============================================================================================

# session初始化, 为防止丢失, 如果有传递PHPSESSID过来, 就沿用.
if (empty($_REQUEST["PHPSESSID"]) === false) {
	session_id($_REQUEST["PHPSESSID"]);
}
session_start();

# gzip判断, ob_start无论如何都将调用.
if(stripos($_SERVER['SERVER_SOFTWARE'],'IIS') === false){
    IS_GZIP? ob_start('ob_gzhandler'):ob_start();
}else{
    ob_start();
}

# 设置几个数组
$_CFG = array();
$_DIR = array();
$_CACHE = array();
$_GLOBAL = array();

# 公共数据处理, 过滤成安全的数据. key未过滤.
$default_parem = common_function_parse_get();
$default_get = common_function_var($_GET);
$default_post = common_function_var($_POST);
$default_check = common_function_check();

# 移动平台判断.
if(empty($default_get['mobile']) === true && fun_ismobile()){
    fun_header(fun_parse_url('./index.php?mobile=index.html'));
}else if(empty($default_get['mobile']) === false && !fun_ismobile()){
    fun_header('./index.php');
}

# 禁止非本站post, 安全限制
if($_SERVER['REQUEST_METHOD'] === 'POST' || IS_POST){
    if($_SERVER['HTTP_REFERER'] && strpos($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']) === false){
        header("HTTP/1.0 404 Not Found");
        exit();
    }
}

# ====================================函数开始====================================================================
function common_function_check() {
    $cookie_data = fun_getcookie('runtime');
    $array = explode('||',$cookie_data);
    if(IS_FILES) {
        return false;
    }
    if(IS_POST) {
        $post_md5 = md5(serialize($_POST));
        if(empty($array[0]) === false && (GET_TIME - $array[0]) <= 10 && $post_md5 === $array[1]) {
            fun_header(fun_referer());
        } else {
            fun_setcookie('runtime',GET_TIME.'||'.$post_md5);
        }
    }
    // 禁止快速刷新,
    $md5 = md5(URL_SITE);
    $temp_cookie = explode('||',fun_getcookie('user_localhost'));
    $referer_time = trim($temp_cookie[1]);
    
    if($md5 !== $temp_cookie[0]){
        $referer_time = 0;
    }
    
    if(empty($referer_time) === false && GET_TIME - $referer_time < 0) {
        fun_setcookie('user_localhost',null,-5);
        fun_header(fun_referer());
    } else {
        fun_setcookie('user_localhost',$md5.'||'.(GET_TIME+0.8),1);
    }
    
    return 'POST:'.$post_time.'referer:'.$referer_time;
}

function common_function_var($array) {
    static $temp = 0;
    if($_POST === $array)
        $temp = 1;
    
    $bcount = 0;
    $arr_count = count($array);
    $return_array = array();
    foreach($array as $key => $val) {
        $bcount ++;
        if(IS_GPC === 0 && $temp !== 1)
            $key = addslashes($key);
        
        if($key && in_array($key, array('_GET','_POST','_SESSION','_COOKIE','GLOBALS')) === true){
            continue;
        }
        
        if(is_string($val) === true && $temp !== 1 && $bcount === $arr_count){
           $val = fun_trim($val,'.html',1);
        }
        
        if($val && is_array($val) === true) {
            $return_array[$key] = common_function_var($val);
        } else {
            if(IS_GPC === 0) {
                $return_array[$key] = addslashes(rtrim($val));
            } else {
                $return_array[$key] = rtrim($val);
            }
        }
    }
    return $return_array;
}

function common_function_template($file) {
    global $html,$common_tpl_arr;
    fun_isajax();
    /* 设置模板引擎相关配置 */
    include_once(DIR_CLASS.'PHPnew_class.php');
    $PHPnew = new PHPnew();
    
    if(!$file)
        exit($file.$PHPnew->templates_postfix.'Template file does not exist');
    
    // 解析路径
    if(strpos($file,'/') !== false && is_file($file) === true) {
        $path = rtrim(dirname($file),'/').'/';
        $PHPnew->templates_dir = $path;
        $info = pathinfo($file);
        $file =  basename($file,'.'.$info['extension']);
        unset($info,$common_tpl_arr);
    } else {
        # 对三个路径进行文件搜索.
        $common_tpl_arr[0] .= $file.$PHPnew->templates_postfix;
        $common_tpl_arr[1] .= $file.$PHPnew->templates_postfix;
        $common_tpl_arr[2] = './Static/Default/'.$file.$PHPnew->templates_postfix;
        
        $common_tpl_i = 0;
        foreach($common_tpl_arr AS $val){
            if(is_file($val) === true){
                $PHPnew->templates_dir = strtr($val,array($file.$PHPnew->templates_postfix=>''));
                $common_tpl_i = 1;
                break;
            }
        }
        unset($common_tpl_arr);
    }
    if($common_tpl_i === 0)
        exit($file.$PHPnew->templates_postfix.'Template file does not exist');
    
    $html['title'] = fun_cutstr($html['title'],50,'');
    define('EXCTIME',microtime(true) - GET_MICROTIME);
    $mysql_error = mysql::get_error();
    $out_str = sprintf('TIME:%01.4f/%s/',(microtime(true) - GET_MICROTIME),empty($mysql_error) === false?'MYSQLERROR':'MYSQL');
    $PHPnew->assign('out_str',$out_str);
    $PHPnew->display($file);
}

function common_function_dir($dir) {
    /* 返回 路径下所有信息 */
    $dir = (trim(strtr($dir,array('\\' => '/')),'/')).'/';
    $dir_fopen = opendir($dir);
    $list = array();
    while(($file = readdir($dir_fopen)) !== false) {
        $new_file = $dir.$file.'/';
        if($file === '..' || $file === '.')
            continue;
        if(is_dir($new_file) === true) {
            $list[$new_file] = common_function_dir($new_file);
        } else {
            $key = basename($dir.$file);
            $list[$key] = $dir.$file;
        }
    }
    return $list;
}

function common_function_parse_get() {
    # 解释这函数的产生, 函数是为了兼容伪静态与动态url而生的.
    # 解析两种url访问模式, a=b或者 a/b.html 
    # 细节未测试, url上的参数是否已经反解义了? 对特殊符号兼容性. 目前测试仅保障取值成功. 复杂点传值, 可用GET方式.
    static $i = 0;
    if($i !== 0)
        return array();
    /* 解析两种url访问模式, a=b或者 a/b.html */
    $site_get = strtr(URL_SITE,array(URL_HOST => ''));
     
    $temp_array = explode('/',$site_get);
    unset($site_get);
    $news_url = '';
    foreach($temp_array as $key => $val) {
        if(strpos($val, '%') !== false)
            $val = urldecode($val);
        
        if($key === 0) {
            if(empty($_GET) === false) {
                $news_url = $val.'.php?';
            } else {
                $news_url = fun_trim($val,'.php',1).'.php';
            }
        } else {
            if(isset($temp_array[$key + 1]) === false)
                $val = fun_trim($val,'.html',1);
            if($key % 2 === 0) {
                $news_url .= urlencode($val).'&';
            } else {
                $news_url .= $val.'=';
            }
        }
        if(isset($temp_array[$key + 1]) === false) {
            $news_url = trim($news_url,'&=');
            $val = fun_trim($val,'.html',1);
        }
        $temp_array[$key] = $val;
        $i += 1;
    }
    
    
    $temp_array['Static_url'] = URL_SITE;
    $temp_array['News_url'] = URL_HOST. ($i === 1?fun_trim($temp_array[0],'.html'):$news_url.'.html');
    empty($temp_array[0]) === true && $temp_array[0] = 'index';
    empty($temp_array[1]) === true && $temp_array[1] = 'main';
    empty($temp_array[2]) === true && $temp_array[2] = 'default';
    
    # 处理GET的值, 全部转在这儿处理.
    $_GET = array();
    foreach($temp_array AS $key => $val){
        if($key === 0 || $key % 2 === 0)
            continue;
        $_GET[$val] = $temp_array[$key+1];
    }
    return $temp_array;
}


function common_function_end() {
    static $a = 0;
    if($a !== 0){
        return false;
    }else{
       global $history_array,$default_parem;
       
       # 分门别类一下.
       $url = GET_URL;
       if(strpos($default_parem['News_url'],'index.php?main=') !== false){
           $url = strtr($url, array(URL_HOST=>'./'));
           $day = date('Ymd',time());
           if(!$GLOBALS['html']['title'])
                $GLOBALS['html']['title'] = 'index';
           $md5 = md5($GLOBALS['html']['title']);
                  
           if(empty($history_array[$md5]) === true && defined('SHOWMESS') === false && $url && $url !== './index.php'){
               $history_array[$md5]['l'] = htmlspecialchars($url);
               $history_array[$md5]['t'] =  mb_substr($GLOBALS['html']['title'], 0, 30, 'UTF-8');
               $history_array[$md5]['m'] =  time();
               if(empty($history_array[$md5]['t']) === false){
                 $history_array = fun_array_sort($history_array,array('m'=>SORT_DESC));
                 array_splice($history_array,10);
                 fun_setcookie('user_history',fun_authcode(serialize($history_array)),86400);
               }
           }
       }
    }
    $a++;
    $log = '';
    # 获取运行错误,仅记录重要的错误.
    $error_array = error_get_last();
    if(empty($error_array) === false && $error_array['type'] != 8){
        $url = htmlspecialchars($_SERVER['REQUEST_URI']);
        $path = DIR_ROOT;
        $date = date('Y-m-d H:i:s',time());
        # 组合错误信息
        $error_info = $error_array['message'].' line:'.$error_array['line'].' file:'.basename($error_array['file']);
        $log .= "PHP||$date||$error_info||{$url}\n";
    }

    # 取得数据库最后一条错误
    $mysql_error = mysql::get_error();
    if($mysql_error){
        $mysql_error = implode("\n",$mysql_error);
        $log .= 'SQL1||'.$mysql_error."\n";
    }
    
    if($log)
        fun_log($log);
}