<?php
/*$Id: common.func.php 565 2010-03-28 08:07:39Z genghonghao $*/

if (!defined('IN_GEN')) {
    die('Hacking attempt');
}

/**
 * 截取UTF-8编码下字符串的函数
 *
 * @param   string      $str        被截取的字符串
 * @param   int         $length     截取的长度
 * @param   bool        $append     是否附加省略号
 *
 * @return  string
 */
function sub_str($str, $length = 0, $append = true) {
    $str = trim($str);
    $strlength = strlen($str);

    if ($length == 0 || $length >= $strlength) {
        return $str;
    }
    elseif ($length < 0) {
        $length = $strlength + $length;
        if ($length < 0) {
            $length = $strlength;
        }
    }

    if (function_exists('mb_substr')) {
        $newstr = mb_substr($str, 0, $length, SMARTGOONE_CHARSET);
    }
    elseif (function_exists('iconv_substr')) {
        $newstr = iconv_substr($str, 0, $length, SMARTGOONE_CHARSET);
    }
    else {
        //$newstr = trim_right(substr($str, 0, $length));
        $newstr = substr($str, 0, $length);
    }

    if ($append && $str != $newstr) {
        $newstr .= '...';
    }

    return $newstr;
}

// 验证用户是否登录
function verify_user() {
    global $_SESSION;
    if (is_array($_SESSION) && isset($_SESSION['user']['islogin']) && $_SESSION['user']['islogin'] == TRUE) {
        return true;
    }
    return false;
}

// 取出系统配置数据
function load_config() {
    global $db, $cache;

    $cache->set('conf');
    if (false !== $cache->isvalid()) {
        return $cache->get_result();
    }

    $result = $db->result("SELECT conf_name, conf_value, is_disable FROM " . $db->get_table(TB_CONF));
    $config = array();
    $num    = count($result);

    for ($i = 0; $i < $num; $i++) {
        $config[$result[$i]['conf_name']] = $result[$i]['conf_value'];
    }

    $cache->make_cache($config);

    return $config;
}

// 传递模板必需的变量
function assign_template() {
    global $tpl, $_CONF;
    unset($_CONF['lang']);

    foreach ($_CONF AS $key => $val) {
        $tpl->assign($key, $val);
    }
    $tpl->assign('power', POWER_BY_SMARTGOON);
}

function assign_right_list() {

    global $tpl, $db;

    $statistics = $db->result("SELECT * FROM " . $db->get_table(TB_STATISTICS) . " WHERE sta_id='1'");

    // 文章数据
    $article_list = $db->result("SELECT * FROM " . $db->get_table(TB_ARTICLE) . " ORDER BY article_id DESC LIMIT 15");
    foreach($article_list AS $key=>$val) {
        $article_list[$key]['title'] = strip_tags($val['subject']);
        $article_list[$key]['subject'] = sub_str(strip_tags($val['subject']),  16);
    }
    $tpl->assign('right_list', $article_list);

    // 评论数据
    $comment_list = $db->result("SELECT * FROM " . $db->get_table(TB_REPLY) . " ORDER BY REPLY_id DESC LIMIT 15");
    foreach($comment_list AS $key=>$val) {
        $comment_list[$key]['title'] = strip_tags($val['content']);
        $comment_list[$key]['content'] = sub_str(strip_tags($val['content']),  10);
    }
    $tpl->assign('reply_list', $comment_list);

    // 友情链接数据
    $links = $db->result("SELECT * FROM " . $db->get_table(TB_LINKS). " ORDER BY link_order ASC");
    $txt_link = array();
    $img_link = array();
    foreach($links AS $val) {
        if (1 == $val['link_type']) {
            $val['link_text'] = sub_str(strip_tags($val['link_text']),  10);
            $txt_link[] =  $val;
        } else {
            $img_link[] = $val;
        }
    }
    $tpl->assign('txt_link', $txt_link);
    $tpl->assign('img_link', $img_link);

    $tpl->assign('category_list', $db->result("SELECT * FROM " . $db->get_table(TB_CATEGORY)));
    $tpl->assign('tags_list', $db->result("SELECT * FROM " . $db->get_table(TB_TAGS)));
    $tpl->assign('statistics', isset($statistics[0]) ? $statistics[0] : null);
    $tpl->assign('filing', get_filing_info());
}



function get_filing_info() {
    global $tpl, $db;

    $arr = array();

    $res = $db->result("SELECT submit_time FROM " . $db->get_table(TB_ARTICLE) . " LIMIT 1");
    $year = date("Y", $res[0]['submit_time']);
    $month = date("n", $res[0]['submit_time']);
    $cur_year = date("Y");
    $cur_month = date("n");

    $diff = ($cur_year-$year);

    if ($diff == 0) {
        $arr[] = $year . '-' . $month;

        $m_diff = $cur_month - $month;


        for ($i = $month; $i < $cur_month; $i++) {
            $arr[] = $year . '-' . (string)($i+1);
        }
    }
    else {
        for($i = 0; $i < $diff+1; $i++) {
            if ($i == 0) {
                $k = $month-1;
            }
            else {
                $k = 0;
            }
            if ( $i == $diff ) {
                $end = $cur_month;
            }
            else {
                $end = 12;
            }
            for($k; $k < $end; $k++) {
                $arr[] = (string)($year+$i). '-' . (string)($k+1);
            }
        }
    }
    rsort($arr);
    foreach($arr AS $key=>$item) {
        $start_time = strtotime($item . "-01 00:00:00");
        $month_day = date('t', $start_time);
        $end_time = strtotime($item . "-" . $month_day . " 23:59:59");
        $query = $db->query("SELECT COUNT(*) AS num FROM " . $db->get_table(TB_ARTICLE) . " WHERE submit_time>'$start_time' AND submit_time<'$end_time'");
        $row = $db->fetch_row($query);
        $arr[$key] .= "（{$row[0]}）";
    }
    return $arr;
}

// 页面跳转
function redirect_page($state_text, $msg, $url, $interval=5) {
    global $base_url;
    $reload = $base_url . '/reload.php' . '?url=' . urlencode($url) . '&interval=' . $interval . '&msg=' . urlencode($msg) . '&state_text=' . urlencode($state_text);
    header("Location: $reload");
    exit;
}

function get_name($type, $id) {
	global $db;
	switch ($type)
	{
		case 'tags':
			$table = TB_TAGS;
			$tid = 'tag_id';
			$tname = 'tag_name';
		break;
		case 'category':
			$table = TB_CATEGORY;
			$tid = 'category_id';
			$tname = 'category_name';
		break;
	}
	$res = $db->result("SELECT {$tname} FROM " . $table . " WHERE " . $tid . "='" . $id . "'");
	return isset($res[0][$tname]) ? $res[0][$tname] : 'NULL';
}
?>
