<?php
/**
 * @version $Id: admin.func.php v2.0 $
 * @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!');
}

/**
 * 后台登陆验证
 * 
 * @return Boolean 验证通过则返回用户信息
 */
function checkLogin($username, $password)
{
	global $DB, $db_prefix, $_SUPERMANAGER, $siteFounder;
	if (empty ($username) || empty ($password))
	{
		return FALSE;
	}
	$customer = $DB->db_fetch_one_array("SELECT m.uid, m.username, m.password, m.adminid, m.groupid, a.allowadmincp FROM {$db_prefix}members m LEFT JOIN {$db_prefix}admingroups a USING (adminid) WHERE m.username = '$username' AND m.password = '$password'");
	if (($customer == FALSE) || ($customer['allowadmincp'] != '1'))
	{
		return FALSE;
	}
	if (($customer['username'] == $siteFounder['username']) && ($customer['password'] == $siteFounder['password']))
	{
		$_SUPERMANAGER = 1;
	}
	return $customer;
}

/**
 * 后台操作权限判断
 * 
 * @param string $item 操作项目
 * @return boolean
 */
function allowdo($item)
{
	global $DB, $db_prefix, $customer, $func_message;
	$adminid = intval($customer['adminid']);
	$purview = $DB->db_fetch_one_array("SELECT allowadmincp cp, $item item FROM {$db_prefix}admingroups WHERE adminid = $adminid");
	if ($purview && $purview['cp'] && $purview['item'])
	{
		return TRUE;
	}
	elseif (!$purview['cp'])
	{
		redirect($func_message['action_nopermission'], 'admincp.php?action=logout');
	}
	else
	{
		redirect($func_message['action_nopermission'], 'admincp.php?action=main');
	}
}

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

/**
 * 返回客户端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 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!');
}

/**
 * 加载插件语言包
 */
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 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 adminlog($description = '', $result = 0, $islog = 0)
{
	global $DB, $db_prefix, $timestamp, $_PBDEV, $customer;
	$uid = isset($customer['uid']) ? $customer['uid'] : 0;
	$DB->db_query("INSERT INTO {$db_prefix}adminlogs (uid, action, description, logdate, logip, result, islog) VALUES(".$uid.", '".addslashes($_PBDEV['REQUEST_URL'])."', '".addslashes($description)."', '$timestamp', '".$_PBDEV['PB_IP']."', $result, $islog)");
}

/**
 * 返回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);
}

/**
 * 格式化时间
 * 
 * @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));
}

/**
 * 首页格式化时间
 */
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 rewrite_Tran(&$str, $type = 'show')
{
	global $pb_rewrite, $pb_rewriteext;
	if (!$str) return '';
	switch ($type)
	{
		case 'show':
			$pattern = '/show.php\?tid=([0-9]{1,})/i';
			$replacement = 'show/$1.'.$pb_rewriteext;
		break;
		case 'user':
			$pattern = '/user.php\?uid=([0-9]{1,})/i';
			$replacement = 'user/$1.'.$pb_rewriteext;
		break;
	}
	$str = preg_replace($pattern, $replacement, $str);
}

/**
 * 脚本执行时间
 */
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 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;
	return substr(md5(random(8).$_PBDEV['PB_IP'].$_SERVER['HTTP_USER_AGENT']), 8, 8);
}

/**
 * 管理员散列值
 */
function getAdminHash($customer)
{
	global $timestamp, $_PBDEV;
	return md5($timestamp.$customer.$_PBDEV['PB_IP'].$_SERVER['HTTP_USER_AGENT']);
}

/**
 * 后台登陆
 */
function login()
{
	global $TPL,$pb_gdcheck,$pb_adminsafecode;
	$TPL->assign('siteconfig', array('pb_gdcheck'=>$pb_gdcheck,'pb_adminsafecode'=>$pb_adminsafecode));
	$TPL->assign('jumpurl', $_SERVER['QUERY_STRING']);
	$TPL->display('login.html');
	exit;
}

/**
 * 后台菜单项目
 * 
 * @return array(当前url, 导航菜单条)
 */
function activeMenu()
{
	global $_PBDEV, $action, $type, $cp_message;
	$actionurl = $_PBDEV['PHP_SELF'];
	$navlink = '';
	$ds = '<strong>&nbsp;&raquo;&nbsp;</strong>';
	if ($action)
	{
		$actionurl .= '?action='.$action;
		if ($type)
		{
			$actionurl .= '&type='.$type;
			$navlink .= $ds.'<a href="admincp.php?action='.$action.'">'.$cp_message[$action].'</a>';
			$navlink .= $ds.$cp_message[$type.'_'.$action];
		}
		else
		{
			$navlink .= $ds.$cp_message[$action];
		}
	}
	return array($actionurl, $navlink);
}

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

/**
 * 提示信息
 */
function showMsg($msg, $url = '')
{
	global $TPL, $_PBDEV;
	$TPL->assign('msg', $msg);
	$url = $url ? $url : $_PBDEV['PB_REFERER'];
	$TPL->assign('url', $url);
	echo $TPL->fetch('msg.html');
	ob_end_flush();
	exit;
}

/**
 * 过滤空白字符
 */
function stripWhite($string)
{
	return str_replace(array("\t", "\n", "\r", " "), array('', '', '', '&nbsp;'), $string);
}

/**
 * 网站风格
 */
function siteStyle($style)
{
	$option = "<select name=\"config[pb_style]\" id=\"style\">\n";
	if (!preg_match('/^[_0-9a-zA-Z]+?$/i', $style))
	{
		$style = 'default';
	}
	$path = PBDIGG_ROOT.'data/style';
	if ($resource = @ opendir($path))
	{
		while (($file = readdir($resource)) !== false)
		{
			if (preg_match('/\.php$/i', $file))
			{
				$stylefile = str_replace('.php', '', $file);
				if ($style == $stylefile)
				{
					$option .= "<option value=\"{$stylefile}\" selected=\"selected\">{$stylefile}</option>\r\n";
				} else {
					$option .= "<option value=\"{$stylefile}\">{$stylefile}</option>\r\n";
				}
			}
		}
	}
	else
	{
		return FALSE;
	}
	$option .= "</select>\n";
	return $option;
}

/**
 * 网站语言
 */
function siteLang($lang)
{
	$option = "<select name=\"config[pb_lang]\" id=\"lang\">\n";
	if (!preg_match('/^[_0-9a-zA-Z-]+?$/i', $lang))
	{
		$lang = 'zh-cn';
	}
	$path = PBDIGG_ROOT.'include/languages/';
	if ($resource = @ opendir($path))
	{
		while (($file = readdir($resource)) !== false)
		{
			if ($file != '.' && $file != '..' && is_dir($path.$file))
			{
				if ($file == $lang)
				{
					$option .= "<option value=\"{$file}\" selected=\"selected\">{$file}</option>\r\n";
				} else {
					$option .= "<option value=\"{$file}\">{$file}</option>\r\n";
				}
			}
		}
	}
	else
	{
		return FALSE;
	}
	$option .= "</select>\n";
	return $option;
}

/**
 * 单项选择（radio）
 * 
 * @param $prefix 变量前缀，如ifopen_
 * @param $index 选择项索引，0为第一项
 * @param $number 单选控件数量
 * @return string
 */
function radioChecked($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 html_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;
}

/**
 * 多项选择（checkbox）
 *
 * @param array $params
 * @param string $name
 * @param array $index
 */
function html_checkbox($params, $name, $index = array(), $newline = 0, $extra = '')
{
	$checkbox = '';
	$i = 1;
	foreach ($params as $key => $value)
	{
		$checkbox .= '<input type="checkbox" name="'.$name.'" value ="'.$key.'"';
		if (in_array($key, $index))
		{
			$checkbox .= ' checked="checked"';
		}
		$checkbox .= $extra.' />'.htmlspecialchars($value).'&nbsp;';
		if ($newline && ($i % $newline == 0))
		{
			$checkbox .= '<br />';
		}
		$i ++;
	}
	return $checkbox;
	
}

/**
 * 交换数值
 */
function exchange(&$var1, &$var2)
{
	if ($var1 > $var2)
	{
		$tmp = $var1;
		$var1 = $var2;
		$var2 = $tmp;
	}
}

/**
 * convert shorthand notation into bytes
 */
function ini_bytes($val)
{
    $val = trim(ini_get($val));
    $last = strtolower($val{strlen($val)-1});
    switch($last)
    {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }
    return $val;
}

/**
 * 转换为正整型
 * 
 * @param mixed $var
 */
function positiveInteger(&$var)
{
	if (is_array($var))
	{
		foreach ($var as $key => $value)
		{
			 positiveInteger($var[$key]);
		}
	}
	elseif ($var < 0)
	{
		$var = 0;
	}
	else
	{
		$var = (int)$var;
	}
}

/**
 * Convert special HTML entities back to characters
 */
function Hentities($var)
{
	$var = str_replace('&quot;', '"', $var);
	$var = str_replace('&#039;', "'", $var);
	$var = str_replace('&lt;', '<', $var);
	$var = str_replace('&gt;', '>', $var);
	return $var;
} 

/**
 * 上级父分类
 * 
 * @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['cid'] == $cate[$startID]['cup'])
		{
			$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 cateOption($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++;
			cateOption($cate, $option, $value['cid'], $index, $level--);
		}
	}
}

/**
 * 分类管理表格
 * 
 * @param Array $cate 分类数组
 * @param String $table 分类管理表格
 * @param Int $startID 分类开始ID，如从顶级分类开始则为0
 * @param Int $index 选择分类ID
 * @param Int $level 分类层次
 * @param Array $cycle 表格属性，2级数组设置TR和TD属性，array(array(item1, item2,...), array(item1, item2,...))
 */
function cateTable($cate, &$table, $startID = 0, $level = 0, $cycle = array())
{
	global $cp_message;
	static $i = 0; 
	$trfiled = $tdfiled = 1;
	$lang[0] = '<span style="color:#f00">'.$cp_message['status_close'].'</font>';
	$lang[1] = $cp_message['status_open'];
	$status[0] = $cp_message['status_open'];
	$status[1] = $cp_message['status_close'];
	if ($cycle[0])
	{
		$trfiled = count($cycle[0]);
	}
	if ($cycle[1])
	{
		$tdfiled = count($cycle[1]);
	}
	foreach ($cate as $key => $value)
	{
		if ($value['cup'] == $startID)
		{
			$table .= '<tr'.$cycle[0][$i % $trfiled].'>'."\r\n";
			$table .= '<td align="center"'.$cycle[1][$i % $tdfiled].'>'.$value['cid'].'</td>'."\r\n";
			$table .= '<td style="text-indent:'.$level.'em"'.$cycle[1][$i % $tdfiled].'>|-&nbsp;'.$value['name'].'</td>'."\r\n";
			$table .= '<td align="center"'.$cycle[1][$i % $tdfiled].'>'.$lang[$value['status']].'</td>'."\r\n";
			$table .= '<td align="center"'.$cycle[1][$i % $tdfiled].'><input class="forminput" type="text" name="cate['.$value['cid'].']" value="'.$value['displayorder'].'" size="5" /></td>'."\r\n";
			$table .= '<td align="center"'.$cycle[1][$i % $tdfiled].'><span class="altconfirm" onclick="checkAction(\'admincp.php?action=cate&type=status&status='.$value['status'].'&cid='.$value['cid'].'\', \''.$status[$value['status']].'\')"><img src="../templates/admin/images/status_'.$value['status'].'.gif" alt="'.$status[$value['status']].'" /></span>&nbsp;&nbsp;<span class="altconfirm" onclick="checkAction(\'admincp.php?action=cate&type=del&cid='.$value['cid'].'\', \'\')"><img src="../templates/admin/images/del.gif" alt="'.$cp_message['del'].'" /></span>&nbsp;&nbsp;<span class="altconfirm" onclick="location.href=\'admincp.php?action=cate&type=mod&cid='.$value['cid'].'\'"><img src="../templates/admin/images/edit.gif" alt="'.$cp_message['edit'].'" /></span></td>'."\r\n";
			$table .= '</tr>'."\r\n";
			$level++;
			$i++;
			cateTable($cate, $table, $value['cid'], $level--, $cycle);
		}
	}
}

/**
 * 后台IP权限判断
 * 符合允许访问列表的ip返回true，否则返回false
 */
function accessIPControl($IP)
{
	global $pb_adminipallow;
	$ipallow = unserialize($pb_adminipallow);
	if (!$ipallow)
	{
		return TRUE;
	}
	$ipallow = explode("\n", $ipallow);
	foreach ($ipallow as $value)
	{
		$pattern = "/^{$value}[\d\.]*?$/i";
		if (preg_match($pattern, $IP))
		{
			return TRUE;
		}
	}
	return FALSE;
}

/**
 * 格式化时间
 * 
 * @param Int $seconds 秒
 */
function timespanFormat($seconds)
{
	global $a_message;

	$days = floor($seconds / 86400);
	if ($days > 0)
	{
		$seconds -= $days * 86400;
	}
	$hours = floor($seconds / 3600);
	if ($days > 0 || $hours > 0)
	{
		$seconds -= $hours * 3600;
	}
	$minutes = floor($seconds / 60);
	if ($days > 0 || $hours > 0 || $minutes > 0)
	{
		$seconds -= $minutes * 60;
	}
	return sprintf($a_message['timespanfmt'], (string) $days, (string) $hours, (string) $minutes, (string) $seconds);
}

/**
 * 返回格式化文件尺寸
 * 
 * @param Int $size 文件尺寸单位（B）
 */
function getRealSize($size)
{
	if ($size < 1024)
	{
		return $size.' Byte';
	}
	if ($size < 1048576)
	{
		return round($size / 1024, 2).' KB';
	}
	if ($size < 1073741824)
	{
		return round($size / 1048576, 2).' MB';
	}
	if ($size < 1099511627776)
	{
		return round($size / 1073741824, 2).' GB';
	}
}

function checkWritable($var)
{
	$writeable = FALSE;
	if(!is_dir($var))
	{
		@mkdir($var, 0777);
	}
	if (is_dir($var))
	{
		$var .= '/temp.txt';
		if ($fp = @fopen($var, 'w'))
		{
			fclose($fp);
			@unlink($var);
			$writeable = TRUE;
		}
	}
	return $writeable;	
}

/**
 * 检查目录属性
 * 
 * @param String $perm 目录名称
 */
function checkPerm($perm)
{
	$rperm = array();
	if ($perm && is_array($perm))
	{
		foreach ($perm as $value)
		{
			if (strpos($value, 'dbak'))
			{
				$path = PBDIGG_CP.'dbak';
			}
			else
			{
				$path = PBDIGG_ROOT.$value;
			}
			if (checkwritable($path))
			{
				$rperm[$value] = '<span class="b">Pass</span>';
			}
			else
			{
				$rperm[$value] = '<span class="r">Failed</span>';
			}
		}
		return $rperm;
	}
	else
	{
		return FALSE;
	}
}

/**
 * 前台分页函数
 */
function multLink($currentPage, $totalRecords, $url, $pageSize = 10)
{
	global $func_message;
	if ($totalRecords <= $pageSize)
	{
		return '';
	}
	else
	{
		$totalPages = ceil($totalRecords / $pageSize);
	}
	if ($currentPage > $totalPages)
	{
		$currentPage = $totalPages;
	}
	elseif ($currentPage < 1)
	{
		$currentPage = 1;
	}		
	$mult = '';
	if ($currentPage == 1)
	{
		$mult .= '<span class="nextprev">'.$func_message['prev'].'</span><span class="current">1</span>';
		for ($i = 2; $i <= $totalPages; $i++)
		{
			$mult .= '<a href="'.$url.'page='.$i.'">'.$i.'</a>';
			if ($i >= 10 && $totalPages > 10)
			{
				$prev = $totalPages - 1;
				$mult .= '<span>&#8230;</span>';
				if ($totalPages > 12)
				{
					$mult .= '<a href="'.$url.'page='.$prev.'">'.$prev.'</a>';
				}
				$mult .= '<a href="'.$url.'page='.$totalPages.'">'.$totalPages.'</a>';
				break;
			}
		}
	}
	else
	{
		$mult .= '<a href="'.$url.'page='.($currentPage - 1).'" class="nextprev">'.$func_message['prev'].'</a>';
		if ($currentPage <= 8)
		{
			for ($i = 1; $i < $currentPage; $i++)
			{
				$mult .= '<a href="'.$url.'page='.$i.'">'.$i.'</a>';
			}
		}
		else
		{
			$mult .= '<a href="'.$url.'page=1">1</a><a href="'.$url.'page=2">2</a><span>&#8230;</span>';
			for ($i = $currentPage -5; $i < $currentPage; $i++)
			{
				$mult .= '<a href="'.$url.'page='.$i.'">'.$i.'</a>';
			}
		}
		$mult .= '<span class="current">'.$currentPage.'</span>';
	}
	if ($currentPage == $totalPages)
	{
		$mult .= '<span class="nextprev">'.$func_message['next'].'</span>';
	}
	else
	{
		if ($currentPage != 1)
		{
			if ($currentPage <= 8)
			{
				for ($i = $currentPage + 1; $i <= $totalPages; $i++)
				{
					$mult .= '<a href="'.$url.'page='.$i.'">'.$i.'</a>';
					if ($i == 10) break;
				}
				$next = $totalPages - 10;
				if ($next > 0)
				{
					$mult .= '<span>&#8230;</span>';
					if ($next > 1)
					{
						$mult .= '<a href="'.$url.'page='.($totalPages - 1).'">'.($totalPages - 1).'</a>';
					}
					$mult .= '<a href="'.$url.'page='.$totalPages.'">'.$totalPages.'</a>';	
				}
			}
			elseif (($totalPages - $currentPage) > 6)
			{
				$endlink = $currentPage + 5;
				for ($i = $currentPage + 1; $i < $endlink; $i++)
				{
					$mult .= '<a href="'.$url.'page='.$i.'">'.$i.'</a>';
				}
				$mult .= '<span>&#8230;</span>';
				$mult .= '<a href="'.$url.'page='.($totalPages - 1).'">'.($totalPages - 1).'</a>';
				$mult .= '<a href="'.$url.'page='.$totalPages.'">'.$totalPages.'</a>';
			}
			else
			{
				for ($i = $currentPage + 1; $i <= $totalPages; $i++)
				{
					$mult .= '<a href="'.$url.'page='.$i.'">'.$i.'</a>';
				}
			}
		}
		$mult .= '<a href="'.$url.'page='.($currentPage + 1).'" class="nextprev">'.$func_message['next'].'</a>';
	}
	return $mult;
}

/**
 * 后台分页函数
 */
function cpmultLink($currentPage, $totalRecords, $url, $pageSize = 10)
{
	if($totalRecords <= $pageSize) return '';
	$pagenum = ceil($totalRecords / $pageSize);
	if($currentPage < 1)
	{
		$currentPage = 1;
	}
	elseif ($currentPage > $pagenum)
	{	
		$currentPage = $pagenum;	
	}
	$pages = '<div class="pages"><a href="'.$url.'page=1" style="font-weight:bold">&laquo;</a>';
	$flag = 0;
	for ($i = $currentPage - 3; $i <= $currentPage - 1; $i++)
	{
		if($i < 1) continue;
		$pages .= '<a href="'.$url.'page='.$i.'">'.$i.'</a>';
	}
	$pages .= "<strong> $currentPage </strong>";
	if($currentPage < $pagenum)
	{
		for ($i =  $currentPage + 1; $i <= $pagenum; $i++)
		{
			$pages .= '<a href="'.$url.'page='.$i.'">'.$i.'</a>';
			$flag ++;
			if ($flag == 4) break;
		}
	}
	return $pages;
}

/**
 * 过滤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(!$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);
	}
}

/**
 * 清空目录
 */
function Deldir($dir)
{
	$newdir = '';
	if (is_dir($dir))
	{
		if ($dh = opendir($dir))
		{
	        while (($file = readdir($dh)) !== FALSE)
	        {
	            if ($file != '..' && $file != '.')
	            {
	            	$newdir = $dir.'/'.$file;
	            	if (is_dir($newdir))
	            	{
	            		Deldir($newdir, FALSE);
	            	}
	            	else
	            	{
	            		@unlink($dir.'/'.$file);
	            	}
	            }
	        }
	        closedir($dh);
    	}
    	@rmdir($dir);
	}
}

/**
 * 备份数据库表
 * 
 * @param String $table 表名
 * @param Int $startfrom 开始记录行数
 * @param Int $currsize 当前备份文件大小
 */

function sqldumptable($table, $startfrom = 0, $currsize = 0)
{
	global $DB, $sizelimit, $startrow, $db_charset;
	$offset = 300;
	$tabledump = '';
	if (!$startfrom) 
	{
		$tabledump = "DROP TABLE IF EXISTS $table;\n";
		$createtable = $DB->db_query("SHOW CREATE TABLE $table");
		$create = $DB->db_fetch_row($createtable);
		$tabledump .= $create[1];
		$tabledump .= ";\n\n";
	}
	$tabledumped = 0;
	$numrows = $offset;
	while (($currsize + strlen($tabledump) < $sizelimit) && ($numrows == $offset))
	{
		$tabledumped = 1;
		$rows = $DB->db_query("SELECT * FROM $table LIMIT $startfrom, $offset");
		$numfields = $DB->db_fieldNum($rows);
		$numrows = $DB->db_num($rows);
		while ($row = $DB->db_fetch_row($rows))
		{
			$comma = '';
			$tabledump .= "INSERT INTO $table VALUES (";
			for ($i = 0; $i < $numfields; $i++)
			{
				$tabledump .= $comma.'\''.mysql_escape_string($row[$i]).'\'';
				$comma = ',';
			}
			$tabledump .= ");\n";
		}
		$startfrom += $offset;
	}
	$startrow = $startfrom;
	$tabledump .= "\n";
	return $tabledump;
}

function splitsql($sql)
{
	$sql = str_replace("\r", "\n", $sql);
	$ret = array();
	$num = 0;
	$queriesarray = explode(";\n", trim($sql));
	unset($sql);
	foreach($queriesarray as $query)
	{
		$queries = explode("\n", trim($query));
		$sq = '';
		foreach($queries as $query)
		{
			$sq .= $query{0}=='#' ? NULL : $query;
		}
		$ret[$num] = $sq;
		$num++;
	}
	unset($sq, $num);
	return($ret);
}

/**
 * 添加自动绑定记录
 */
function addselftpl($cid)
{
	global $DB, $db_prefix, $Cache;
	$tpllist = $selflist = array();
	$DB->db_query("SELECT * FROM {$db_prefix}templates WHERE ifself = 1");
	while ($rs = $DB->db_fetch_array())
	{
		$selfmark = substr($rs['tplmark'], 0, strrpos($rs['tplmark'], '_'));
		if (!in_array($selfmark, $selflist))
		{
			$selflist[] = $selfmark;
		}
		else
		{
			continue;
		}
		$rs['tplmarkpre'] = $selfmark;
		$tpllist[] = $rs;
	}
	foreach ($tpllist as $v)
	{
		$DB->db_query("INSERT INTO {$db_prefix}templates (tplid, tplname, tplmark, trancid, trannum, tranattribute, cotentlimit, titlelimit, iftopicimg, timelimit, timeformat, trantype, displayorder, ifself, tplcontent) VALUES (NULL, '".$v['tplname']."', '".$v['tplmarkpre'].'_'.$cid."', '$cid', ".$v['trannum'].", '".$v['tranattribute']."', ".$v['cotentlimit'].", ".$v['titlelimit'].", ".$v['iftopicimg'].", ".$v['timelimit'].", '".$v['timeformat']."', '".$v['trantype']."', ".$v['displayorder'].", 1, '".$v['tplcontent']."')");
	}
	$Cache->mktrantpl();
	$Cache->mktran();
}

/**
 * 删除自动绑定记录
 */
function delselftpl($cid)
{
	global $DB, $db_prefix, $Cache;
	$DB->db_query("DELETE FROM {$db_prefix}templates WHERE ifself = 1 AND trancid = $cid");
	$Cache->mktrantpl();
	$Cache->mktran();
}

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

/**
 * 输出函数
 */
function PBOutPut($var, $cacheid = NULL, $compileid = NULL)
{
	global $TPL, $pb_exectime;
	$output = $TPL->fetch($var, $cacheid, $compileid);
	echo $output;
	exit;
}
?>
