<?php
/********************************************************************
 *                              DirCMS后台公用函数
 *                            -------------------
 *   begin                : 2010-4-10
 *   copyright            : (C) 2009 DirCMS
 *   email                : uuturn@126.com
 *
 *   $Id: global.func.php, 2010-10-30 22:08:24 M Exp $
 ********************************************************************/

function admin_tlp($tlp)
{
	!file_exists(DIRCMS_ROOT.'admin/template/'.$tlp.'.tlp.php') && fatal_error('模板文件'.$tlp.'.tlp.php不存在!');
	return DIRCMS_ROOT.'admin/template/'.$tlp.'.tlp.php';
}


function basename_suffix($dir,$suffix='.html') //////////// 取得一个路径中的文件名（不带后缀）
{
	return basename($dir,$suffix);
}

function gethosturlname()
{
	$port=$_SERVER["SERVER_PORT"]=='80'?'':':'.$_SERVER["SERVER_PORT"];
	$ServerName = strtolower($_SERVER['SERVER_NAME']?$_SERVER['SERVER_NAME']:$_SERVER['HTTP_HOST']); 
	if(strpos($ServerName,'http://'))
	{   
		$ServerName=str_replace('http://','',$ServerName);
	}  
	return strpos($ServerName,':')?'http://'.$ServerName:'http://'.$ServerName.$port;
}

function set_config($config)
{
	global $DIRCMS;
	if(!is_array($config)) return false;
	$configfile = DIRCMS_ROOT.'config.inc.php';
	if(!is_writable($configfile)) fatal_error('Please chmod ./config.inc.php to 0777 !');
	$pattern = $replacement = array();
	$config['site_url']=$config['site_url']?$config['site_url']:gethosturlname().DIRCMS_PATH;
	
	foreach($config as $k=>$v)
	{
		$v=in_array($k,array('statistics_online'))?str_replace("\'",'',$v):strip_tags(str_replace("\'",'',$v));
		$pattern[$k] = "/define\(\s*['\"]".strtoupper($k)."['\"]\s*,\s*([']?)[^']*([']?)\s*\)/is";
        $replacement[$k] = "define('".strtoupper($k)."', \${1}".$v."\${2})";
	}
	$str = file_get_contents($configfile);
	$str = preg_replace($pattern, $replacement, $str);
	
	foreach($config as $_k => $_v)
	{
		$_config[strtolower($_k)]=$_v;
	}
	
	$_tconfig=n_array_diff($DIRCMS,$_config);
	
	foreach($_tconfig as $key=>$value)
	{
		$_config[$key]=$value;
	}
	//$_config=array_merge($_config,$_tconfig); //某些版本不支持 + 

	$_config=array_unique($_config);
	//print_r($_config);exit();
	$_config['tpl_name']=$_config['tlp_name']=TPL_NAME;
	
	cache_config('common.cache.php',array_map('stripcslashes',$_config));
	return file_put_contents($configfile, $str);
}

function hash_str($len=10) //返回一个长度为$len的随机字符串，该字符串可能由字母和数字构成
{
	$hash=preg_replace('/[^a-z0-9]+/i','',crypt(mt_rand(10,99)));
	$max=strlen($hash)-$len>0?strlen($hash)-$len:0;	
	return substr($hash,mt_rand(0,$max),$len);
}

function get_hostip()
{
	return $_SERVER['SERVER_ADDR']?$_SERVER['SERVER_ADDR']:gethostbyname($_SERVER['SERVER_NAME']); 
}
?>