<?php
/*
'#################################################################
'# 程序名称：中环CMSV2.0
'# 授权方式：免费软件
'# 作者：善
'# 联系QQ:9118847
'# 作者网站:http://www.ps173.com
'# 发布时间：2015-6-10
'# 声明：欢迎广大的PHP爱好者一起共同探讨
'# 声明：各种用途均可免费使用、自由传播，但必须保留程序代码中的版权信息。
'#################################################################
 */
 
//工具类

class val{
	
	//字符串截取
	static function substr($data, $field, $length){
		if(isset($data)){
			if(is_array($data)){
				foreach($data as $val){
					if(mb_strlen($val[$field]) > $length){
						$val[$field] = mb_substr($val[$field], 0, $length).'...';
					}
				}
			}else{
				if(mb_strlen($data) > $length){
					return mb_substr($data, 0, $length).'...';
				}else{
					return $data;
				}
			}
		}

	}

	//将数组遍历并返回
	static function offstr($arr, $field, $pid=null){
		if(is_array($arr)){
			foreach ($arr as $val) {
				$html []=$val[$field];	
			}
			$pid = isset($pid) ? $html[]=intval($pid) : 0;
		}else{
			$html = intval($arr);
		}

		return isset($html) ? $html : null;
	}

	//匹配数据是否合法
	static function match($data, $val){
		if(preg_match($val, $data))
			return true;
		else
			return false;
	}

	//删除HTML标签
	static function unhtml($str) {
        return html_entity_decode($str);
        
    }

    //获取上传图片
	static function getimgbody($img, $che = 1){
		$pic = '';
		preg_match_all('/src\=\".*uploads\/(.*\.(jpg|png|gif|bmp))\"/isU', stripslashes($img), $img_array);
		$img_array = array_unique($img_array[1]);
		if(($che == 1) && !empty($img_array)){
			if(count($img_array) > 0){
				$pic = preg_replace("/[\"|'| ]{1,}/", '', $img_array[0]);
				$pic = str_replace(array('"', '\''), '', $pic);
				$pic = "uploads/".$pic;

			}
		}else if($che == 2){
			$pic = $img_array;
		}

		return $pic;
	}

	//kindeditor编译器
    static function editor($name, $content = '', $setting= 1){
        $str = '';
		$page = !isset($setting) && $name == 'content' ? ", 'pagebreak'" : '';
        $source = defined('B_PUBLIC') ? "'source', '|'," : '';
        $other = isset($_SESSION['user']) ? "allowFileManager : true, uploadJson : '".B_URL."/upload'," : "allowImageUpload: false, allowFlashUpload: false,allowMediaUpload:false,allowFileUpload:false,";
        if (!defined('ZHCMS_EDITOR_LD')) {
            $str .= '<script type="text/javascript" src="'.B_PUBLIC.'/kindeditor/kindeditor-min.js"></script>';
            define('ZHCMS_EDITOR_LD', 1);
        }
		if ($setting == 2) {
            $str .= "<script type=\"text/javascript\">
				KindEditor.ready(function(K) {
                window.editor = K.create('#" . $name . "', { 
				" . $other . "
				items:[" . $source . "'forecolor','bold', 'copy', 'underline','lineheight','|','image','|','justifyleft','justifycenter','justifyright','justifyfull','insertorderedlist','insertunorderedlist','indent','outdent','clearhtml','quickformat','hr','baidumap'" . $page . ",'|','fullscreen']
			});
        });
		</script>";
        } else if ($setting == 1) {
            $str .= "<script type=\"text/javascript\">
				KindEditor.ready(function(K) {
                window.editor = K.create('#" . $name . "', { 
				" . $other . "
				items:[" . $source . "'forecolor','bold', 'emoticons', 'copy', 'italic','underline','lineheight','|','fontname','fontsize','code','plainpaste','wordpaste','|','image','flash','media','insertfile','link','unlink','|','justifyleft','justifycenter','justifyright','justifyfull','insertorderedlist','insertunorderedlist','indent','outdent','clearhtml','quickformat','hr','baidumap'" . $page . ",'|','fullscreen']
			});
        });
		</script>";
        } else {
            $str .= "<script type=\"text/javascript\">
				KindEditor.ready(function(K) {
                window.editor = K.create('#" . $name . "', { 
				" . $other . "
				items:[" . $source . "'forecolor', 'emoticons', 'bold','italic','underline','|','image','flash','media','insertfile','link','unlink','fontname','fontsize','|','justifyleft','justifycenter','justifyright','justifyfull','clearhtml','quickformat','baidumap','|','fullscreen']
			});
        });
		</script>";
        }

        $str .= '<textarea id="' . $name . '" name="'.$name.'" style="width:' . 950 . 'px;height:' . 380 . 'px;">' . $content . '</textarea>';

        return $str;
    }

    //获取IP
	static function clientip(){
		if(getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
			$ip = getenv("HTTP_CLIENT_IP");
		else if(getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
			$ip = getenv("HTTP_X_FORWARDED_FOR");
		else if(getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
			$ip = getenv("REMOTE_ADDR");
		else if(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
			$ip = $_SERVER['REMOTE_ADDR'];
		else
			$ip = "unknown";

		return $ip;
	}

	//检测邮箱是否合法
	static function checkemail($email){
		if(preg_match("/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/", $email)){
			return true;
		}else{
			return false;
		}
	}

	//检测数据长度
	static function length($data, $length, $flag){
		if($flag == 'min'){
			if(mb_strlen(trim($data), 'utf-8') < $length) return true;
			return false;
		}else if($flag == 'max'){
			if(mb_strlen(trim($data), 'utf-8') > $length) return true;
			return false;
		}else if($falg == 'equals'){
			if(mb_strlen(trim($data), 'utf-8') != $length) return true;
			return false;
		}else{
			self::mess('参数传递错误，必须是min, max');
		}

	}

	//检测是否为空
	static function check($post){
		if(trim($post) == '') return false;
		return true;
	}

	//检测是否是数字
	static function number($post){
		$rs = "/^\d+$/";
		if(preg_match($rs, $post))
			return true;
		else{
			return false;
		}
	}

	//对上传的图片将他的值传到指定的列表里
    static function opener($_info,$_path, $style) {
		echo "<script type='text/javascript'>alert('$_info');</script>";
		echo "<script type='text/javascript'>opener.document.content.$style.value='$_path';</script>";
		echo "<script type='text/javascript'>window.close();</script>";
		exit();
	} 

	//获取数据的大小
    static function countsize($size){
        if($size >=pow(2, 40)){
            $return = round($size / pow(1024, 4), 2);
            $suffix = "TB";
        }else if($size >= pow(2, 30)){
            $return = round($size / pow(1024, 3), 2);
            $suffix = "GB";
        }else if($size >= pow(2, 20)){
            $return = round($size / pow(1024, 2), 2);
            $suffix = "MB";
        }else if($size >= pow(2, 10)){
            $return = round($size / pow(1024, 1), 2);
            $suffix = "KB";
        }else{
            $return =$size;
            $suffix ="Byte";
        }

        return $return ." " . $suffix;

    }

    //提示消息
    static function mess($mess, $type=1, $url=null){
        if($type==1){
            echo "<script>window.alert('$mess');window.history.go(-1);</script>";
            exit;
        }else if($type==2){
            echo "<script>window.alert('$mess');window.location.href='$url'</script>";
            exit;
        }
    }
    //URL转换
	static function parseurl(){
		if(isset($_SERVER['PATH_INFO'])){
			$pathinfo = explode('/', trim($_SERVER['PATH_INFO'], "/"));
			$_GET['m'] = (!empty($pathinfo[0]) ? $pathinfo[0] : "index");
			array_shift($pathinfo);

			$_GET['a'] = (!empty($pathinfo[0]) ? $pathinfo[0] : "index");
			array_shift($pathinfo);

			for($i = 0; $i<count($pathinfo); $i+=2){
				$_GET[$pathinfo[$i]] = $pathinfo[$i+1];
			}
		}else{

			$_GET['m'] = (!empty($_GET['m']) ? $_GET['m']: "index");
			$_GET['a'] = (!empty($_GET['a']) ? $_GET['a']: "index");

			if($_SERVER['QUERY_STRING']){
				$m = $_GET["m"];
				unset($_GET["m"]);
				$a = $_GET["a"];
				unset($_GET["a"]);
				$query = http_build_query($_GET);
				$url = $_SERVER["SCRIPT_NAME"]."/{$m}/{$a}/".str_replace(array("&", "="), "/", $query);
				header("Location:".$url);
			}
		}
	}

	//通过传递进来的类进行输出
	static function model($className){
		if($className){
            $src=ZH."Model/".strtolower($className)."Model.class.php";
			$className=ucfirst($className).'Model';
		}else{
			self::mess('类名不存在');
		}
		return $className;
	}

	
}

?>
