<?php
/**
 * @version $Id: global.func.php v2.1 $
 * @package PBDigg
 * @copyright Copyright (C) 2007 - 2008 PBDigg.com. All Rights Reserved.
 * @license PBDigg is free software and use is subject to license terms
 */

if (!defined('IN_PBDIGG'))
{
	exit('Access Denied!');
}

/**
 * 添加转义字符
 */
function addS(&$array)
{
	if (is_array($array))
	{
		foreach ($array as $key => $value)
		{
			 addS($array[$key]);
		}
	}
	elseif (is_string($array))
	{
		$array = addslashes($array);
	}
}

/**
 * 格式化时间
 * 
 * @param String $time 时间
 * @param String $format 格式
 */
function gdate($time = '', $format = '')
{
	global $pb_timezone,$pb_timeformat,$pb_dateformat;
	if (!$time)
	{
		$time = time();
	}
	if ($pb_timezone == '111')
	{
		$offtime = 0;
	}
	else
	{
		$offtime = $pb_timezone;
	}
	if (!$format)
	{
		//24 OR 12 time format
		$hour = $pb_timeformat ? 'H:i:s' : 'h:i:s';
		$format = $pb_dateformat . ' ' . $hour;
	}
	return gmdate($format, ($time + $offtime * 3600));
}

/**
 * 加载语言包
 * 
 * @param String $type 语言文件名
 */
function loadLang($type)
{
	global $pb_lang;
	$langPath = PBDIGG_ROOT.'include/languages/'.$pb_lang.'/'.$type.'.lang.php';
	if (file_exists($langPath))
	{
		return $langPath;
	}
	$defaultPaht = PBDIGG_ROOT.'include/languages/zh-cn/'.$type.'.lang.php';
	if (file_exists($defaultPaht))
	{
		return $defaultPaht;
	}
	exit('Load Language File Failed!');
}
/**
 * 返回COOKIE信息
 */
function gCookie($var)
{
	return isset($_COOKIE[$var]) ? $_COOKIE[$var] : FALSE;
}

/**
 * 设置COOKIE信息
 * 
 * @param $name cookie名称
 * @param $value cookie值
 * @param $expire 过期时间：-1：删除，0：即时，1：永久
 * @return Boolean 设置cookie是否成功
 */
function sCookie($name, $value, $expire = 0)
{
	global $pb_ckpath, $pb_ckdomain, $timestamp;
	switch ($expire)
	{
		case 0:
			$expire = 0;
			break;
		case 1:
			$expire = $timestamp + 31536000;
			break;
		case -1:
			$expire = $timestamp - 31536000;
			break;
		default:
			$expire += $timestamp;
			break;
	}
	if ($pb_ckpath)
	{
		$path = $pb_ckpath;
	}
	else
	{
		$path = '/';
	}
	$secure = ($_SERVER['SERVER_PORT'] == '443') ? 1 : 0;
	return setcookie($name, $value, $expire, $path, $pb_ckdomain, $secure);
}

/**
 * 清除cookies
 */
function clearcookie()
{
	sCookie('pb_sid', '', -1);
	sCookie('pb_auth', '', -1);
	sCookie('pb_lastvisit', '', -1);
}

/**
 * 返回客户端IP和代理信息
 * 
 * @return Array(IP地址, 是否为代理访问)
 */
function getIP()
{
	if (isset ($_SERVER['HTTP_X_FORWARDED_FOR']))
	{
		$currentIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
		$isagent = TRUE;
	}
	elseif (isset ($_SERVER['HTTP_CLIENT_IP']))
	{
		$currentIP = $_SERVER['HTTP_CLIENT_IP'];
		$isagent = TRUE;
	}
	else
	{
		$currentIP = $_SERVER['REMOTE_ADDR'];
		$isagent = FALSE;
	}
	$currentIP = addslashes(htmlspecialchars($currentIP));
	preg_match('/[\d\.]{7,15}/', $currentIP, $match);
	$currentIP = $match[0] ? $match[0] : FALSE;
	return array($currentIP, $isagent);
}

/**
 * 带跳转信息提示
 */
function redirect($msg, $url, $time = 2)
{
	global $TPL;
	$TPL->assign('msg', $msg);
	$TPL->assign('url', $url);
	$TPL->assign('delay_time', $time);
	$TPL->display('redirect.html');
	exit;
}

/**
 * 提示信息
 */
function showMsg($msg, $url = 'javascript:history.go(-1)')
{
	global $TPL;
	$TPL->assign('msg', $msg);
	$TPL->assign('url', $url);
	echo $TPL->fetch('msg.html');
	@ob_end_flush();
	exit;
}

/**
 * 加解密处理函数
 *
 */
function PEncode($txt, $key)
{
	srand((double)microtime() * 1000000);
	$encrypt_key = md5(rand(0, 32000));
	$ctr = 0;
	$tmp = '';
	for($i = 0;$i < strlen($txt); $i++) 
	{
		$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
		$tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);
	}
	return base64_encode(PKey($tmp, $key));
}

function PDecode($txt, $key) 
{
	$txt = PKey(base64_decode($txt), $key);
	$tmp = '';
	for ($i = 0;$i < strlen($txt); $i++)
	{
		$md5 = $txt[$i];
		$tmp .= $txt[++$i] ^ $md5;
	}
	return $tmp;
}

function PKey($txt, $encrypt_key)
{
	$encrypt_key = md5($encrypt_key);
	$ctr = 0;
	$tmp = '';
	for($i = 0; $i < strlen($txt); $i++)
	{
		$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
		$tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
	}
	return $tmp;
}

/**
 * 脚本执行时间
 */
function spendTime()
{
	global $loadTime;
	$mtime = explode(' ', microtime());
	return number_format(($mtime[1] + $mtime[0] - $loadTime), 6);
}

/**
 * 写入文件
 * 
 * @param String $filename 文件名（包括路径）
 * @param String $content 写入内容
 * @param String $mode 写入模式，默认为‘ab’
 * 
 * @return Boolean 写入成功返回TRUE，失败返回FALSE
 * 
 */
function PWriteFile($filename, $content, $mode = 'ab')
{
	if (strpos($filename, '..') !== FALSE)
	{
		return FALSE;
	}
	$path = dirname($filename);
	if (!is_dir($path))
	{
		if (!mkdir($path, 0777))
		{
			return FALSE;
		}
	}
	$fp = @ fopen($filename, $mode);
	if ($fp)
	{
		flock($fp, LOCK_EX);
		fwrite($fp, $content);
		fclose($fp);
		@ chmod($filename, 0777);
		return TRUE;
	}
	return FALSE;
}

/**
 * 读取文件
 * 
 * @param String $filename 文件名
 * @param String $mode 文件读取模式
 */
function PReadFile($filename, $mode = 'rb')
{
	if (strpos($filename, '..') !== FALSE)
	{
		return FALSE;
	}
	if (PHP_VERSION >= '4.3.0')
	{
		return file_get_contents($filename);
	}
	if ($fp = @ fopen($filename, $mode))
	{
		flock($fp, LOCK_SH);
		$filedata = @ fread($fp, filesize($filename));
		fclose($fp);
	}
	return $filedata;
}

/**
 * 删除文件
 */
function PDel($var)
{
	if (strpos($var, '..') !== FALSE)
	{
		return FALSE;
	}
	return @unlink($var);
}

/**
 * 返回目录下特定文件
 * 
 * @param String $var 目录路径
 */
function PListFile($var, $type = array())
{
	if (is_dir($var))
	{
		$rs = @opendir($var);
		while (($file = readdir($rs)) !== FALSE)
		{
			if ($file != '..' && $file != '.')
			{
				if ($type && in_array(pathinfo($file, PATHINFO_EXTENSION), $type))
				$rt[] = $file;
			}
		}
		return $rt;
	}
	return FALSE;
}
/**
 * 创建无限级目录
 * 
 * @param String $var 目录路径
 * @param String $basedir 基本路径，结尾无'/'
 */
function Pmkdir($var, $basedir, $force = FALSE)
{
	global $func_message;
	if (strpos($var, '..') !== FALSE || strpos($basedir, '..') !== FALSE)
	{
		exit($func_message['illegal_filepath']);
	}
	if (!is_dir($basedir.$var))
	{
		$var = preg_replace('/\/{2,}/', '/', str_replace('\\', '/', $var));
		$basedir = preg_replace('/\/{2,}/', '/', str_replace('\\', '/', $basedir));
		$temp = explode('/',$var);
		$dirnum = count($temp);
		$cur_dir = $basedir.'/';
		for($i = 0; $i < $dirnum; $i++)
		{
			$cur_dir .= $temp[$i].'/';
			if (!is_dir($cur_dir))
			{
				if (!mkdir($cur_dir, 0777) && $force)
				{
					exit($func_message['attachment_mkdir_failed']);
				}
			} 
		}
	}
	return TRUE;
}
/**
 * 取得随机序列
 * 
 * @param int $length 随机数长度
 * @param boolean $isNum 是否为数字随机数
 * 
 * @return string
 */
function random($length, $isNum = FALSE)
{
	$random = '';
	$str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	$num = '0123456789';
	if ($isNum)
	{
		$sequece = 'num';
	}
	else
	{
		$sequece = 'str';
	}
	$max = strlen($$sequece) - 1;
	for ($i = 0; $i < $length; $i++)
	{
		$random .= ${$sequece}{mt_rand(0, $max)};
	}
	return $random;
}

/**
 * 取得散列值
 */
function getUserHash()
{
	global $_PBDEV, $timestamp;
	return substr(md5(random(8).$_PBDEV['PB_IP'].$_SERVER['HTTP_USER_AGENT'].$timestamp), 8, 8);
}

/**
 * 过滤HTML字符
 */
function HConvert($var)
{
	if (is_array($var))
	{
		foreach ($var as $key => $value)
		{
			$var[$key] = HConvert($value);
		}
	}
	else
	{
		$var = str_replace(array('"', '\'', '<', '>', "\t", "\r"), array('&quot;', '&#39;', '&lt;', '&gt;', '&nbsp;&nbsp;', ''), $var);
	}
	return $var;
}

/**
 * HTML危险代码过滤
 * 
 * @param String $string 过滤字符
 */
function safeConvert($string)
{
	$pattern = array('/(javascript|jscript|js|vbscript|vbs|about):/i','/on(mouse|exit|error|click|dblclick|key|load|unload|change|move|submit|reset|cut|copy|select|start|stop)/i','/<script([^>]*)>/i','/<iframe([^>]*)>/i','/<frame([^>]*)>/i','/<link([^>]*)>/i','/@import/i');
	$replace = array('','','&lt;script${1}&gt;','&lt;iframe${1}&gt;','&lt;frame${1}&gt;','&lt;link${1}&gt;','');
	$string = preg_replace($pattern, $replace, $string);
	$string = str_replace(array('</script>', '</iframe>', '&#'), array('&lt;/script&gt;', '&lt;/iframe&gt;', '&amp;#'), $string);
	return $string;
}

/**
 * 字符截取函数
 * 
 * @param String $text 内容
 * @param Integer $limit 截取长度
 * @param String $add 更多标记
 */
function PBSubstr($text, $limit, $add = '&#8230;')
{
	global $db_charset;
	$strlen = strlen($text);
	$db_charset = strtolower($db_charset);
	if($strlen <= $limit) return $text;
	$text = str_replace(array('&nbsp;', '&quot;', '&#039;', '&lt;', '&gt;'), array(' ', '"', "'", '<', '>'), $text);
	$rtext = '';
	if ($db_charset == 'utf-8')
	{
		$n = $tn = $noc = 0;
		while ($n < $strlen)
		{
			$t = ord($text{$n});
			if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126))
			{
				$tn = 1; $n++; $noc++;
			}
			elseif (194 <= $t && $t <= 223)
			{
				$tn = 2; $n += 2; $noc += 2;
			}
			elseif (224 <= $t && $t < 239)
			{
				$tn = 3; $n += 3; $noc += 2;
			}
			elseif (240 <= $t && $t <= 247)
			{
				$tn = 4; $n += 4; $noc += 2;
			}
			elseif (248 <= $t && $t <= 251)
			{
				$tn = 5; $n += 5; $noc += 2;
			}
			elseif ($t == 252 || $t == 253)
			{
				$tn = 6; $n += 6; $noc += 2;
			}
			else
			{
				$n++;
			}
			if($noc >= $limit) break;
		}
		if($noc > $limit) $n -= $tn;
		$rtext = substr($text, 0, $n);
	}
	else
	{
		$addlen = strlen($add);
		$limit -= $addlen - 1;
		for ($i = 0; $i < $limit; $i++)
		{
			$rtext .= ord($text[$i]) > 127 ? $text[$i] . $text[++$i] : $text[$i];
		}
	}
	$rtext = str_replace(array('"', "'", '<', '>'), array('&quot;', '&#039;', '&lt;', '&gt;'), $rtext);
	return $rtext.$add;
}

/**
 * Convert character encoding
 * 
 * @param String $from_encoding 原始编码
 * @param String $to_encoding 目标编码
 * @param String $str 编码字符串
 */
function convert_encoding($from_encoding, $to_encoding, $str)
{
	if(empty($str) || ($from_encoding == $to_encoding)) return $str;
//	$from_encoding = str_replace('gbk', 'gb2312', $from_encoding);
//	$to_encoding = str_replace('gbk', 'gb2312', $to_encoding);
	if(function_exists('mb_convert_encoding'))
	{
		return mb_convert_encoding($str, $to_encoding, $from_encoding);
	}
	elseif (function_exists('iconv'))
	{
		return iconv($from_encoding, $to_encoding.'//IGNORE', $str);
	}
	else
	{
		require_once(PBDIGG_ROOT.'include/Chinese.class.php');
		$CHS = new Chinese($from_encoding, $to_encoding);
		return $CHS->Convert($str);
	}
}
/**
 * IP访问控制
 */
function ipControl($ip)
{
	global $func_message, $pb_ipallow, $pb_ipdeny;
	$ipExist = FALSE;
	$pb_ipallow = unserialize($pb_ipallow);
	$pb_ipdeny = unserialize($pb_ipdeny);
	//allow
	if ($pb_ipallow)
	{
		$allowip = explode("\n", $pb_ipallow);
		foreach ($allowip as $value)
		{
			$pattern = "/^{$value}[\d\.]*?/i";
			if (preg_match($pattern, $ip))
			{
				$ipExist = TRUE;
				break;
			}
		}
		if (!$ipExist)
		{
			showMsg($func_message['ip_limit'], $func_message['js_close_window']);
		}
	}
	//deny
	if ($pb_ipdeny)
	{
		$ipdeny = explode("\n", $pb_ipdeny);
		foreach ($ipdeny as $value)
		{
			$pattern = "/^{$value}[\d\.]*?/i";
			if (preg_match($pattern, $ip))
			{
				showMsg($func_message['ip_limit'], $func_message['js_close_window']);
			}
		}
	}
}


/**
 * 上级父分类
 * 
 * @param Array $cate 分类数组
 * @param String $parCate 返回分类数组
 * @param Int $startID 分类开始ID，如从顶级分类开始则为0
 */

function parCate($cate, &$parCate, $startID = 1)
{
	static $i = 0;
	if (!$cate[$startID]['cup']) return;
	foreach ($cate as $key => $value)
	{
		if ($value['cid'] == $cate[$startID]['cup'])
		{
			$parCate[$i] = $value['cid'];
			$i++;
			parCate($cate, $parCate, $value['cid']);
		}
	}
}

/**
 * 下级子分类
 * 
 * @param Array $cate 分类数组
 * @param String $subCate 返回分类数组
 * @param Int $startID 分类开始ID，如从顶级分类开始则为0
 */

function subCate($cate, &$subCate, $startID = 0)
{
	static $i = 0;
	foreach ($cate as $key => $value)
	{
		if ($value['cup'] == $startID)
		{
			$subCate[$i] = $value['cid'];
			$i++;
			subCate($cate, $subCate, $value['cid']);
		}
	}
}

/**
 * 上级父分类字符串
 * 
 * @param Array $cate 分类数组
 * @param String $subCate 返回分类字符串
 * @param Int $startID 分类开始ID，如从顶级分类开始则为0
 */

function str_parcate($cate, &$str_parcate, $startID = 0)
{
	if (!$cate[$startID]['cup']) return;
	foreach ($cate as $key => $value)
	{
		if ($value['cup'] == $startID)
		{
			$str_parcate .= $value['cid'].',';
			str_parcate($cate, $str_parcate, $value['cid']);
		}
	}
}

/**
 * 下级子分类字符串
 * 
 * @param Array $cate 分类数组
 * @param String $subCate 返回分类字符串
 * @param Int $startID 分类开始ID，如从顶级分类开始则为0
 */

function str_subcate($cate, &$str_subcate, $startID = 0)
{
	foreach ($cate as $key => $value)
	{
		if ($value['cup'] == $startID)
		{
			$str_subcate .= $value['cid'].',';
			str_subcate($cate, $str_subcate, $value['cid']);
		}
	}
}

/**
 * 分类菜单
 * 
 * @param Array $cate 分类数组
 * @param String $option 分类菜单
 * @param Int $startID 分类开始ID，如从顶级分类开始则为0
 * @param Int $index 选择分类ID
 * @param Int $level 分类层次
 */

function cate_Option($cate, &$option, $startID = 0, $index = 0, $level = 0)
{
	foreach ($cate as $key => $value)
	{
		if ($value['cup'] == $startID)
		{
			$option .= '<option value="'.$value['cid'];
			if ($value['cid'] == $index)
			{
				$option .= '" selected="select';
			}
			$option .= '">'.str_repeat('&nbsp;', $level).'|-&nbsp;'.$value['name'].'</option>'."\r\n";
			$level++;
			cate_Option($cate, $option, $value['cid'], $index, $level--);
		}
	}
}

/**
 * URL重写
 * 
 * @param String $str
 */
function rewrite(&$str)
{
	if (!$str) return;
	$str = preg_replace("/<a href\=\"index.php(\?page=([0-9]{1,}))?\"([^\>]*)\>/e", "rewriteIndex('\\2', '\\3')", $str);
	$str = preg_replace("/<a href\=\"category.php\?cid=([0-9]{1,})(&amp;page=([0-9]{1,}))?\"([^\>]*)\>/e", "rewriteCate('\\1', '\\3', '\\4')", $str);
	$str = preg_replace("/<a href\=\"show.php\?tid=([0-9]{1,})(&amp;page=([0-9]{1,}))?\"([^\>]*)\>/e", "rewriteThread('\\1', '\\3', '\\4')", $str);
	$str = preg_replace("/<a href\=\"user.php\?uid=([0-9]{1,})(&amp;page=([0-9]{1,}))?\"([^\>]*)\>/e", "rewriteUser('\\1', '\\3', '\\4')", $str);
}
function rewriteIndex($page, $ext)
{
	global $_PBENV, $pb_rewriteext;
	return '<a href="'.$_PBENV['PB_URL'].'index.'.$pb_rewriteext.''.($page ? '&amp;page='.$page : '').'"'.($ext ? ' ' : '').stripslashes($ext).'>';
}
function rewriteCate($cid, $page, $ext)
{
	global $_PBENV;
	return '<a href="'.$_PBENV['PB_URL'].'category/'.$cid.($page ? '&amp;page='.$page : '').'"'.($ext ? ' ' : '').stripslashes($ext).'>';
}
function rewriteThread($tid, $page, $ext)
{
	global $pb_rewriteext, $_PBENV;
	return '<a href="'.$_PBENV['PB_URL'].'show/'.$tid.'.'.$pb_rewriteext.($page ? '&amp;page='.$page : '').'"'.($ext ? ' ' : '').stripslashes($ext).'>';
}
function rewriteUser($uid, $page, $ext)
{
	global $_PBENV;
	return '<a href="'.$_PBENV['PB_URL'].'user/'.$uid.($page ? '&amp;page='.$page : '').'"'.($ext ? ' ' : '').stripslashes($ext).'>';
}

/**
 * 将数组转换为可通过 url 传递的字符串连接
 *
 * @param array $args
 * @return string
 */
function gURL($args)
{
    $str = $amp = '';
    foreach ($args as $key => $value)
    {
        if (is_array($value))
        {
            $str .= $amp . gURL($value);
        }
        else
        {
            $str .= $amp . rawurlencode($key) . '=' . rawurlencode($value);
        }
        $amp = '&amp;';
    }
    return $str;
}

/**
 * 返回GET OR POST变量值
 */
function GP($value, $method = 'G')
{
	if($method == 'G' && isset($_GET[$value]))
	{
		return $_GET[$value];
	}
	return $_POST[$value];
}

/**
 * 菜单导航
 */
function PMenu()
{
	global $_PBENV, $categories, $cid, $pb_rewrite, $ui_message;
	$subcatestr = $multcatestr = '';
	$primaryMenu = '<li><a href="'.$_PBENV['PB_URL'].'"'.($cid ? '' : ' class="nav_current"').'>'.$ui_message['menu_all'].'</a></li>';
	if ($cid)
	{
		$parcid = array();
		global $singlecate;
		if ($singlecate['parcids'])
		{
			$parcid = array_reverse(explode(',',substr($singlecate['parcids'],0,-1)));
		}
		$parcid[] = $cid;
		unset($parcid[0]);
		$i = 1;
		foreach ($parcid as $key)
		{
			$multcatestr .= '<ul class="menu_'.$i++.'">';
			foreach ($categories as $k => $v)
			{
				if ($v['cup'] == $categories[$key]['cup'])
				{
					$multcatestr .= '<li><a href="category.php?cid='.$v['cid'].'"'.(($k == $key) ? ' class="nav_current"' : '').'>'.$v['name'].'</a></li>';
				}
			}
			$multcatestr .= '</ul>';
		}
		foreach ($categories as $k => $v)
		{
			if ($v['cup'] == $cid)
			{
				$subcatestr .= '<li><a href="category.php?cid='.$v['cid'].'">'.$v['name'].'</a></li>';
			}
		}
		if ($subcatestr) $multcatestr .= '<ul class="subnav">'.$subcatestr.'</ul>';
	}
	foreach ($categories as $key => $value)
	{
		if (!$value['cup'])
		{
			$primaryMenu .= '<li><a href="category.php?cid='.$value['cid'].'"'.(($cid == $key) ? ' class="nav_current"' : '').'>'.$value['name'].'</a></li>';
		}
	}
	return array($primaryMenu, $multcatestr);
}

/**
 * 加载调用缓存
 */
function loadTranCache()
{
	global $pb_opentran, $TPL, $Cache, $cid;
	$pb_opentran = explode("\t", $pb_opentran);
	$tranlist = '';
	if (!@include(PBDIGG_ROOT.'data/cache/cache_tranlist.php')) return;
	if ($pb_opentran[0])
	{
		$Cache->loadCache('tags', TRUE, 1);
		$TPL->assign('tran_tags', $Cache->getCacheContent());
		$Cache->loadCache('systags');
		$TPL->assign('tran_systags', $Cache->getCacheContent());
	}
	if ($pb_opentran[1])
	{
		foreach ($tranlist[0] as $v)
		{
			$tplvar = $v;
			if ($v{0} == 's')
			{
				$tmpcid = substr($v, strrpos($v, '_')+1);
				if ($cid != $tmpcid) continue;
				$tplvar = substr($v, 0, strrpos($v, '_'));
			}
			$Cache->_loadTran($v, 0);
			$TPL->assign($tplvar, $Cache->getCacheContent());
		}
	}
	if ($pb_opentran[2])
	{
		$tplvar = $v;
		foreach ($tranlist[1] as $v)
		{
			$tplvar = $v;
			if ($v{0} == 's')
			{
				$tmpcid = substr($v, strrpos($v, '_')+1);
				if ($cid != $tmpcid) continue;
				$tplvar = substr($v, 0, strrpos($v, '_'));
			}
			$Cache->_loadTran($v, 1);
			$TPL->assign($tplvar, $Cache->getCacheContent());
		}
	}
	if ($pb_opentran[3] && (PB_CSCRIPT == 'index'))
	{
		foreach ($tranlist[2] as $v)
		{
			$Cache->_loadTran($v, 2);
			$TPL->assign($v, $Cache->getCacheContent());
		}
	}
	$Cache->loadCache('sitestat');
	$TPL->assign('tran_sitestat', $Cache->getCacheContent());
}

/**
 * 首页格式化时间
 */
function formatPostTime($seconds)
{
	global $func_message, $pb_dformat, $timestamp;
	if ($pb_dformat)
	{
		$timestr = gdate($seconds, 'Y-m-d H:i');
	}
	else
	{
		$seconds = $timestamp - $seconds;
		$days = $hours = $timestr = '';
		$days = floor($seconds / 86400);
		if ($days > 0)
		{
			$seconds -= $days * 86400;
			$timestr .= $days.$func_message['formatted_post_day'].' ';
		}
		$hours = floor($seconds / 3600);
		if ($hours > 0)
		{
			$seconds -= $hours * 3600;
			$timestr .= $hours.$func_message['formatted_post_hour'].' ';
		}
		$timestr .= floor($seconds / 60).$func_message['formatted_post_minutebefore'];
	}
	return $timestr;
}

/**
 * 返回文件后缀名
 */
function Fext($filename)
{
	return trim(substr(strrchr($filename, '.'), 1));
}

/**
 * 导航链接
 * @param mix $cid 分类ID或当前页面名称
 * @param string $link 页面文件名
 */
function navlink($cid, $link = '')
{
	global $_PBENV, $ui_message;
	$navlink = '<a href="'.$_PBENV['PB_URL'].'"><span>'.$ui_message['menu_all'].'</span></a>';
	$sep = ' &raquo; ';
	if (is_numeric($cid))
	{
		global $categories;
		require(PBDIGG_ROOT.'data/cache/cache_singlecate_'.$cid.'.php');
		$pcid = explode(',', $singlecate['parcids'].$cid);
		foreach ($pcid as $value)
		{
			$navlink .= $sep.'<a href="category.php?cid='.$value.'"><span>'.$categories[$value]['name'].'</span></a>';
		}
	}
	elseif ($link)
	{
		$navlink .= $sep.'<a href="'.$link.'">'.$cid.'</a>';
	}
	return $navlink;
}

/**
 * 单项选择（radio）
 * 
 * @param $prefix 变量前缀，如ifopen_
 * @param $index 选择项索引，0为第一项
 * @param $number 单选控件数量
 * @return string
 */
function radio_checked($prefix, $index = 0, $number = 2)
{
	for ($i = 0; $i < $number; $i++)
	{
		global ${$prefix.$i};
		if ($i == $index)
		{
			${$prefix.$i} = 'checked="checked"';
		}
		else
		{
			${$prefix.$i} = '';
		}
	}
}

/**
 * 下拉列表框
 *
 * @param array $params
 * @param string $name
 * @param mixed $index
 * @param string $extra
 */
function phtml_select($params, $name, $index = '', $extra = '')
{
    $select = "<select name=\"{$name}\" {$extra}>\n";
    foreach ($params as $key => $value)
    {
        $select .= '<option value="'.htmlspecialchars($key).'"';
        if ($index == $key)
        {
        	$select .= ' selected="selected"'; 
        }
        $select .= '>'.htmlspecialchars($value)."</option>\n";
    }
   $select .= "</select>\n";
   return $select;
}

/**
 * 网站链接分类
 */
function PLink()
{
	$links = $link = $pic_link = $txt_link = array();
	@include_once(PBDIGG_ROOT.'data/cache/cache_links.php');
	if ($links)
	{
		foreach ($links as $lid => $ldetail)
		{
			if ($ldetail['logo'])
			{
				
				$pic_link[] = $ldetail;
			}
			else
			{
				$txt_link[] = $ldetail;
			}
		}
		$link[0] = $txt_link;
		$link[1] = $pic_link;
	}
	return $link;
}

function multLink($currentPage, $totalRecords, $url, $pageSize = 10)
{
	global $func_message;
	if ($totalRecords <= $pageSize) return '';
	$mult = '';
	$totalPages = ceil($totalRecords / $pageSize);
	$mult .= '<div class="pages"><div class="nextprev">';
	if ($currentPage > 1)
	{
		$mult .= '<a href="'.$url.'page='.($currentPage - 1).'">'.$func_message['prev'].'</a>';
	}
	else
	{
		$mult .= '<span class="nextprev">'.$func_message['prev'].'</span>';	
	}
	if ($totalPages < 13)
	{
		for ($counter = 1; $counter <= $totalPages; $counter++)
		{
			if ($counter == $currentPage)
			{
				$mult .= '<span class="current">'.$counter.'</span>';	
			}
			else
			{
				$mult .= '<a href="'.$url.'page='.$counter.'">'.$counter.'</a>';
			}
		}
	}
	elseif ($totalPages > 11)
	{
		if($currentPage < 7)		
		{
			for ($counter = 1; $counter < 10; $counter++)
			{
				if ($counter == $currentPage)
				{
					$mult .= '<span class="current">'.$counter.'</span>';
				}
				else
				{
					$mult .= '<a href="'.$url.'page='.$counter.'">'.$counter.'</a>';
				}	
			}
			$mult .= '<span>&#8230;</span><a href="'.$url.'page='.($totalPages-1).'">'.($totalPages-1).'</a><a href="'.$url.'page='.$totalPages.'">'.$totalPages.'</a>';	
		}
		elseif($totalPages - 6 > $currentPage && $currentPage > 6)
		{
			$mult .= '<a href="'.$url.'page=1">1</a><a href="'.$url.'page=2">2</a><span>&#8230;</span>';
			for ($counter = $currentPage - 3; $counter <= $currentPage + 3; $counter++)
			{
				if ($counter == $currentPage)
				{
					$mult .= '<span class="current">'.$counter.'</span>';	
				}
				else
				{
					$mult .= '<a href="'.$url.'page='.$counter.'">'.$counter.'</a>';
				}					
			}
			$mult .= '<span>&#8230;</span><a href="'.$url.'page='.($totalPages-1).'">'.($totalPages-1).'</a><a href="'.$url.'page='.$totalPages.'">'.$totalPages.'</a>';		
		}
		else
		{
			$mult .= '<a href="'.$url.'page=1">1</a><a href="'.$url.'page=2">2</a><span>&#8230;</span>';
			for ($counter = $totalPages - 8; $counter <= $totalPages; $counter++)
			{
				if ($counter == $currentPage)
				{
					$mult .= '<span class="current">'.$counter.'</span>';	
				}
				else
				{
					$mult .= '<a href="'.$url.'page='.$counter.'">'.$counter.'</a>';
				}
			}
		}
	}
	if ($currentPage < $counter - 1)
	{
		$mult .= '<a href="'.$url.'page='.($currentPage + 1).'" class="nextprev">'.$func_message['next'].'</a>';
	}
	else
	{
		$mult .= '<span class="nextprev">'.$func_message['next'].'</span>';
	}
	$mult .= '</div></div>';
	return $mult;
}

function is_Page($page)
{
	return !empty($page) && preg_match ('/^([0-9]+)$/', $page);
}

/**
* 缩略图
* 
* @param String $img 图片路径
* @param String $save_prefix 图片文件名前缀
*/
function thumb($img, $save_prefix = 'thumb_')
{
	global $pb_thumbsize;
	list($height, $width) = explode("\t", $pb_thumbsize);
	if (empty($img) || !file_exists($img)) return $img;
	$imginfo = @getimagesize($img);
	switch($imginfo[2])
	{
		case 1:
			$tmp_img = @imagecreatefromgif($img);
			break;
		case 2:
			$tmp_img = imagecreatefromjpeg($img);
			break;
		case 3:
			$tmp_img = imagecreatefrompng($img);
			break;
		default:
			$tmp_img = imagecreatefromstring($img);
			break;
	}
	if ($save_prefix)
	{
		$imgpath = substr($img, 0, strrpos($img, '/'));
		$filename = substr($img, strrpos($img, '/')+1);
		$savepath = $imgpath.'/'.$save_prefix.$filename;
	}
	else
	{
		$savepath = $img;
	}
	if(($height >= $imginfo[1] || !$height) && ($width >= $imginfo[0] || !$width))
	{
		if ($save_prefix)
		{
			@copy($img, $savepath);
		}
		return array($savepath, floor($imginfo[1]), floor($imginfo[0]));
	}
	$realscale = $imginfo[1] / $imginfo[0];
	if ($realscale <= 1)
	{
		$width = ($width > $imginfo[0] || !$width) ? $imginfo[0] : $width;
		$height = ($height > $imginfo[1] || !$height) ? $imginfo[1] : $width*$realscale;
	}
	else
	{
		$height = ($height > $imginfo[1] || !$height) ? $imginfo[1] : $height;
		$width = ($width > $imginfo[0] || !$width) ? $imginfo[0] : $height / $realscale;
	}
	$width = floor($width);
	$height = floor($height);
    $dst_image = imagecreatetruecolor($width, $height);
    imagecopyresampled($dst_image, $tmp_img, 0, 0, 0, 0, $width, $height, $imginfo[0], $imginfo[1]);
     switch($imginfo[2])
	{
        case '1':
        	imagegif($dst_image, $savepath);
        	break;
        case '2':
        	imagejpeg($dst_image, $savepath);
        	break;
        case '3':
        	imagepng($dst_image, $savepath);
        	break;
        default :
            imagejpeg($dst_image, $savepath);
            break;
    }
	return array($savepath, $height, $width);
}

/**
 * 编辑器
 */
function gEditor($text = '')
{
	global $pb_editor, $_PBENV, $TPL;
	if ($pb_editor == '1')
	{
		$TPL->assign('jsmore', '<script src="'.$_PBENV['PB_URL'].'include/editor/ubb/js/pbeditor.js" type="text/javascript"></script>');
		$TPL->assign('cssmore', '<link rel="stylesheet" type="text/css" id="css" href="'.$_PBENV['PB_URL'].'include/editor/ubb/images/pbeditor.css">');
//		$TPL->assign('ubbcontent', $text);
		$TPL->assign('editoronsubmit', ' onsubmit="return postForm()"');
//		$content = PReadFile(PBDIGG_ROOT.'include/editor/ubb/edit.html');
		require_once(PBDIGG_ROOT.'include/editor/ubb/edit.php');
	}
	elseif ($pb_editor == '2')
	{
		include_once (PBDIGG_ROOT.'include/editor/fck/fckeditor.php');
		$FCKeditor = new FCKeditor('content');
		$FCKeditor->BasePath = 'include/editor/fck/';
		$FCKeditor->Value = ubb_html($text);
		$FCKeditor->Height = '300';
		$FCKeditor->Width = '550';
		$FCKeditor->ToolbarSet = 'pb_post';
		$content = $FCKeditor->CreateHtml();
	}
	else
	{
		$content = '<div><textarea id="posteditor_textarea" name="content" cols="70" rows="10" class="text_editor" onselect="storeCaret(this);" onclick="storeCaret(this);" onkeyup="storeCaret(this);" >'.$text.'</textarea></div>';
		$TPL->assign('editoronsubmit', ' onsubmit="return postForm()"');
	}
	return $content;
}

/**
 * returns safe code for preloading in the RTE
 */
function rteSafe($strText)
{
	$tmpString = $strText;
	$tmpString = str_replace("'", "&#39;", $tmpString);
	$tmpString = str_replace(chr(10), ' ', $tmpString);
	$tmpString = str_replace(chr(13), ' ', $tmpString);
	return $tmpString;
}

/**
 * ubb代码转html
 */
function ubb_html($str)
{
	$search = array('[strike]', '[/strike]', '[br]','[u]', '[/u]', '[i]', '[/i]', '[b]', '[/b]', '[code]', '[/code]', '[pre]', '[/pre]', '[acronym]', '[/acronym]', '[address]', '[/address]', '[div]', '[/div]', '[p]', '[/p]', '[span]', '[/span]', '[ul]', '[ol]', '[li]', '[/ul]', '[/ol]', '[/li]', '[tr]', '[/tr]', '[td]', '[/td]', '[table]', '[/table]');
	$replace = array('<strike>', '</strike>', '<br />', '<u>', '</u>', '<i>', '</i>', '<b>', '</b>', '<code>', '</code>', '<pre>', '</pre>', '<acronym>', '</acronym>', '<address>', '</address>', '<div>', '</div>', '<p>', '</p>', '<span>', '</span>', '<ul>', '<ol>', '<li>', '</ul>', '</ol>', '</li>', '<tr>', '</tr>', '<td>', '</td>', '<table>', '</table>');
	$str = str_replace($search, $replace, $str);
	$reg_search = array("#\[align=([^\[\<]+?)\](.*?)\[/align]#is",
						"/\[table=(\d{1,4}(px|em|ex|pt|pc|in|mm|cm|%|)?)(,([\(\)%,#\w ]+)?)?\]/ies",
						"#\[td=(\d{1,2}),(\d{1,2})(,(\d{1,3}(px|em|ex|pt|pc|in|mm|cm|%|)?))?\]#is",
						"#\[font=([^\[\<]+?)\](.*?)\[/font\]#is",
						"#\[size=(\d+(\.\d+)?(px|em|ex|pt|pc|in|mm|cm|%|)?)\](.*?)\[/size\]#ies",
						"#\[color=([^\[\<]+?)\](.*?)\[/color\]#is");
	$reg_replace = array("<p style=\"text-align:\\1\">\\2</p>",
						"table_code('\\1','\\4')",
						"<td colspan=\"\\1\" rowspan=\"\\2\" width=\"\\4\">",
						"<span style=\"font-family:\\1\">\\2</span>",
						"font_size('\\1', '\\4', 'content')",
						"<span style=\"color:\\1\">\\2</span>");
	$str = preg_replace($reg_search, $reg_replace, $str);
	if ((strpos($str, '[url=') !== FALSE) && (strpos($str, '[/url]') !== FALSE))
	{
		$str = preg_replace("#\[url=(https?|ftp|gopher|news|telnet|rtsp|mms|callto|ed2k){1}:\/\/([^\[\"']+?)\](.+?)\[\/url\]#is", "<a href=\"\\1://\\2\" target=\"_blank\">\\3</a>", $str);
	}
	if ((strpos($str, '[email=') !== FALSE) && (strpos($str, '[/email]') !== FALSE))
	{
		$str = preg_replace("#\[email=([a-z0-9\-_.+]+)@([a-z0-9\-_]+[.][a-z0-9\-_.]+)\](.+?)\[\/email\]#is", "<a href=\"mailto:\\1@\\2\">\\3</a>", $str);
	}
	if ((strpos($str, '[img]') !== FALSE) && (strpos($str, '[/img]') !== FALSE))
	{
		$str = preg_replace("#\[img\]\s*([^\[\<\r\n]+?)\s*\[/img\]#is", "<img src=\"\\1\" />", $str);
	}
	return $str;
}

function table_code($width, $bgcolor)
{
	if (substr($width, -1) == '%')
	{
		$width = (substr($width, 0, -1) < 98) ? (int)$width.'%' : '98%';
	}
	else
	{
		$width = (int)$width;
		$width = ($width <= 560) ? $width : '98%';
	}
	return '<table'.($width ? ' width="'.$width.'" ' : ' ').'align="center" class="t_table"'.($bgcolor ? ' bgcolor="'.$bgcolor.'" ' : '').'>';
}

function font_size($size, $content, $type)
{
	global $pb_tubbsize;
	if (is_numeric($size))
	{
		if ($type == 'content' || $type == 'comment')
		{
			if ($size > $pb_tubbsize || $size < 1) $size = 3;
		}
		else
		{
			$size = 3;
		}
		return '<font size="'.$size.'">'.$content.'</font>';
	}
	else
	{
		return '<span style="font-size:'.$size.'">'.$content.'</span>';
	}
}

/**
 * 加载插件语言包
 */
function loadPluginLang($mark, $cp = FALSE)
{
	global $pb_lang;
	$filename = $mark;
	if ($cp) $filename .= '_cp';
	$langPath = PBDIGG_ROOT.'plugins/'.$mark.'/include/languages/'.$pb_lang.'/'.$filename.'.lang.php';
	if (file_exists($langPath))
	{
		return $langPath;
	}
	$defaultPaht = PBDIGG_ROOT.'plugins/'.$mark.'/include/languages/zh-cn/'.$filename.'.lang.php';
	if (file_exists($defaultPaht))
	{
		return $defaultPaht;
	}
	else
	{
		exit('Load Language Pack Failed!');
	}
}

/**
 * 返回附件目录
 */
function getUploadDir($cid = '')
{
	global $pb_attachdir, $timestamp, $func_message;
	$path = PBDIGG_ROOT.'attachments/';
	if ($pb_attachdir == '2' && $cid)
	{
		$dir = $cid;
	}
	elseif ($pb_attachdir == '0')
	{
		$dir = gdate($timestamp, 'ymd');
	}
	else
	{
		$dir = gdate($timestamp, 'ym');
	}
	if (!is_dir($path . $dir))
	{
		if (!mkdir($path . $dir, 0777)) showMsg($func_message['attachment_mkdir_failed']);
	}
	return $dir;
}

/**
 * 清除文件缓存
 */
function clearcache($tplmark, $cacheid, $show = FALSE)
{
	global $TPL, $pb_visitcache, $cache_dir, $dir;
	if ($pb_visitcache)
	{
		$TPL->caching = TRUE;
		if ($show)
		{
			$showdir = '';
			$cacheid = (string)$cacheid;
			$tidlen = strlen($cacheid);
			$ctid = 0;
			while ($ctid < $tidlen)
			{
				$showdir .= '/'.$cacheid{$ctid};
				$ctid++;
			}
			$TPL->cache_dir = $cache_dir.$dir.$showdir;
		}
		$TPL->clear_cache($tplmark.'.html', $cacheid);
	}
}

/**
 * 验证码校验
 */
function ckgdcode($postcode)
{
	$ckcode = gCookie('pb_ckcode');
	if (!$postcode || !$ckcode) return FALSE;
	list($t, $n) = explode("\t", $ckcode);
	return md5($t.strtolower($postcode)) == $n;
}

function getTagStyle()
{
    //自定义字体大小
    $sizearray = array('8','9','10','11','12','20');
    return 'font-size:'.$sizearray[rand(0,count($sizearray))].'pt;color:#'.dechex(rand(0,255)).dechex(rand(0,196)).dechex(rand(0,255));
}

/**
 * PBDIGG输出函数
 */
function PBOutPut($var, $cacheid = NULL, $compileid = NULL)
{
	global $TPL, $pb_exectime, $pb_rewrite, $DB, $pb_gzip;
	$output = $TPL->fetch($var, $cacheid, $compileid);
	ob_end_clean();
	if ($pb_rewrite)
	{
		rewrite($output);
	}
	if ($pb_exectime)
	{
		$output .= '<script type="text/javascript">document.getElementById("debug").innerHTML = "Processed in ' . spendTime() . ' second(s), ' . $DB->getQueries() . ' queries Gzip Enabled";</script>';
	}
	($pb_gzip && (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE) && function_exists('ob_gzhandler')) ? ob_start('ob_gzhandler') : ob_start();
	echo $output;
	exit;
}
?>
