<?php !defined('APP_DIR') ? die('acceess not defined') : '';
/**
 * 常用工具方法
 *
 */
class tool{
    public static $_config = array();
    
    public static $_lang = array();
    
    /**
     * 获取配置文件的信息
     *
     * @param str $config_str
     * @return mixed
     */
    static public function config($config_str){
        $config_arr = explode('.',$config_str);
        
        $file_name = array_shift($config_arr);
        if(is_dir(ROOT_DIR."/config/$file_name")){
            $file_name = "$file_name/".array_shift($config_arr);
        }
        if ( !key_exists($file_name,self::$_config) ) {
            $file_path = ROOT_DIR."/config/$file_name.php";
            if(file_exists($file_path)){
                require($file_path);
                self::$_config[$file_name] = $config;
            }else {
                return '';
                //die("Required file $file_path not exist!");
            }
        }
        $arr = self::$_config[$file_name];
        if(empty($config_arr)){
            return $arr;
        }
        do{
            $key = array_shift($config_arr);
            if (key_exists($key, $arr)) {
                if ( is_array($arr[$key]) AND ! empty($config_arr) ){
                    $arr = $arr[$key];
                }else{
                    return $arr[$key];
                }
            }else {
                break;
            }
        }while (!empty($config_arr));
        return '';
    }
    
    /**
     * 获取提示信息
     *
     * @param str $lang_str
     */
    static public function lang($lang_str){
        
    }
    
    /**
     * 创建文件夹
     *
     * @param string $dir '/aaa/bbb/ccc/'
     * @param string $mod 0777
     * @return bool
     */
    public static function mkdirs($dir, $mod=0777){
        if ( is_dir($dir) || @mkdir($dir, $mod)) return true;
        if ( !self::mkdirs(dirname($dir), $mod) ) return false;
        return @mkdir($dir, $mod);
    }
    
    /**
     * 删除文件夹
     *
     * @param string $dir
     */
    function removedirs($dir) { 
        if (is_dir($dir)) { 
            $objects = scandir($dir); 
            foreach ($objects as $object) { 
                if ($object != "." && $object != "..") { 
                    if (filetype($dir."/".$object) == "dir") self::removedirs($dir."/".$object); else unlink($dir."/".$object); 
                } 
            } 
            reset($objects); 
            rmdir($dir); 
        }
    }
    
    /**
     * 获取ip
     *
     */
    function ip(){
        $keys = array('HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'REMOTE_ADDR');
        $ip = '0.0.0.0';
        foreach ($keys as $key){
            if (key_exists($key, $_SERVER)) {
                $ip = $_SERVER[$key];
                break;
            }
        }
        return $ip;
    }
    
    /**
     * 多维数组中，按照第二维数组的某个键值排序
     *
     */
    static public function array_sort($array, $key){
        $rt = array();
        foreach ($array as $_arr){
            $rt[$_arr[$key]] = $_arr;
        }
        return $rt;
    }
    
    static public function isCrawler() {
        if (isset($_SERVER['HTTP_USER_AGENT'])){
            $agent= $_SERVER['HTTP_USER_AGENT'];
            $crawlers= array(
                "/Googlebot/",
                "/Yahoo! Slurp;/",
                "/msnbot/",
                "/Mediapartners-Google/",
                "/Scooter/",
                "/Yahoo-MMCrawler/",
                "/FAST-WebCrawler/",
                "/Yahoo-MMCrawler/",
                "/Yahoo! Slurp/",
                "/FAST-WebCrawler/",
                "/FAST Enterprise Crawler/",
                "/grub-client-/",
                "/MSIECrawler/",
                "/NPBot/",
                "/NameProtect/i",
                "/ZyBorg/i",
                "/worio bot heritrix/i",
                "/Ask Jeeves/",
                "/libwww-perl/i",
                "/Gigabot/i",
                "/bot@bot.bot/i",
                "/SeznamBot/i",
            );
            foreach($crawlers as $c) {
                if(preg_match($c, $agent)) {
                    return true;
                }
            }
        }
        return false;
    }
    
    /**
     * 将分类按照等级处理
     *
     * @param array $categories
     * @param int $parent_id
     * @param int $level
     * @param int $inchildren
     * @return array
     */
    static public function tree_categories($categories, $parent_id = 0, $level = 1, $inchildren = 1, $parent_key='parent_id', $id_key='id'){
        if (empty($categories)) {
        	return array();
        }
        $return_data = array();
        foreach ($categories as $key => $category){
            if ($category[$parent_key] == $parent_id) {
                $category['level_depth'] = $level;
            	unset($categories[$key]);
            	$children = self::tree_categories($categories, $category[$id_key], $level+1, $inchildren, $parent_key, $id_key);
            	if ( !empty($children) ) {
            	    if ($inchildren == 0) {
            	        $return_data[] = $category;
            	    	$return_data = array_merge($return_data,$children);
            	    }else {
            	        $category['children'] = $children;
            	        $return_data[] = $category;
            	    }
            	}else {
            	    $return_data[] = $category;
            	}
            }
        }
        return $return_data;
    }
    
    /**
     * 图片验证码
     *
     * @param int $num
     */
    public function identifyingCode(){
    	session_start();
        $num_1 = rand(10,50);
        $num_2 = rand(51,99);
        $text = "$num_1+$num_2= ?";
        $count = $num_1+$num_2;
        $_SESSION['imageIdentifyingCode'] = $count;
        //验证码图片
        $font = ROOT_DIR.'/font/simhei.ttf'; //字体
        header("Content-type: image/png");
        $img = imagecreatetruecolor(100,25); //图片大小
        $img_bg = imagecolorallocate($img, 255,255,255);  //定义图片背景色
        imagefill($img,0,0,$img_bg);                      //图片填入背景色
        $img_color = imagecolorallocate($img, 233, 14, 91);  //文字颜色
        imagettftext($img,16,0,8,20,$img_color,$font,$text); //文字写到图片上
        imagepng($img);      //生成图片
        imagedestroy($img);  //结束图片操作
        exit();
    }
    
    /**
     * 图片验证码
     *
     * @param int $num
     */
    public function identifyingCharsCode(){
	    session_start();
        $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
        $text = strtoupper($chars[mt_rand(0,35)].$chars[mt_rand(0,35)].$chars[mt_rand(0,35)].$chars[mt_rand(0,35)]);
        $_SESSION['imageIdentifyingCode'] = $text;
        //验证码图片
        $font = ROOT_DIR.'/font/simhei.ttf'; //字体
        header("Content-type: image/png");
        $img = imagecreatetruecolor(60,25); //图片大小
        $img_bg = imagecolorallocate($img, 255,255,255);  //定义图片背景色
        imagefill($img,0,0,$img_bg);                      //图片填入背景色
        $img_color = imagecolorallocate($img, 0, 0, 0);  //文字颜色
        $img_color_line = imagecolorallocate($img, 50, 50, 50);  //文字颜色
        
        imageline($img,0,mt_rand(10,20),60,mt_rand(10,20),$img_color_line);
        
        for ($i=0; $i<strlen($text); $i++){
        	$_text = $text[$i];
        	$x = 8+$i*12;
        	$range = mt_rand(-20,20);
        	imagettftext($img,16,$range,$x,20,$img_color,$font,$_text); //文字写到图片上
        }
        
        //imagettftext($img,16,10,8,20,$img_color,$font,$text); //文字写到图片上
        imagepng($img);      //生成图片
        imagedestroy($img);  //结束图片操作
        exit();
    }
    
    /**
     * 验证图片验证码是否准确
     *
     * @param unknown_type $code
     * @return unknown
     */
    public function checkIdentifyingCode($code){
        session_start();
        return $_SESSION['imageIdentifyingCode'] == strtoupper($code);
    }
    
    /**
     * 获取数据库limit的参数
     *
     * @param int $perpage
     * @param string $pagekey
     * @return array
     */
    public function sqlLimit($perpage=10,$pagekey='page'){
        $page = intval($_GET[$pagekey]) ? intval($_GET[$pagekey]) : 1;
        $offset = ($page-1)*$perpage;
        return array($offset,$perpage);
    }
    
    /**
     * 获取页面url的get参数
     *
     * @param string $key
     * @param string $value
     */
    public function getStr($key='', $value='', $url='', $pagename='page'){
        $gets = $_GET;
        if( key_exists($key,$gets) ){
            unset($gets[$key]);
        }
        //参数中屏蔽翻页
        if( $key != $pagename && key_exists($pagename,$gets) ){
            unset($gets[$pagename]);
        }
        $str_arr = array();
        if($gets){
            foreach ($gets as $_k => $_v){
                $str_arr[] = $_k.'='.urlencode($_v);
            }
        }
        if($key!=='' && $value!==''){
            $str_arr[] = $key.'='.urlencode($value);
        }
        
        if($str_arr){
            $getstr = $url.'?'.implode('&',$str_arr);
        }else {
            $getstr = $url;
        }
        return $getstr;
    }

    /**
     * utf8编码转gbk
     *
     * @param string $str
     */
    public function u2g($str){
        $str = iconv('utf-8','gbk',$str);
        return $str;
    }

    /**
     * gbk编码转utf8
     *
     * @param string $str
     */
    public function g2u($str){
        $str = iconv('gbk','utf-8',$str);
        return $str;
    }
    
    static public function gbk2utf8($arr){
        if( !is_array($arr) ){
            return iconv('GBK','UTF-8',$arr);
            /*$encode = mb_detect_encoding($arr, array('ASCII','UTF-8','GB2312','GBK','BIG5'));
            if($encode != 'UTF-8'){
                //return iconv($encode,'UTF-8',$arr);
				return iconv('GBK','UTF-8',$arr);
            }else{
                if ($arr=='困') {
                	return iconv('GBK','UTF-8',$arr);
                }
				return $arr;
			}*/
        }
    	foreach ($arr as $key => $vo){
            $arr[$key]=self::gbk2utf8($vo);
        }
        return $arr;
    }
    
    static public function utf82gbk($arr){
		if( !is_array($arr) ){
			$encode = mb_detect_encoding($arr, array('ASCII','UTF-8','GB2312','GBK','BIG5'));
			if($encode=="UTF-8"){
				return iconv('UTF-8','GBK',$arr);
			}else{
				return $arr;
			}	
		}
		foreach ($arr as $key=>$vo){
			$arr[$key]=self::utf82gbk($vo);
		}
		return $arr;
	 }

    /**
     * 调取接口
     *
     * @param string $str
     */
    public function api_get_contents($conf,$params,$isunserialize='',$city='nj'){
    	$conf = 'jjr.conf.apiurl.'.$conf;
    	$url  = tool::config($conf).$params.'&city='.$city;
		if($_GET['yy']){
			echo $url;

		}
		$data = @file_get_contents($url);           //需要封装在 server里去

		if ($isunserialize == '1') {
			$str = unserialize($data);
		}else{
			$str = $data;
		}
        return $str;
    }
    
    /**
     * 调取接口
     *
     * @param string $str
     */
    public function get_contents_by_url($url,$isunserialize=''){
		$data = @file_get_contents($url);           //需要封装在 server里去
		if ($isunserialize == '1') {
			$data = unserialize($data);
		}
        return $data;
    }
    
    /**
     * 获得数组中的id 组成串 暂支持二维数组
     *
     * @param array $arr
     * @param str $key
     * @return str
     */
    public function fKeys($arr,$key,$param=','){
    	if (empty($arr) || !$key) {
    		return false;
    	}
    	$str = '';
    	foreach ($arr as $k => $v) {
    		$str .= $param.$v[$key];
    	}
    	if (!$str) {
    		return false;
    	}
    	return trim($str,$param);
    }

	//批量转换数组
	function array_iconv($input_code, $output_code,$result)  
	{  
		if (is_array($result))  
		{  
			if(!empty($result)){
				foreach ($result as $key => $value)  
				{  
					// 如果是在类里面则改为：$this->dgiconv($value, $flag);  
					if($value){
					$value = array_iconv($input_code, $output_code,$value);   
					}
					$_temp[$key] = $value;  
				}
			}
			else
			{
				return $result;
			}
		}  
		else 
		{  
			return iconv($input_code, $output_code, $result);  
		}

		return $_temp;  
	}

    function dump($vars, $label = '', $return = false) {
        if (ini_get('html_errors')) {
            $content = "<pre>\n";
            if ($label != '') {
                $content .= "<strong>{$label} :</strong>\n";
            }
            $content .= htmlspecialchars(print_r($vars, true));
            $content .= "\n</pre>\n";
        } else {
            $content = $label . " :\n" . print_r($vars, true);
        }
        if ($return) { return $content; }
        echo $content;
        return null;
    }
    
    public function transCoding($arr){
        foreach ($arr as $key=>$vo){
            if(is_array($vo)){
                $arr[$key]=self::transCoding($vo);
            }else{
                $arr[$key]=iconv('GBK','UTF-8',$vo);
            }
        }
        return $arr;
    }
    
    public function gbk_json_encode($arr){
        $arr = self::gbk2utf8($arr);
        return json_encode($arr);
    }
    
    /**
     * gbk json encode
     *
     * @param mixed $arr
     * @return string
     */
    public function json_encode($arr){
        $arr = self::gbk2utf8($arr);
        return json_encode($arr);
    }
    
    /**
     * 将数组转换成字符串
     *
     * @param array $arr
     * @param string
     */
    public static function arrayToCode($arr, $depth=1) {
    	$arr_str = "array(\n";
    	$space = '';
    	$bracket_space = '';
    	for ($i=0; $i<$depth; $i++) {
    		$space .= '    ';
    	}
    	for ($j=0; $j<$depth-1; $j++) {
    		$bracket_space .= '    ';
    	}
        if($arr){
			foreach ($arr as $key => $val) {
				if ( is_array($val) ) {
					$val = self::arrayToCode($val, $depth+1);
					$arr_str .=  "$space'$key' => $val,\n";
				} else {
					$val = str_replace("'", "\'", $val);
					$arr_str .= "$space'$key' => '$val',\n";
				}
			}
		}
    	$arr_str .= "$bracket_space)";
    	return $arr_str;
    }
}
?>