<?php
/***
*
*@package binzcms
*@version $id:CommonClass.php, v 1.0
*@author 斌子
*@Fri Jan 02 15:31:39 CST 2009
*@copyright (c) 2009-2010 binzcms
*
*/
if(!defined("BINZCMS")) {
	die("hacking");
}
/**
 *
 * CommonClass
 * 通用函数类
 * 
 */
class CommonClass {
	/**
	 * cut_str
	 *
	 * 截取字符串长度
	 * @access  public（权限）
	 * @param   string	$str		需要截取的字符串
	 * @param   int		$num		截取长度
	 * @return  string	截取后的字符串
	 */
	public function cut_str($str,$num){
		$count = 0;
		for($i = 0;$i < $num;$i++) {
			if(ord($str[$i]) > 128) {
				$count++;
			}
		}
		return (((int)($count/2)*2) == $count)?substr($str,0,$num):substr($str,0,$num-1);
	}
	/**
	 * get_true_ip
	 *
	 * 获取当前ip
	 * @access  public（权限）
	 *
	 * @return  string	ip地址
	 */
	public function get_true_ip() {

		static $realip = NULL;
		if ($realip !== NULL) {
			return $realip;
		}

		if (isset($_SERVER)) {
			if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
				$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

				foreach ($arr AS $ip) {
					$ip = trim($ip);

					if ($ip != 'unknown') {
						$realip = $ip;

						break;
					}
				}
			} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
				$realip = $_SERVER['HTTP_CLIENT_IP'];
			} else {
				if (isset($_SERVER['REMOTE_ADDR'])) {
					$realip = $_SERVER['REMOTE_ADDR'];
				} else {
					$realip = '0.0.0.0';
				}
			}
		} else {
			if (getenv('HTTP_X_FORWARDED_FOR')) {
				$realip = getenv('HTTP_X_FORWARDED_FOR');
			} elseif (getenv('HTTP_CLIENT_IP')) {
				$realip = getenv('HTTP_CLIENT_IP');
			} else {
				$realip = getenv('REMOTE_ADDR');
			}
		}

		preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
		$realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

		return $realip;
	}
	/**
	 * make_dir
	 *
	 * 创建目录
	 * @access  public（权限）
	 * @param   string	$folder		目录名称
	 * @return  bool
	 */
	public function make_dir($folder) {

		$reval = false;
		if (!file_exists($folder)) {
			@umask(0);
			preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);
			$base = ($atmp[0][0] == '/') ? '/' : '';

			foreach ($atmp[1] AS $val) {
				if ('' != $val) {
					$base .= $val;

					if ('..' == $val || '.' == $val) {

						$base .= '/';

						continue;
					}
				} else {
					continue;
				}

				$base .= '/';

				if (!file_exists($base)) {
					if (@mkdir(rtrim($base, '/'), 0777)) {
						@chmod($base, 0777);
						$reval = true;
					}
				}
			}
		} else {
			$reval = is_dir($folder);
		}

		clearstatcache();

		return $reval;
	}
	/**
	 * write_file
	 *
	 * 检查目录是否可写
	 * @access  public（权限）
	 * @param   string 	$dir_path		目录
	 * @param   string	$test_file		测试文件名称
	 * @return  bool
	 */
	public function write_file($dir_path,$test_file	= "binz_text.txt") {
		$fh	= @fopen($dir_path.'/'.$test_file,'w');
		if(!fh) {
			return false;
		} else {
			@fclose($fh);
			if(@unlink($dir_path.'/'.$test_file)) {
				return true;
			} else {
				return false;
			}
		}
	}
	/**
	 * create_binz_code
	 *
	 * 调用
	 * @access  public（权限）
	 * @param   string	$str		鼠标放到验证码时的提示文字	
	 * @return  string	输出验证码
	 */
	public function create_binz_code($str='看不清？点击更换') {
		return '<img src="'.WEB_HOST.'/index.php?ctl=code" onClick="this.src=this.src+\'&ctl=code\'" style="cursor:pointer" align="absmiddle" alt="'.$str.'">';
	}
	/**
	 * real_server_ip
	 *
	 * 获取服务器ip
	 * @access  public（权限）
	 * 
	 * @return  string	ip地址
	 */
	public function real_server_ip() {

		static $serverip = NULL;
		if ($serverip !== NULL) {
			return $serverip;
		}

		if (isset($_SERVER)) {
			if (isset($_SERVER['SERVER_ADDR'])) {
				$serverip = $_SERVER['SERVER_ADDR'];
			} else {
				$serverip = '0.0.0.0';
			}
		} else {
			$serverip = getenv('SERVER_ADDR');
		}

		return $serverip;
	}
	/**
	 * html_input
	 *
	 * 生成文本框，单选，多选，文本域
	 * @access  public（权限）
	 * @param   string			$name	表单名称（id和名字相同）
	 * @param   string			$type	表单的类型（text，hidden，radio，checkbox，textarea）
	 * @param   string/array	$str	默认显示的内容，如果是radio类型或checkbox类型时，$str应为数组形式，键名为value值，键值为显示的文本
	 * @param   array			$array	只有类型为radio或是checkbox时使用，默认选中的选框
	 * @param   string			$other	当需要写入css，或是js代码可以写在这里
	 * @return  string			表单框
	 */
	function html_input($name,$type='text',$str='',$array=array(),$other='') {
		$input = '<input type="'.$type.'" name="'.$name.'" id="'.$name.'" ';
		if($type == 'textarea') {
			$input = '<textarea name="'.$name.'" id="'.$name.'" ';
		}
		if(!empty($other)) {
			$input .= ' '.$other.' ';
		}
		if(!empty($str)) {
			$str = $str;
		}
		if($type == 'radio' || $type =='checkbox') {
			if(is_array($str)) {
				$forminput = '';
				foreach ($str as $k => $v) {
					$forminput .= $input.' value="'.$k.'" ';
					if(in_array($k,$array)) {
						$forminput .= ' checked="checked"';
					}
					$forminput .= ' />'."&nbsp;".$v."&nbsp;";
				}
			}
		} else {
			if($type == 'textarea') {
				$forminput = $input.'>'.$str.'</textarea>';
			} else {
				$forminput = $input.' value="'.$str.'" />';
			}
		}
		return $forminput;
	}
	/**
	 * html_select
	 *
	 * 生成下来菜单
	 * @access  public（权限）
	 * @param   string			$name		表单名称（id和名字相同）
	 * @param   array			$textarray	下拉表单内容，此为数组形式，键名为value，键值为显示文本
	 * @param   string			$top_array	下拉默认名称，比如‘请选择’,$top_array[0]是名称，$top_array[1]是值
	 * @param   string			$other		当需要写入css，或是js代码可以写在这里
	 * @param   array			$selected	默认选中的菜单
	 * @return  string			表单框
	 */
	public function html_select($name,$textarray,$top_array=array(),$selected='',$other='',$array=array()) {
		if(!is_array($textarray)) {
			return '';
		}
		$select = '<select name="'.$name.'" id="'.$name.'" '.$other.' >';
		if(!empty($top_array)) {
			$select .= '<option value="'.$top_array[1].'">'.$top_array[0].'</option>';
		}
		$formselect = '';
		foreach ($textarray as $k => $v) {
			/*添加对多维数组的赋值*/
			if(count($array)>0) {
				$k	= $v[$array[0]];//值
				$v	= $v[$array[1]];//文本
			}

			$formselect .= '<option value="'.$k.'"';
			if($k == $selected) {
				$formselect .= ' selected';
			}
			$formselect .=' >'.$v.'</option>';
		}
		$select .= $formselect.'</select>';
		return $select;
	}
	/**
	 * check_file_type
	 *
	 * 检查文件类型
	 * @access  public（权限）
	 * @param   string      $filename            文件名
	 * @param   string      $realname            真实文件名
	 * @param   string      $limit_ext_types     允许的文件类型
	 * @return  string
	 */
	public function check_file_type($filename, $realname = '', $limit_ext_types = '') {
		if ($realname) {
			$extname = strtolower(substr($realname, strrpos($realname, '.') + 1));
		} else {
			$extname = strtolower(substr($filename, strrpos($filename, '.') + 1));
		}

		$str = $format = '';

		$file = @fopen($filename, 'rb');
		if ($file) {
			$str = @fread($file, 0x400); // 读取前 1024 个字节
			@fclose($file);
		} else {
			if (stristr($filename, ROOT_PATH) === false) {
				if ($extname == 'jpg' || $extname == 'jpeg' || $extname == 'gif' || $extname == 'png' || $extname == 'doc' ||
				$extname == 'xls' || $extname == 'txt'  || $extname == 'zip' || $extname == 'rar' || $extname == 'ppt' ||
				$extname == 'pdf' || $extname == 'rm'   || $extname == 'mid' || $extname == 'wav' || $extname == 'bmp' ||
				$extname == 'swf' || $extname == 'chm'  || $extname == 'sql' || $extname == 'cert') {
					$format = $extname;
				}
			} else {
				return '';
			}
		}

		if ($format == '' && strlen($str) >= 2 ) {
			if (substr($str, 0, 4) == 'MThd' && $extname != 'txt') {
				$format = 'mid';
			} elseif (substr($str, 0, 4) == 'RIFF' && $extname == 'wav') {
				$format = 'wav';
			} elseif (substr($str ,0, 3) == "\xFF\xD8\xFF") {
				$format = 'jpg';
			} elseif (substr($str ,0, 4) == 'GIF8' && $extname != 'txt') {
				$format = 'gif';
			} elseif (substr($str ,0, 8) == "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A") {
				$format = 'png';
			} elseif (substr($str ,0, 2) == 'BM' && $extname != 'txt') {
				$format = 'bmp';
			} elseif ((substr($str ,0, 3) == 'CWS' || substr($str ,0, 3) == 'FWS') && $extname != 'txt') {
				$format = 'swf';
			} elseif (substr($str ,0, 4) == "\xD0\xCF\x11\xE0") {   // D0CF11E == DOCFILE == Microsoft Office Document
				if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extname == 'doc') {
					$format = 'doc';
				} elseif (substr($str,0x200,2) == "\x09\x08" || $extname == 'xls') {
					$format = 'xls';
				} elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extname == 'ppt') {
					$format = 'ppt';
				}
			} elseif (substr($str ,0, 4) == "PK\x03\x04") {
				$format = 'zip';
			} elseif (substr($str ,0, 4) == 'Rar!' && $extname != 'txt') {
				$format = 'rar';
			} elseif (substr($str ,0, 4) == "\x25PDF") {
				$format = 'pdf';
			} elseif (substr($str ,0, 3) == "\x30\x82\x0A") {
				$format = 'cert';
			} elseif (substr($str ,0, 4) == 'ITSF' && $extname != 'txt') {
				$format = 'chm';
			} elseif (substr($str ,0, 4) == "\x2ERMF") {
				$format = 'rm';
			} elseif ($extname == 'sql') {
				$format = 'sql';
			} elseif ($extname == 'txt') {
				$format = 'txt';
			}
		}

		if ($limit_ext_types && stristr($limit_ext_types, '|' . $format . '|') === false) {
			$format = '';
		}

		return $format;
	}
	/**
	 * make_semiangle
	 *
	 * 全角转换为半角
	 * @access  public（权限）
	 * @param   string  $str         待转换字串
	 * @return  string  $str         处理后字串
	 */
	public function make_semiangle($str) {
		$arr = array('０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',
		'５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
		'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',
		'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',
		'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',
		'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',
		'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',
		'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',
		'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',
		'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',
		'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',
		'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',
		'ｙ' => 'y', 'ｚ' => 'z',
		'（' => '(', '）' => ')', '〔' => '[', '〕' => ']', '【' => '[',
		'】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']',
		'‘' => '[', '’' => ']', '｛' => '{', '｝' => '}', '《' => '<',
		'》' => '>',
		'％' => '%', '＋' => '+', '—' => '-', '－' => '-', '～' => '-',
		'：' => ':', '。' => '.', '、' => ',', '，' => '.', '、' => '.',
		'；' => ',', '？' => '?', '！' => '!', '…' => '-', '‖' => '|',
		'”' => '"', '’' => '`', '‘' => '`', '｜' => '|', '〃' => '"',
		'　' => ' ');

		return strtr($str, $arr);
	}
	/**
	 * admin_msg
	 *
	 * 管理员后台提示信息
	 * @access  public（权限）
	 * @param   string		$message	提示内容
	 * @param   integer		$type		跳转类型
	 * @param   array		$links		可选链接
	 * @param   object		$class_tpl	模板引擎类
	 * @param   bool		$redirect	是否自动跳转 暂时没有用处
	 * @param   string		$jump_time	跳转时间
	 * @param   string		$tpl_name	提示信息模板名称
	 * @return  void		返回类型
	 */
	public function admin_msg($message,$type=0,$links=array(),$class_tpl='',$redirect = true,$jump_time=5,$tpl_name='admin_message') {
		$language_path	= (ADMIN_LG == true ? ADMIN_LANGUAGE : FRONT_LANGUAGE);
		include(ROOT_PATH.'/languages/'.$language_path.'/AdminCommonLanguage.php');

		if(count($links) == 0) {
			$links[0]['text'] = $language['common_click_url'];
			$links[0]['href'] = 'javascript:history.go(-1)';
		}
		$class_tpl->set_var($language);
		$class_tpl->set_var('message',		$message);
		$class_tpl->set_var('type',			$type);
		$class_tpl->set_var('links',		$links);
		$class_tpl->set_var('jump_time',	$jump_time);
		$class_tpl->set_var('default_url',	$links[0]['href']);
		$class_tpl->set_var('redirect',		$redirect);

		$class_tpl->set_tag($tpl_name);
		exit;
	}
	/**
	 * front_msg
	 *
	 * 前台提示信息
	 * @access  public（权限）
	 * 
	 */	
	public function front_msg($message,$type=0,$links=array(),$class_tpl='',$redirect = true,$jump_time=5,$tpl_name='front_message') {
		$this->admin_msg($message,$type,$links,$class_tpl,$redirect,$jump_time,$tpl_name);
	}
	/**
	 * out_calendar
	 *
	 * 输出时间js代码
	 * @access  public（权限）
	 * 
	 */
	public function out_calendar() {
		$language_path	= (ADMIN_LG == true ? ADMIN_LANGUAGE : FRONT_LANGUAGE);
		include(ROOT_PATH.'/languages/'.$language_path.'/AdminCommonLanguage.php');

		$cal_language	= '';
		foreach ($language['calendar_lang'] AS $cal_key => $cal_data)
		{
			$cal_language .= 'var ' . $cal_key . " = \"" . $cal_data . "\";\r\n";
		}

		$calendar_str = file_get_contents(ROOT_PATH.'/js/calendar/calendar.js');

		return $cal_language.$calendar_str;
	}
	/**
	 * out_calendar
	 *
	 * 创建一个JSON格式的数据
	 * @access  public
	 * @param   string      $content
	 * @param   integer     $error
	 * @param   string      $message
	 * @param   array       $append
	 * @return  void
	 * 
	 */
	function make_json_response($content='', $error="0", $message='', $append=array())
	{
		include_once(ROOT_PATH . '/include/JsonClass.php');
		$json = new Services_JSON();
		$res = array('error' => $error, 'message' => $message, 'content' => $content);
		if (!empty($append))
		{
			foreach ($append AS $key => $val)
			{
				$res[$key] = $val;
			}
		}
		$val = $json->encode($res);
		exit($val);
	}
	/**
	 * addslashes_value
	 *
	 * 对变量中的特殊字符进行转义
	 * @access  public（权限）
	 */
	public function addslashes_value($value) {
		if (empty($value)) {
			return $value;
		} else {
			return (is_array($value) ? array_map($this->addslashes_value, $value) : addslashes($value));
		}
	}
}
?>