<?php
/*
Dvbbs.php  - Version: 2.0.0
Web: http://www.dvbbs.net
Copyright: 2000-2006 Dvbbs.Net
script file:blackol_functions.php
Script Written by Lao Mi
Function of the Page:include file functions of blakol
*/
if(!defined('PRODUCT') || PRODUCT !='Dvbbs.php' || !defined('ISDVBBS') || !defined('VERSION')) exit('Access denied.Sorry, you can not access this file directly.');
//get_forum_info 获取论坛基本信息
function get_forum_info(){
	global $forum_type,$db,$_xsltProcessor,$xml,$root,$param_get,$forum_setting,$forum_info,$forum_user,$forum_chansetting,$forum_pack,$forum_topicnum,$forum_postnum,$forum_usernum,$dv,$forum_maxpostnum,$forum_maxpostdate,$forum_maxonline,$forum_maxonlinedate,$forum_adminfolder,$forum_nowusebbs;
	$query=$db->query('select forum_setting,forum_chansetting,forum_pack,forum_topicnum,forum_postnum,forum_usernum,forum_maxpostnum,forum_maxpostdate,forum_maxonline,forum_maxonlinedate,forum_adminfolder,forum_nowusebbs from '.$dv.'setup limit 1');
	$result = $db->fetch_row($query);
	$Forum_Setting=explode('|||',$result[0]);
	$forum_info=explode(',',$Forum_Setting[0]);
	$forum_type=$forum_info[0];
	$forum_setting=explode(',',$Forum_Setting[1]);
	$forum_user=explode(',',$Forum_Setting[2]);
	$forum_chansetting=explode(',',$result[1]);
	$forum_pack=explode('|||',$result[2]);
	$forum_topicnum=$result[3];
	$forum_postnum=$result[4];
	$forum_usernum=$result[5];
	$forum_maxpostnum=$result[6];
	//$forum_maxpostdate=gmdate('Y-m-d H:i:s', $result[7] + getUserTimeZoneOffset());
	$forum_maxpostdate=$result[7];
	$forum_maxonline=$result[8];
	//$forum_maxonlinedate=gmdate('Y-m-d H:i:s', $result[9] + getUserTimeZoneOffset());
	$forum_maxonlinedate=$result[9];
	$forum_adminfolder=$result[10];
	$forum_nowusebbs=$result[11];
	unset($Forum_Setting);
}
//输出页面头部分
function head($pagetitle=''){
	global $forum_type,$charset,$bodystyle,$lang;
	if ($pagetitle=='') $pagetitle=$lang['page_title'];
	require_once printout('head');
}
//输出页面结束部分
function footer($action=1){
	global $db,$time_start,$db_obstart;
	$version=VERSION;
	$product=PRODUCT;
	if ($action==1){
		if($db){
			$qn=$db->querynum;
		}
		$t_array	= explode(' ',microtime());
		$totaltime	= number_format(($t_array[0]+$t_array[1]-$time_start),6);
		$is_gzip=($db_obstart==1 ? "Gzip enabled" : "Gzip disabled");
		$forum_speed	= "<br />Processed in $totaltime(s), $qn queries  , $is_gzip";
	}
	save_log();
	require_once printout('footer');
	$db->close();
	$output = str_replace(array('<!--<!---->','<!---->'),array('',''),ob_get_contents());
	ob_end_clean();
	$db_obstart == 1 ? ob_start('ob_gzhandler') : ob_start();
	echo $output;
	flush;
	exit;
}
//返回模板路径
function printout($template,$ext="tpl.php"){
	global $tplpath;
	$path=TEMPLATE_PATH."$template.$ext";
	return $path;
}
//load_lang 获取语言包数组
function load_lang($current_lang, $area, $langpath='')
{
	if (empty($langpath)) {
		$langfile = LANG_PATH.$area.'.lang.php';
	} else {
		$langfile = $langpath.$area.'.lang.php';
	}
	if (!is_file($langfile)) {
		return front_load_lang($current_lang, $area, $langpath);
	}
	require $langfile;
	if (!empty($language) AND is_array($language)) {
		foreach ($language as $k => $v) {
			if( is_array($v) && !empty($v) ){
				$current_lang[$k] = $v;
			} else{
				$current_lang[$k] = $v;
			}
		}
		unset($language);
	}
	return $current_lang;
}
//load_lang 获取前台语言包数组
function front_load_lang($current_lang, $area, $langpath='')
{
	if (empty($langpath)) {
		$langfile = FRONT_LANG_PATH.$area.'.lang.php';
	} else {
		$langfile = $langpath.$area.'.lang.php';
	}
	require $langfile;
	if (!empty($language) AND is_array($language)) {
		foreach ($language as $k => $v) {
			if( is_array($v) && !empty($v) ){
				$current_lang[$k] = $v;
			} else{
				$current_lang[$k] = stripslashes($v);
			}
		}
		unset($language);
	}
	return $current_lang;
}

//get_datetime 返回指定格式的时间
function get_datetime($string_format='Y-m-d h:m:s'){
	global $timestamp,$forum_setting;
	return gmdate($string_format,$timestamp+getUserTimeZoneOffset());
}
// get_yn_str返回√或×
function get_yn_str($value=0){
	global $lang;
	if ($value==0){
		return '<font style="color:red">'.$lang['g_no'].'</font>';
	}else{
		return '<font style="color:green">'.$lang['g_yes'].'</font>';
	}
}
//checklogin 判断是否已登录
function checklogin(){
	global $islogin;
	if ( $islogin == 0 ){
		header("Location:login.php");
		exit;
	}
}
//show_msg 返回成功或失败信息.
//参数说明：title 标题,messanger信息内容，suc 0 失败，1 成功
//link显示链接地址，text 链接文字,url 按钮点击进入的地址，button按钮文字
function show_msg($title,$messanger,$suc=0,$link='',$text='',$url='',$button=''){
	global $lang;
	if ($button==''){
		$button=$lang['comback'];
	}
	if ($suc==0){
		$suc_tyle=$lang['fail'];
	}else{
		$suc_tyle=$lang['suc'];
	}
	if ($link!='' && $text!=''){
		$link='<a href="'.$link.'" target="_blank">'.$text.'</a>';
	}
	require_once printout('show_msg');
}
//readme 输出操作说明
//参数说明：title操作项目名称，redametext操作说明内容
//menutext 快速导航菜单
function readme($title='',$redametext='',$menutext=''){
	global $lang;
	require printout('readme');
}
/*new_form_item 新增一个表单项目
参数说明
$items表单项目数组
$type 表单类型
$name 表单名称和ID
$value表单的值
$simpleType 数据类型名称
$item_tit 表单项目名称
$description 表单说明
$style 表单样式
$top_falg 是否显示top链接
$h_link  帮助链接
$group_title 分组标题文字
$attribute_str附加的自定属性数据
*/
function new_form_item($items,$type='text',$name='',$value='',$simpleType='',$item_tit='',$description='',$style='',$top_falg='',$h_link='',$group_title='',$attribute_str=''){
	$items[]=array(
	'type'=>$type
	,'name'=>$name
	,'value'=>$value
	,'simpleType'=>$simpleType
	,'item_tit'=>$item_tit
	,'description'=>$description
	,'style'=>$style
	,'top_falg'=>$top_falg
	,'h_link'=>$h_link
	,'group_title'=>$group_title
	,'attribute_str'=>$attribute_str
	);
	return $items;
}
/*
new_restriction 新增数据约束
参数说明
$restriction 数据类型数组
$key 类型名称
$base 数据类型
---数据类型为字符串----
| $maxLength 最大长度 |
| $minLength 最小长度 |
---数据类型为数值------
| $minExclusive 最小值|
| $maxExclusive 最大值|
$pattern 采用正则表达式约束数据
$enumeration 值的列表约束数组
*/
function new_restriction($restriction,$key,$base='string',$minLength=0,$maxLength=0,$minExclusive=0,$maxExclusive=0,$pattern='',$enumeration=null){
	$restriction[$key]=array(
	'base'=>$base
	,'minLength'=>$minLength
	,'maxLength'=>$maxLength
	,'minExclusive'=>$minExclusive
	,'maxExclusive'=>$maxExclusive
	,'pattern'=>$pattern
	,'enumeration'=>$enumeration
	);
	return $restriction;
}
/*
new_enumeration新增一项目约束值
$enumeration约束数组
$value 值
$text 显示文字
*/
function new_enumeration($enumeration,$value,$text){
	$enumeration[]=array('value'=>$value,'text'=>$text);
	return $enumeration;
}
/*show_form
显示表单
$form表单数据
*/
function show_form($form){
	global $lang,$restriction;
	require_once printout('show_form');
}
function check_date($item,$value){
	global $lang,$restriction;
	$base=$restriction[$item['simpleType']]['base'];
	if(is_array($value)){
		foreach($value as $val) {
			$res=$res.check_date($item,$val);
		}
		return $res;
	}else{
		switch ($base){
			case 'string':
				if($restriction[$item['simpleType']]['pattern']!=''){
					if (!preg_match ($restriction[$item['simpleType']]['pattern'],$value)) {
						return '<li>'.$item['item_tit'].$lang['data_err_1'].' '.$value.' '.$lang['data_err_10'].'"'.$restriction[$item['simpleType']]['pattern'].'"</li>';
					}
				}
				$enumeration = $restriction[$item['simpleType']]['enumeration'];
				if (is_array($enumeration)){
					foreach($enumeration as $val) {
						if ($val['value']==floatval($value)){
							$res=1;
							break;
						}
						if ($values==''){
							$values=' '.$val['value'];
						}else{
							$values=$values.$lang['data_err_9'].$val['value'];
						}
					}
					if($res!=1)
					{
						return '<li>'.$item['item_tit'].$lang['data_err_1'].' '.$value.' '.$lang['data_err_8'].$values.'</li>';
					}
				}else{
					$maxLength = $restriction[$item['simpleType']]['maxLength'];
					$minLength = $restriction[$item['simpleType']]['minLength'];
					if(strlen($value)< $minLength){
						return '<li>'.$item['item_tit'].$lang['data_err_5'].$minLength.'</li>';
					}elseif(strlen($value) > $maxLength){
						return '<li>'.$item['item_tit'].$lang['data_err_6'].$maxLength.'</li>';
					}
				}
				break;
			case 'numeric':
				if (is_numeric($value)){
					if($restriction[$item['simpleType']]['pattern']!=''){
						if (!preg_match ($restriction[$item['simpleType']]['pattern'],$value)) {
							return '<li>'.$item['item_tit'].$lang['data_err_1'].' '.$value.' '.$lang['data_err_10'].'"'.$restriction[$item['simpleType']]['pattern'].'"</li>';
						}
					}
					$enumeration = $restriction[$item['simpleType']]['enumeration'];
					if (is_array($enumeration)){
						foreach($enumeration as $val) {
							if ($val['value']==floatval($value)){
								$res=1;
								break;
							}
							if ($values==''){
								$values=' '.$val['value'];
							}else{
								$values=$values.$lang['data_err_9'].$val['value'];
							}
						}
						if($res!=1)
						{
							return '<li>'.$item['item_tit'].$lang['data_err_1'].' '.$value.' '.$lang['data_err_8'].$values.'</li>';
						}
					}else{
						$maxExclusive = $restriction[$item['simpleType']]['maxExclusive'];
						$minExclusive = $restriction[$item['simpleType']]['minExclusive'];
						if(floatval($value)< $minExclusive){
							return '<li>'.$item['item_tit'].$lang['data_err_1'].' '.$value.' '.$lang['data_err_3'].$minExclusive.'</li>';
						}elseif(floatval($value) > $maxExclusive){
							return '<li>'.$item['item_tit'].$lang['data_err_1'].' '.$value.' '.$lang['data_err_4'].$maxExclusive.'</li>';
						}
					}
				}else{
					return '<li>'.$item['item_tit'].$lang['data_err_1'].'"'.$value.'"'.$lang['data_err_2'].'</li>';
				}
				break;
			default:
				return '<li>'.$lang['base_err'].$restriction[$simpleType]['base'].'</li>';
		}
	}
}
//校验所有表单数据，并返回表单项数组$post
function ckeck_post($backurl=''){
	global $post,$form,$lang;
	foreach($form['items']  as $item){
		$post[$item['name']]=stripslashes($_POST[$item['name']]);
		$res.=check_date($item,$post[$item['name']]);
	}
	if ($res!=''){
		head();
		show_msg($lang['page_title'],'<ul>'.$res.'</ul>',0,'','',$backurl);
		footer();
		exit;
	}
}
function split_replace($string){
	$string=str_replace('&lt;&gt;','&amp;lt;&amp;gt;',$string);
	return  str_replace('<>','&lt;&gt;',$string);
}
function unsplit_replace($string){
	$string=str_replace('&lt;&gt;','<>',$string);
	return  str_replace('&amp;lt;&amp;gt;','&lt;&gt;',$string);
}
function replacehtml($string){
	return preg_replace( '/<(.[^>]*)>/i' ,'' ,$string);
}
function forumusertrueip(){
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$UserTrueIP = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$UserTrueIP = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$UserTrueIP = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$UserTrueIP = $_SERVER['REMOTE_ADDR'];
	}
	return addslashes(str_filter_xss($UserTrueIP = preg_replace("/^([\d\.]+).*/", "\\1", $UserTrueIP)));
}
function boardjumplist($inboardid = 0,$defaultTitle=''){
	global $_DCACHE, $lang;
	('' === $defaultTitle) AND ($defaultTitle = $lang['blackol_functions.str1']);
	$jumplist = '<option value="0">'.$defaultTitle.'</option>';
	if( empty($_DCACHE['all_forums']) ){
		include_once CACHE_PATH.'board/board_all.php';
	}
	if( !empty($_DCACHE['all_forums']) && is_array($_DCACHE['all_forums']) ){
		foreach( $_DCACHE['all_forums'] as $currBoardid => $currForum ){
			$currBoardType = "<option ";
			if( $currBoardid == $inboardid ){
				$currBoardType .= ' selected ';
			}
			$currBoardType .= " value='{$currForum[boardid]}'>";
			if( $currForum['depth'] == 0 ){
				$currBoardType .= $lang['blackol_functions.str2'];
			} elseif($currForum['depth'] == 1){
				$currBoardType .= "&nbsp;&nbsp;".$lang['blackol_functions.str3'];
			}
			if( $currForum['depth'] > 1 ){
				for ($i = 2; $i <= $currForum['depth'] ; $i++){
					$currBoardType .= "&nbsp;&nbsp;".$lang['blackol_functions.str4'];
				}
				$currBoardType .= "&nbsp;&nbsp;".$lang['blackol_functions.str3'];
			}
			$currBoardType .= "{$currForum[boardtype]}</option>";
			$jumplist .= $currBoardType;
		}
	}
	return $jumplist;
}


function savvyboardjumplist($inboardid=0,$defaultTitle=''){//论坛知道版面ID
	global $_DCACHE, $lang;
	$inboardarr=explode(',',$inboardid);
	('' === $defaultTitle) AND ($defaultTitle = $lang['blackol_functions.str1']);
	$jumplist = '<option value="0">'.$defaultTitle.'</option>';
	if( empty($_DCACHE['all_forums']) ){
		include_once CACHE_PATH.'board/board_all.php';
	}
	if( !empty($_DCACHE['all_forums']) && is_array($_DCACHE['all_forums']) ){
		foreach( $_DCACHE['all_forums'] as $currBoardid => $currForum ){
			$currBoardType = "<option ";
			if(in_array($currBoardid,$inboardarr)){
				$currBoardType .= ' selected ';
			}
			$currBoardType .= " value='{$currForum[boardid]}'>";
			if( $currForum['depth'] == 0 ){
				$currBoardType .= $lang['blackol_functions.str2'];
			} elseif($currForum['depth'] == 1){
				$currBoardType .= "&nbsp;&nbsp;".$lang['blackol_functions.str3'];
			}
			if( $currForum['depth'] > 1 ){
				for ($i = 2; $i <= $currForum['depth'] ; $i++){
					$currBoardType .= "&nbsp;&nbsp;".$lang['blackol_functions.str4'];
				}
				$currBoardType .= "&nbsp;&nbsp;".$lang['blackol_functions.str3'];
			}
			$currBoardType .= "{$currForum[boardtype]}</option>";
			$jumplist .= $currBoardType;
		}
	}
	return $jumplist;
}
//信息数/每页数/当前页/URL/当前页信息数/最大页
function pagelist($num, $perpage, $curpage, $mpurl, $topicnum, $maxpages = 0) {
	global $lang;
	$multipage = '';
	$mpurl .= strpos($mpurl, '?') !== false ? '&' : '?';
	if($num > $perpage) {
		$page = 10;
		$offset = 2;

		$realpages = @ceil($num / $perpage);
		$pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;

		if($page > $pages) {
			$from = 1;
			$to = $pages;
		} else {
			$from = $curpage - $offset;
			$to = $curpage + $page - $offset - 1;
			if($from < 1) {
				$to = $curpage + 1 - $from;
				$from = 1;
				if(($to - $from) < $page && ($to - $from) < $pages) {
					$to = $page;
				}
			} elseif($to > $pages) {
				$from = $curpage - $pages + $to;
				$to = $pages;
				if(($to - $from) < $page && ($to - $from) < $pages) {
					$from = $pages - $page + 1;
				}
			}
		}

		$multipage = ($curpage - $offset > 1 && $pages > $page ? '<td class="tablebody1">&nbsp;<a href="'.$mpurl.'page=1"><img src="'.ROOT_PATH.'images/pagelist/first.gif" border="0"></a>&nbsp;</td>' : '').
		($curpage > 1 ? '<td class="tablebody1">&nbsp;<a href="'.$mpurl.'page='.($curpage - 1).'"><img src="'.ROOT_PATH.'images/pagelist/previous.gif" border="0" alt="'.$lang['blackol_msg.str1'].'"></a>&nbsp;</td>' : '');
		for($i = $from; $i <= $to; $i++) {
			$multipage .= $i == $curpage ? '<td class="tablebody2">&nbsp;<font class="normalTextSmall"><u><b>'.$i.'</b></u></font>&nbsp;</td>' :
			'<td class="tablebody1">&nbsp;<a href="'.$mpurl.'page='.$i.'">'.$i.'</a>&nbsp;</td>';
		}

		$multipage .= ($curpage < $pages ? '<td class="tablebody1">&nbsp;<a href="'.$mpurl.'page='.($curpage + 1).'"><img src="'.ROOT_PATH.'images/pagelist/next.gif" border="0" alt="'.$lang['blackol_msg.str2'].'"></a>&nbsp;</td>' : '').
		($to < $pages ? '<td class="tablebody1">&nbsp;<a href="'.$mpurl.'page='.$pages.'"><img src="'.ROOT_PATH.'images/pagelist/last.gif" border="0" alt="'.$lang['blackol_msg.str3'].'"></a>&nbsp;</td>' : '').
		($curpage == $maxpages ? '<td class="tablebody1">&nbsp;<a href="misc.php?action=maxpages&pages='.$maxpages.'">&gt;<b>?</b></a>&nbsp;</td>' : '').
		($pages > $page ? '<td class="tablebody1"><input type="text" name="page" size="1" value="1" class="PageInput"><input type="submit" value="GO" name="submit" class="PageInput"></td>' : '');

		$multipage = $multipage ? '<table class="tableborder5" cellpadding="0" cellspacing="1">'.
		'<tr align="center"><td class="tabletitle1" title="'.$lang['blackol_msg.str4'].'">&nbsp;'.$num.'&nbsp;</td><td class="tabletitle1" title="'.$lang['blackol_msg.str5'].'">&nbsp;'.$topicnum.'&nbsp;</td><td class="tabletitle1">&nbsp;'.$curpage.'/'.$realpages.'&nbsp;</td>'.$multipage.'</tr></table>'.
		'</td></tr><tr><td height="3"></td></tr></table>' : '';
	}
	return $multipage;
}
function more_substr($str , $start , $len = -1) {
	preg_match_all("#[\x80-\xff]?.#i" , $str , $arr);
	if($len == -1) $len = sizeof($arr[0]) - $start;
	return @implode(array_slice($arr[0] , $start , $len) , "");
}
function save_log() {
	global $lang,$dv,$db,$action,$sysusername,$userip,$nowdate,$ScriptName;
	$userip=forumusertrueip();
	$action_str=$_GET['action'];
	$nowdate=time();
	include_once INC_PATH.'DV_Encoding.class.php';
	if($action_str != ""){
		$action_str="action=".$action_str;
		$action_str=check_str($action_str);
		$enc =& DV_Encoding::GetEncoding($GLOBALS['charset']);
		$action_str=$enc->SubString($action_str,0,250);
		$sql=$db->query("insert into {$dv}log (l_touser,l_username,l_content,l_ip,l_type,l_addtime) values ('".$ScriptName."','".$sysusername."','".$action_str."','".$userip."',0,'".$nowdate."')");
	}
	if(!empty($_POST)){
		$action_str=check_str($_POST);
		$enc =& DV_Encoding::GetEncoding($GLOBALS['charset']);
		$action_str=$enc->SubString($action_str,0,250);
		$sql=$db->query("insert into {$dv}log (l_touser,l_username,l_content,l_ip,l_type,l_addtime) values ('".$ScriptName."','".$sysusername."','".$action_str."','".$userip."',1,'".$nowdate."')");
	}
}
function check_str($str) {
	if(is_null($str)){
		$checkstr='';
	}
	else{
		$str=str_replace(chr(0),"",$str);
		$checkstr=str_replace("'","\\'",$str);
		$checkstr=str_replace('\\','\\\\',$checkstr);
	}
	return $checkstr;
}

function fsockgeturlfile($url){
	eregi("^(http://)?([^/:]*):?([^/]*)?(.*)?",$url,$fileparts);
	$port=($fileparts[3]=="")?80:intval($fileparts[3]);
	$strCommands="";
	$retBin=NULL;
	if($fphttp=fsockopen($fileparts[2],$port,$errno,$errstr,10)){
		$strCommands.= "GET ".$fileparts[4]." HTTP/1.1\n";
		$strCommands.= "Host:".$fileparts[2]."\n";
		$strCommands.= "Accept:*/*\n";
		$strCommands.="User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)\n";
		$strCommands=$strCommands."Referer:{$url}\n";
		$strCommands.="Connect:Keep-Alive\n";
		$strCommands.="\n";
		fputs($fphttp,$strCommands);
		$filesize=0;
		$crlf=chr(13).chr(10);
		$bodyEnd=chr(0).chr(0);
		while(($parts=fgets($fphttp))&&$parts!=$crlf&&(substr($parts,-2)!=$bodyEnd))$retBin.=$parts;
		eregi("Content-Length:([^\n]*)?.*",$retBin,$regs);
		$filesize=intval($regs[1]);
		if($filesize===0)return false;
		while(($parts=fgets($fphttp))&&$parts!=$crlf){
			$content.=$parts;
		}
		fclose($fphttp);
		return array("filesize"=>$filesize,"content"=>$content);
	}else{
		return false;
	}
}

function getfileurl($url){
	if (function_exists("fsockopen")){
		$http=new httpdown();
		$http->OpenUrl($url);
		return $http->GetRaw();
	}elseif (function_exists("file_get_contents")){
		$strhtml=file_get_contents($url);
	}elseif(function_exists("fopen")&&$fp=@fopen($url,"rb")){
		while($buf=fread($fp,4096))$strhtml.=$buf;
		fclose($fp);
	}
	return $strhtml;
}

//add by hj 20071221
//配合 _varstoscript，返回一个数组变量的PHP脚本形式
//@$varname 要保存的数级变量名
//@$arr 要转换的数组
function varstoscript($varname,$arr,$setvaluesign=null){
	return _varstoscript($varname,$arr,$setvaluesign);
}

//在一个二维数组中查找索引$index值等于$search子数组
//函本数类似在表中查找记录
function search_subarrary($arr,$index,$search){
	foreach ($arr as $k=>$v){
		if(isset($v[$index])&&$v[$index]==$search)return $v;
	}
	return false;
}
?>