<?php
// 获取客户端IP地址
function get_client_ip(){
   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
 * @access public
 +----------------------------------------------------------
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function msubstr($str, $start=0, $length=100, $charset="utf-8", $suffix=true)
{
    if(function_exists("mb_substr")){
            if ($suffix && strlen($str)>$length)
                return mb_substr($str, $start, $length, $charset)."...";
        else
                 return mb_substr($str, $start, $length, $charset);
    }
    elseif(function_exists('iconv_substr')) {
            if ($suffix && strlen($str)>$length)
                return iconv_substr($str,$start,$length,$charset)."...";
        else
                return iconv_substr($str,$start,$length,$charset);
    }
    $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("",array_slice($match[0], $start, $length));
    if($suffix) return $slice."…";
    return $slice;
}

function IP($ip='',$file='UTFWry.dat') {
	import("@.ORG.IpLocation");
	$iplocation = new IpLocation($file);
	$location = $iplocation->getlocation($ip);
	return $location;
}


function toDate($time,$format='Y-m-d H:i:s')
{
	if( empty($time)) {
		return '';
	}
    $format = str_replace('#',':',$format);
	return date($format,$time);
}

function showTags($tags)
{
	$tags = explode(' ',$tags);
    $str = '';
    foreach($tags as $key=>$val) {
    	$tag =  trim($val);
        $str  .= ' <a href="'.__URL__.'/tag/name/'.urlencode($tag).'">'.$tag.'</a>  ';
    }
    return $str;
}
function firendlyTime($time)
{
    if(empty($time)) {
    	return '';
    }
	import('@.ORG.Date');  //日期时间操作类目录与1.5不一样
	$date	=	new Date(intval($time));
    return $date->timeDiff(time(),2);
}
function autourl($message){
      $message= preg_replace( array(
     "/(?<=[^\]a-z0-9-=\"'\\/])((https?|ftp|gopher|news|telnet|mms|rtsp):\/\/|www\.)([a-z0-9\/\-_+=.~!%@?#%&;:$\\│]+)/i",
     "/(?<=[^\]a-z0-9\/\-_.~?=:.])([_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4}))/i"
      ), array(
      "[url]\\1\\3[/url]",
      "[email]\\0[/email]"
      ), ' '.$message);
      return $message;
     }


    function getCategoryName($id)
    {
      $category = M("category");
	  $map["id"] = array("eq",$id);
	  $data = $category->where($map)->getField("name");
	  return $data;
    }
	
	
    function getAbstract($content,$id)
    {
        if(false !== $pos=strpos($content,'[separator]')) {
            $content  =  substr($content,0,$pos).'  <P> <a href="'.__URL__.'/'.$id.'"><B>阅读文章全部内容… </B></a> ';
         }
         return $content;
    }


function getTitleSize($count)
{
    $size = (ceil($count/10)+11).'px';
    return $size;
}

function getBlogTitle($id)
{
	$dao = D("Blog");
    $blog   =  $dao->getById($id);
    if($blog) {
    	return $blog['title'];
    }else {
    	return '';
    }
}

function getUserName($id){
    return '游客';
}

function getTopicTitle($id)
{
	$dao = D("Topic");
    $topic   =  $dao->getById($id);
    if($topic) {
    	return $topic->title;
    }else {
    	return '';
    }
}

function CategoryName($id)
{
   $dao = M("Category");
   $map["id"] = array("eq",$id);
   $map["del"] = array("eq",0);
   //$count  =  $dao->count(categoryId='{$categoryId}'");
   $name = $dao->where($map)->getField("name");
   return $name;
}

function rcolor() {
$rand = rand(0,255);
return sprintf("%02X","$rand");
}
function rand_color()
{
	return '#'.rcolor().rcolor().rcolor();
}


function byte_format($input, $dec=0)
{
  $prefix_arr = array("B", "K", "M", "G", "T");
  $value = round($input, $dec);
  $i=0;
  while ($value>1024)
  {
     $value /= 1024;
     $i++;
  }
  $return_str = round($value, $dec).$prefix_arr[$i];
  return $return_str;
}

//返回是否
function yes_no($id)
{
   if(!is_numeric($id))
   {
      return "请输入数字";
   }
   else
   {
      if($id == 1)
	  {
	     return "是";
	  }else{
	     return "否";
	  }
   }
}
//获取行业名称
function getIndustryName($id)
{
   $industry = M("industry");
   $name = $industry->where("id=".$id)->getField("name");
    return $name;
}
//获取荣誉名称
function getTypeName($id)
{
   $award_type = M("award_type");
   $name = $award_type->where("id=".$id)->getField("name");
    return $name;
}
//获取新闻
function getNews($Category)
{
   $news = M("news");
   $map["del"] = array("eq",0);
   $map["category"] = array("eq",$Category);
   $data = $news->where($map)->limit(5)->order("id desc")->field("title,id")->select();
   foreach($data as $value) 
   {
      echo "<li><a href=\"__APP__/index.php/Home/read/index/id/".$value["id"]."\"target=\"_self\">".msubstr($value["title"],0,10)."</a></li>";
   }
}
//获取友情链接名称
function friendship($id)
{
    $friendship_type = M("friendship_type");
	$map["del"] = array("eq",0);
	$map["id"] = array("eq",$id);
	return $friendship_type->where($map)->getfield("name");
}
//状态
function status($id)
{
  if($id == 0)
  {
    $img = "<img src='__APP__/public/images/del.gif'>";
  }else if($id == 1)
  {
    $img = "<img src='__APP__/public/images/ok.gif'>";
  }
  return $img;
}
//获取新闻的中的图片
function getImg($content)
{
  $regex = "/src=(.+?).(jpg|gif|png|bmp)/i";
  $matches = array();
if(preg_match_all($regex, $content, $matches)){
      return $matches["1"];
   }
   else
   {
     return "没有图片";
   }
}
//剥离HTML代码
function strip($content)
{
   $html = strip_tags($content,'<p><br/><a><img>');
   return $html;
}
//数据转换
 function judge($value)
	 {
	    if(isset($value) && $value == "on")
		{
		    return "1";
		}else
		{
		   return "0";
		}
	 }
//验证用户名
function checkaccount($name)
{
   $name = trim($name);
   $user = M("user");
   $map["account"] = array("eq",$name);
   $count = $user->where($map)->count();
   if($count)
   {
      echo "0";
   }
   else
   {
      return $name;
   }
}
?>