<?php
if (!defined('IN_59MIAO'))
{
	exit('Access Defined');
}
//工具类，封装函数和算法等。
class Tool {
	
	//获取客户端ip
	static public function getIP() {
		return $_SERVER["REMOTE_ADDR"];
	}
	
	//获取目前的时间
	static public function getDate() {
		return date('Y-m-d H:i:s');
	}
	
	//表单提交字符转义
	static public function setFormString($_string) {
		if (!get_magic_quotes_gpc()) {
			if (Validate::isArray($_string)) {
				foreach ($_string as $_key=>$_value) {
					$_string[$_key] = self::setFormString($_value);	//不支持就用代替addslashes();
				}
			} else {
				return addslashes($_string); //mysql_real_escape_string($_string, $_link);
			}
		}
		return $_string;
	}
	
	//html过滤
	static public function setHtmlString($_data) {
		$_string = '';
		if (Validate::isArray($_data)) {
			if (Validate::isNullArray($_data)) return $_data;
			foreach ($_data as $_key=>$_value) {
				$_string[$_key] = self::setHtmlString($_value);  //递归
			}
		} elseif (is_object($_data)) {
			foreach ($_data as $_key=>$_value) {
				$_string->$_key = self::setHtmlString($_value);  //递归
			}
		} else {
			$_string = htmlspecialchars($_data);
		}
		return $_string;
	}
	
	//表单选项转换
	static public function setFormItem($_data, $_key, $_value) {
		$_items = array();
		if (Validate::isArray($_data)) {
			foreach ($_data as $_v) {
				$_items[$_v->$_key] = $_v->$_value;
			}
		}
		return $_items;
	}
	//api列表转换
	static public function setFormApiItem($_data, $_key, $_value) {
		$_items = array();
		if (Validate::isArray($_data)) {
			foreach ($_data as $_v) {
				$_items[$_v[$_key]] = $_v[$_value].' ( ID:'.$_v[$_key].')';
			}
		}
		return $_items;
	}
	
	//过滤
	static public function setRequest() {
		if (isset($_GET)) $_GET = Tool::setFormString($_GET);
		if (isset($_POST)) $_POST = Tool::setFormString($_POST);
	}
	
	//得到上一页
	static public function getPrevPage() {
		return empty($_SERVER["HTTP_REFERER"]) ? './index.php?a=admin' : $_SERVER["HTTP_REFERER"];
	}
	//弹窗赋值关闭(上传专用)
	static public function alertOpenerClose($_info,$sourcepath,$minpath) {
		echo "<script type='text/javascript'>alert('$_info');</script>";
		echo "<script type='text/javascript'>opener.document.contentjs.site_logo.value='$sourcepath';</script>";
		echo "<script type='text/javascript'>opener.document.contentjs.sourcepath.value='$sourcepath';</script>";
		echo "<script type='text/javascript'>opener.document.contentjs.pic.style.display='';</script>";
		echo "<script type='text/javascript'>opener.document.contentjs.pic.src='$sourcepath';</script>"; //获取图片上传的路径显示在网页上
		echo "<script type='text/javascript'>window.close();</script>";
		exit();
	}
	//弹窗返回
	static public function alert($_info) {
		echo "<script type='text/javascript'>alert('$_info')</script>";
		exit();
	}
	//删除文件
	static public function unlinkFile($_file){
		if(file_exists($_file)){
				@unlink($_file);
		}
	}
	
	//判断一个数组是一维数组还是二维数组
	static public function IsTwoArray($array){
	  return count($array)==count($array, 1);
	}
	//字符串截取
	static public function subStr($_object,$_field,$_length,$_encoding) {
		if ($_object) {
			if (is_array($_object)) {
				foreach ($_object as $_value) {
					if (mb_strlen($_value->$_field,$_encoding) > $_length) {
						$_value->$_field = mb_substr($_value->$_field,0,$_length,$_encoding).'';
					}
				}
			} else {
				$_object = mb_substr($_object,0,$_length,$_encoding);
			}
		}
		return $_object;
	}
	//序列化函数
	static public function Serialize($array){
		return serialize($array);
	}
	//反序列化函数
	static public function UnSerialize($array){
		return unserialize($array);
	}
 	//筛选数据 不过滤代码  用于文章==
 	static public function selectData($_requestData, $_fields) {
 		$_selectData = array();
 		foreach ($_requestData as $_key=>$_value) {
			if (Validate::inArray($_key, $_fields)) {
				$_selectData[$_key] = $_value;
			}
		}
		return $_selectData;		
 	}
 	//清楚缓存
	static public function delCache($dir){	//删除目录
	    $handle=@opendir($dir);
	    while ($file = @readdir($handle)) {
	        $bdir=$dir.'/'.$file;
	        if (filetype($bdir)=='dir') {
	            if($file!='.' && $file!='..')
	            self::delCache($bdir);
	        } else {
	            @unlink($bdir);
	        }
	    }
	    closedir($handle);
	    @rmdir($dir);		
		return true;
	}
	
	/**
	 * 重写 URL 地址
	 *
	 * @access  public
	 * @param   string  $app        执行程序
	 * @param   array   $params     参数数组
	 * @param   string  $append     附加字串
	 * @return  void
	 */
//	static public function buid_uri($app, $params, $append = ''){
//		    $args = array('id'   => 0,
//                  'cid'   => 0,
//                  'iid'   => 0,
//                  'pid'  => 0,                 
//                  'sid'   => 0                 
//                );
//    		extract(array_merge($args, $params));
//    		$uri= '';
//    		switch ($app)
//    		{
//    			case 'mall':
//    				if(REWRITE){
//    					$uri=MALL;
//    				}
//    				else{
//    					$uri='./index.php?a=mall';
//    				}
//    				break;
//    			case 'sellerinfo':
//    				if(!isset($_GET['id'])){
//    					return false;
//    				}
//    				else{
//    					if(REWRITE){
//    						$uri=SELLERINFO.'_'.$_GET['id'];
//    					}
//    					else{
//    						$uri='./index.php?a=sellerinfo&id='.$_GET['id'].'';
//    					}
//    				}
//    				break;
//    			case 'all':
//    				if(REWRITE){
//    					$uri=ALL;
//    				}
//    				else{
//    					$uri='./index.php?a=all';
//    				}
//    				break;
//    			case 'category':
//    				if(REWRITE){
//    					if(isset($_GET['cid'])&&!isset($_GET['tab'])){
//    						$uri=B2C_CATEGORY.'-'.$_GET['cid'];
//    					}
//    					else{
//    						$uri='index.php?a=category&cid='.$_GET['cid'].'';
//    					}
//    					if(isset($_GET['cid']) && isset($_GET['tab']) && $_GET['tab']=='tao'){
//    						$uri=TAO_CATEGORY.'-tao-'.$_GET['cid'];
//    					}else{
//    						$uri='index.php?a=category&tab=tao&cid='.$_GET['cid'].'';
//    					}
//    				}
//    			case 'promo':
//    				if(REWRITE){
//    					
//    				}
//    		}
//	} 
//		
 	//禁止ip访问函数
	static public function banip($value1,$value2){
			$ban_range_low=ip2long($value1);
			$ban_range_up=ip2long($value2);
			$ip=ip2long($_SERVER["REMOTE_ADDR"]);			
			if ($ip>=$ban_range_low && $ip<=$ban_range_up)
			{
				echo "对不起,您的IP在被禁止的IP段之中，禁止访问！";
				exit();
			}
	}
	//屏蔽蜘蛛访问
	static public function banspider($ban_str){			
		if(preg_match("/($ban_str)/i", $_SERVER['HTTP_USER_AGENT']))
		{		    
		    exit; 
		}
	}	
	//获取最后蜘蛛爬行记录
	static public function get_bot()
	{
        $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
                      
        if (strpos($useragent, 'googlebot') !== false){
                return 'googlebot';
        }
      
        if (strpos($useragent, 'msnbot') !== false){
                return 'msnbot';
        }
      
        if (strpos($useragent, 'slurp') !== false){
                return 'slurp';
        }
      
        if (strpos($useragent, 'baiduspider') !== false){
                return 'baiduspider';
        }
      
        if (strpos($useragent, 'sogou') !== false){
                return 'sogou';
        }
      
        if (strpos($useragent, 'sosospider') !== false){
                return 'sosospider';
        }
      
        if (strpos($useragent, 'bingbot') !== false){
                return 'bingbot';
        }
        if (strpos($useragent, 'ia_archiver') !== false){
                return 'ia_archiver';
        }    
        if (strpos($useragent, 'youdaobot') !== false){
                return 'youdaobot';
        }          
        return false;
	}
	static public function Get_REQUEST_URI(){
		if (empty($_SERVER['REQUEST_URI'])){			
			// IIS Mod-Rewrite
			if (isset($_SERVER['HTTP_X_ORIGINAL_URL'])) {
				$_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_ORIGINAL_URL'];
			}
			// IIS Isapi_Rewrite
			else if (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
				$_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL'];
			} else {
				// Use ORIG_PATH_INFO if there is no PATH_INFO
				if ( !isset($_SERVER['PATH_INFO']) && isset($_SERVER['ORIG_PATH_INFO']) )
					$_SERVER['PATH_INFO'] = $_SERVER['ORIG_PATH_INFO'];
				// Some IIS + PHP configurations puts the script-name in the path-info (No need to append it twice)
				if ( isset($_SERVER['PATH_INFO']) ) {
					if ( $_SERVER['PATH_INFO'] == $_SERVER['SCRIPT_NAME'] )
						$_SERVER['REQUEST_URI'] = $_SERVER['PATH_INFO'];
					else
						$_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] . $_SERVER['PATH_INFO'];
				}
				// Append the query string if it exists and isn't null
				if (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])) {
					$_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
				}
			}
		}		
		return $_SERVER['REQUEST_URI'];
		
	}	
 	//检测文件目录是否可写
	static public function file_mode_info($file_path)
	{
	    /* 如果不存在，则不可读、不可写、不可改 */
	    if (!file_exists($file_path))
	    {
	        return false;
	    }
	
	    $mark = 0;
	
	    if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')
	    {
	        /* 测试文件 */
	        $test_file = $file_path . '/cf_test.txt';
	
	        /* 如果是目录 */
	        if (is_dir($file_path))
	        {
	            /* 检查目录是否可读 */
	            $dir = @opendir($file_path);
	            if ($dir === false)
	            {
	                return $mark; //如果目录打开失败，直接返回目录不可修改、不可写、不可读
	            }
	            if (@readdir($dir) !== false)
	            {
	                $mark ^= 1; //目录可读 001，目录不可读 000
	            }
	            @closedir($dir);
	
	            /* 检查目录是否可写 */
	            $fp = @fopen($test_file, 'wb');
	            if ($fp === false)
	            {
	                return $mark; //如果目录中的文件创建失败，返回不可写。
	            }
	            if (@fwrite($fp, 'directory access testing.') !== false)
	            {
	                $mark ^= 2; //目录可写可读011，目录可写不可读 010
	            }
	            @fclose($fp);
	
	            @unlink($test_file);
	
	            /* 检查目录是否可修改 */
	            $fp = @fopen($test_file, 'ab+');
	            if ($fp === false)
	            {
	                return $mark;
	            }
	            if (@fwrite($fp, "modify test.\r\n") !== false)
	            {
	                $mark ^= 4;
	            }
	            @fclose($fp);
	
	            /* 检查目录下是否有执行rename()函数的权限 */
	            if (@rename($test_file, $test_file) !== false)
	            {
	                $mark ^= 8;
	            }
	            @unlink($test_file);
	        }
	        /* 如果是文件 */
	        elseif (is_file($file_path))
	        {
	            /* 以读方式打开 */
	            $fp = @fopen($file_path, 'rb');
	            if ($fp)
	            {
	                $mark ^= 1; //可读 001
	            }
	            @fclose($fp);
	
	            /* 试着修改文件 */
	            $fp = @fopen($file_path, 'ab+');
	            if ($fp && @fwrite($fp, '') !== false)
	            {
	                $mark ^= 6; //可修改可写可读 111，不可修改可写可读011...
	            }
	            @fclose($fp);
	
	            /* 检查目录下是否有执行rename()函数的权限 */
	            if (@rename($test_file, $test_file) !== false)
	            {
	                $mark ^= 8;
	            }
	        }
	    }
	    else
	    {
	        if (@is_readable($file_path))
	        {
	            $mark ^= 1;
	        }
	
	        if (@is_writable($file_path))
	        {
	            $mark ^= 14;
	        }
	    }
	
	    return $mark;
	}
	
}
?>