<?php
# Name: PHP版程氏音乐CMS管理系统 v3.0
# Author: 程氏<web@chshcms.com> [QQ:848769359]
# Homepage:http://www.chshcms.cn/
session_start(); 
error_reporting(E_ERROR);  
ini_set("display_errors","Off");
date_default_timezone_set('PRC');
@header("Content-type: text/html;charset=".CS_Sqlcharset."");
$CSDJCMS_URL="http://dj.chshcms.com/dj/api.php?mark=php";
define("CS_INT",0);
define("CS_TXT",1);
define('_CSDJ_PATH_', ereg_replace("[/\\]{1,}",'/',dirname(__FILE__) ));
define('_CSDJ_ROOT_', ereg_replace("[/\\]{1,}",'/',substr(_CSDJ_PATH_,0,-3) ));

//简单的防CC攻击，在3秒内连续刷新页面15次以上将指向攻击者IP
if(CS_Webmode!=3){
      $P_S_T = $t_array[0] + $t_array[1]; 
      $timestamp = time(); 

      $ll_nowtime = $timestamp ; 
      if (session_is_registered('ll_lasttime')){ 
         $ll_lasttime = $_SESSION['ll_lasttime']; 
         $ll_times = $_SESSION['ll_times'] + 1; 
         $_SESSION['ll_times'] = $ll_times; 
      }else{ 
         $ll_lasttime = $ll_nowtime; 
         $ll_times = 1; 
         $_SESSION['ll_times'] = $ll_times; 
         $_SESSION['ll_lasttime'] = $ll_lasttime; 
      } 
        if (($ll_nowtime - $ll_lasttime)<5){ 
              if ($ll_times>=25){ 
	      if(!empty($_SERVER["HTTP_CLIENT_IP"]))
	         $UIP = $_SERVER["HTTP_CLIENT_IP"];
	      else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
	         $UIP = $_SERVER["HTTP_X_FORWARDED_FOR"];
	      else if(!empty($_SERVER["REMOTE_ADDR"]))
	         $UIP = $_SERVER["REMOTE_ADDR"];
	      else
 	        $UIP = "127.0.0.1";
         header(sprintf("Location: %s",'http://'.$UIP)); 
         exit; 
        } 
      }else{ 
        $ll_times = 0; 
        $_SESSION['ll_lasttime'] = $ll_nowtime; 
        $_SESSION['ll_times'] = $ll_times; 
      } 
}

//判断是否安装
if(!file_exists(_CSDJ_ROOT_."lib/install/install.lock")){
    header("Location: ".CS_WebPath."install.php");
    exit();
}

//判断是否为空
function IsNull($str,$cid='1'){
  if($cid=='2'){
      if( is_numeric($str) ){
             return true;
      }else{
             return false;
      }
  }else{
      if (!is_string($str)) return false;
      if (empty($str)) return false;
      if ($str=='') return false;
     return true;
  }
  return false;
}

//注入拦截
function CS_Request($pi_strName, $pi_Def = "", $pi_iType = CS_TXT)
{
  if ( isset($_GET[$pi_strName]) ) 
    $t_Val = trim($_GET[$pi_strName]);
  else if ( isset($_POST[$pi_strName]))
    $t_Val = trim($_POST[$pi_strName]);
  else 
    return $pi_Def;

  // INT
  if ( CS_INT == $pi_iType)
  {
    if (is_numeric($t_Val))
      return $t_Val;
    else
      return $pi_Def;
  }
  
  // String
  $t_Val = str_replace("&", "&amp;",$t_Val); 
  $t_Val = str_replace("<", "&lt;",$t_Val);
  $t_Val = str_replace(">", "&gt;",$t_Val);
  if ( get_magic_quotes_gpc() )
  {
    $t_Val = str_replace("\\\"", "&quot;",$t_Val);
    $t_Val = str_replace("\\''", "&#039;",$t_Val);
  }
  else
  {
    $t_Val = str_replace("\"", "&quot;",$t_Val);
    $t_Val = str_replace("'", "&#039;",$t_Val);
  }
  return $t_Val;
}

//获取多项
function CS_Requestbox($key){
  $array =isset($_POST[$key]) ?$_POST[$key] : '';
  if($array==""){
 $value="0";
  }else{
  for($i=0;$i<count($array);$i++){
$value=implode(',',$array);
  }
  }
 return $value;
}

//字符替换函数
function CS_ReplaceStr($text,$search,$replace){
     if(empty($text)) $text="";
     $result_text=str_replace($search,$replace,$text);
  return $result_text;
}

//编码转换
function convert_encoding($str,$nfate,$ofate){
    if(function_exists("mb_convert_encoding")){
         $str=mb_convert_encoding($str,$nfate,$ofate);
    }else{
         if($nfate=="GBK") $nfate="GBK//IGNORE";
              $str=iconv($ofate,$nfate ,$str);
         }
   return $str;
}

//截取字符长度
function cnsubstr($str,$strlen=10) {
   if(empty($str)||!is_numeric($strlen)){
     $strlen=10;
   }
   $strlen=intval($strlen*2);
   if(strlen($str)<=$strlen){
     return $str;
   }
   $last_word_needed=substr($str,$strlen-1,1);
   if(!ord($last_word_needed)>128){
      $needed_sub_sentence=substr($str,0,$strlen);
      return $needed_sub_sentence;
   }else{
       for($i=0;$i<$strlen;$i++){
          if(ord($str[$i])>128){
              $i++;
          }
       }
     $needed_sub_sentence=substr($str,0,$i);
     return $needed_sub_sentence;
   }
}

// 得到时间的年月日
function GetTime($str){
     if(empty($str)){
         return false;
     }else{
         $strs=explode(" ",$str);
         return $strs[0];
     }
}

// 得到两时间间隔的秒数
function DateDiff($d1,$d2=""){
     if(is_string($d1)) $d1=strtotime($d1);
     if(is_string($d2)) $d2=strtotime($d2);
     return ($d2-$d1);
}

// 得到两日期之间间隔的时间  
function DateBj ($interval, $date1,$date2) { 
  $timedifference = strtotime($date2) -strtotime($date1); 
  switch ($interval) { 
      case "w": $retval = round($timedifference/604800); break; //得到两日期之间间隔的星期数；
      case "d": $retval = round($timedifference/86400); break; //得到两日期之间间隔的日数；
      case "h": $retval = round($timedifference/3600); break; //得到两日期之间间隔的小时数；
      case "n": $retval = round($timedifference/60); break; //得到两日期之间间隔的分钟数；
      case "s": $retval = $timedifference; break; //得到两日期之间间隔的秒数；
   } 
 return $retval;
} 

//标签解析
function HotSearch($Search_Key,$type="0"){
   $Search_List="";
   $Search_Key1="";
   $Search_Key=trim($Search_Key);
   $Str=" @,@|@_";
   $StrArr=explode('@',$Str);
      for($i=0;$i<=3;$i++){
         if(stristr($Search_Key,$StrArr[$i])){
               $Search_Key1=explode($StrArr[$i],$Search_Key);
         }
      }
   if(is_array($Search_Key1)){
         for($j=0;$j<count($Search_Key1);$j++){
             if(CS_Webmode==2){
                  $Search_List= $Search_List."<A HREF=\"".CS_WebPath."so-dance-key-".urlencode($Search_Key1[$j]).".html\">".$Search_Key1[$j]."</A> ";
             }else{
                  $Search_List= $Search_List."<A HREF=\"".CS_WebPath."?cs=so-dance-key-".urlencode($Search_Key1[$j]).".html\">".$Search_Key1[$j]."</A> ";
             }
         }
   }else{
      $Search_List=$Search_Key;
   }
return $Search_List;
}


//解析多个分类ID  如 cid=1,2,3,4,5,6
function getChild($CID){
        if(!empty($CID)){
             global $db;
             $ClassArr=explode(',',$CID);
                for($i=0;$i<count($ClassArr);$i++){
                    $sql="select CS_ID from ".Getdbname('class')." where CS_FID=$ClassArr[$i]";
                    $result=$db->query($sql);
                    if($result){
                        while($row=$db->fetch_array($result)){
                              $ClassArr[]=$row['CS_ID'];
                        }
                    }
                }
          $CID=implode(',',$ClassArr);
       }
return $CID;
}

/*
  文件操作函数
*/
class iFile {
    private $Fp;
    private $Pipe;
    private $File;
    private $OpenMode;
    private $Data;

 function iFile($File,$Mode = 'r',$Data4Write='',$Pipe = 'f'){
    $this ->File = $File;
    $this ->Pipe = $Pipe;
    if($Mode == 'dr'){
        $this ->OpenMode = 'r';
        $this ->OpenFile();
        $this ->getFileData();
    }else{
        $this ->OpenMode = $Mode;
        $this ->OpenFile();
    }
    if($this->OpenMode=='w'&$Data4Write!=''){
               $this ->WriteFile($Data4Write,$Mode = 3);
    }
 }

 function OpenFile(){
    if ($this ->OpenMode == 'r'||$this ->OpenMode == 'r+'){
          if($this->CheckFile()){
                if ($this ->Pipe == 'f') {
                   $this->Fp = fopen($this ->File,$this ->OpenMode);
                }elseif ($Pipe == 'p') {
                   $this->Fp = popen($this ->File,$this ->OpenMode);
                }else{
                  Die("请检查文件打开参数3,f:fopen()");
                }
          }else {
                  Die("文件访问错误,请检查文件是否存在!");
          }
     }else {
          if ($this ->Pipe == 'f') {
                    $this->Fp = fopen($this ->File,$this ->OpenMode);
          }elseif ($Pipe == 'p') {
                    $this->Fp = popen($this ->File,$this ->OpenMode);
          }else {
                 Die("请检查文件打开参数3,f:fopen()");
          }
      }
 }

 function CloseFile(){
      if ($this->Pipe == 'f'){
          @fclose($this->Fp);
      }else {
          @pclose($this->Fp);
      }
 }

 function getFileData(){
      @flock($this->Fp,1);
      $Content = fread($this->Fp,filesize($this->File));
      $this->Data = $Content;
 }

 function CheckFile(){
       if (file_exists($this ->File)) {
		    return true;
		}else {
			return false;
		}
 }

 function WriteFile($Data4Write,$Mode = 3){
       @flock($this->Fp,$Mode);
       fwrite($this->Fp,$Data4Write);
       $this->CloseFile();
  return true;
 }

}

/*
   网站缓存技术操作
*/
class Cache_Lite
{

	var $_dir  = '/cache/';
	var $_time = 60;
	var $_id;

	function __construct($options=array(NULL)){
		if(is_array($options)){
			$available_options = array('_dir','_time');
			foreach($options as $key => $value){
				if(in_array($key,$available_options)){
					$this->$key = $value;
				}
			}
		}
	}

	function get($id){
		$this->_id = md5($id.CS_CacheMark);
		if(file_exists($this->_dir.$this->_id) && ((time() - filemtime($this->_dir.$this->_id)) < $this->_time)){
			if(PHP_VERSION >= '4.3.0'){
				$data = file_get_contents($this->_dir.$this->_id);
			}else{
				$handle = fopen($this->_dir.$this->_id,'rb');
				$data = fread($handle,filesize($this->_dir.$this->_id));
				fclose($handle);
			}
			return $data;
		}else{
			return false;
		}
	}  


	function save($data){
		if(!is_writable($this->_dir)){
			if(!@mkdir($this->_dir,0777,true)){
				echo 'Cache directory not writable';
				exit;
			}
		}
		if(PHP_VERSION >= '5'){
			file_put_contents($this->_dir.$this->_id,$data);
		}else{
			$handle = fopen($this->_dir.$this->_id,'wb');
			fwrite($handle,$data);
			fclose($handle);
		}
		return true;
	}

	function start($id){
		$data = $this->get($id);
		if($data !== false && CS_IsCache==1){
			echo($data);
			return true;
		}
		ob_start();
		ob_implicit_flush(false);
		return false;
	}

	function end(){
		$data = ob_get_contents();
		ob_end_clean();
		if(CS_IsCache==1) $this->save($data);
		echo($data);
	}

}
$cache_opt = new Cache_Lite(array('_dir'=>_CSDJ_ROOT_."/".CS_Cachename."/",'_time'=>CS_CacheTime));

/*
   Mail smtp 邮件发送函数
*/
class smtp
{
  /* Public Variables */
  var $smtp_port;
  var $time_out;
  var $host_name;
  var $log_file;
  var $relay_host;
  var $debug;
  var $auth;
  var $user;
  var $pass;
  var $sender;
  var $sock;

  /* Constractor */
  function smtp($relay_host = "", $smtp_port = 25,$auth = false,$user,$pass,$sender)
  {
         $this->debug = FALSE;

         $this->smtp_port = $smtp_port;

         $this->relay_host = $relay_host;

         $this->time_out = 30; //is used in fsockopen()

         $this->auth = $auth;//auth

         $this->user = $user;

         $this->pass = $pass;

         $this->sender = $sender;

         $this->host_name = "localhost"; //is used in HELO command 

         $this->log_file = "";

         $this->logs = ""; //记录跟服务器的交互过程

         $this->sock = FALSE;
  }

  /* Main Function */
  function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "")
  {
      $sent = TRUE;
      $mail_from = $this->get_address($this->strip_comment($from));
      $body = ereg_replace("(^|(\r\n))(\.)", "\1.\3", $body);
      $header .= "MIME-Version:1.0\r\n";
           if($mailtype=="HTML"){
               $header .= "Content-Type:text/html\r\n";
           }
               $header .= "To: ".$to."\r\n";
           if ($cc != "") {
               $header .= "Cc: ".$cc."\r\n";
           }
               $header .= "From: ".$from."\r\n";
               $header .= "Subject: ".$subject."\r\n";
               $header .= $additional_headers;
               $header .= "Date: ".date("r")."\r\n";
               $header .= "X-Mailer: 72e.net (PHP/".phpversion().")\r\n";
               list($msec, $sec) = explode(" ", microtime());
               $header .= "Message-ID: <".date("YmdHis", $sec).".".($msec*1000000).".".$mail_from.">\r\n";
               $TO = explode(",", $this->strip_comment($to));
           if ($cc != "") {
               $TO = array_merge($TO, explode(",", $this->strip_comment($cc)));
           }
           if ($bcc != "") {
               $TO = array_merge($TO, explode(",", $this->strip_comment($bcc)));
           }
           foreach ($TO as $rcpt_to) {
               $rcpt_to = $this->get_address($rcpt_to);
               if (!$this->smtp_sockopen($rcpt_to)) {
                      $this->log_write("Error: Cannot send email to ".$rcpt_to."\n");
                      $sent = FALSE;
                       continue;
               }
               if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $header, $body)) {
                       $this->log_write("E-mail has been sent to <".$rcpt_to.">\n");
               } else {
                       $this->log_write("Error: Cannot send email to <".$rcpt_to.">\n");
                       $sent = FALSE;
               }
               fclose($this->sock);
               $this->log_write("Disconnected from remote host\n");
           }
    return $sent;
  }

  function smtp_send($helo, $from, $to, $header, $body = "")
  {
        if (!$this->smtp_putcmd("HELO", $helo)) {
            return $this->smtp_error("sending HELO command");
        }
        if($this->auth){
              if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {
                  return $this->smtp_error("sending AUTH command");
              }
                      if (!$this->smtp_putcmd("", base64_encode($this->pass))) {
                           return $this->smtp_error("sending AUTH command");
                      }
         }
         if (!$this->smtp_putcmd("MAIL", "FROM:<".$this->sender.">")) {
              return $this->smtp_error("sending MAIL FROM command");
         }
         if (!$this->smtp_putcmd("RCPT", "TO:<".$to.">")) {
              return $this->smtp_error("sending RCPT TO command");
         }
         if (!$this->smtp_putcmd("DATA")) {
              return $this->smtp_error("sending DATA command");
         }
         if (!$this->smtp_message($header, $body)) {
              return $this->smtp_error("sending message");
         }
         if (!$this->smtp_eom()) {
              return $this->smtp_error("sending <CR><LF>.<CR><LF> [EOM]");
         }
         if (!$this->smtp_putcmd("QUIT")) {
              return $this->smtp_error("sending QUIT command");
         }
    return TRUE;
  }

  function smtp_sockopen($address)
  {
      if ($this->relay_host == "") {
           return $this->smtp_sockopen_mx($address);
      } else {
           return $this->smtp_sockopen_relay();
     }
  }

  function smtp_sockopen_relay()
  {
      $this->log_write("Trying to ".$this->relay_host.":".$this->smtp_port."\n");
      $this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out);
      if (!($this->sock && $this->smtp_ok())) {
           $this->log_write("Error: Cannot connenct to relay host ".$this->relay_host."\n");
            $this->log_write("Error: ".$errstr." (".$errno.")\n");
         return FALSE;
      }
      $this->log_write("Connected to relay host ".$this->relay_host."\n");
     return TRUE;
  }

  function smtp_sockopen_mx($address)
  {
      $domain = ereg_replace("^.+@([^@]+)$", "\1", $address);
      if (!@getmxrr($domain, $MXHOSTS)) {
           $this->log_write("Error: Cannot resolve MX \"".$domain."\"\n");
         return FALSE;
      }
        foreach ($MXHOSTS as $host) {
        $this->log_write("Trying to ".$host.":".$this->smtp_port."\n");
        $this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);
           if (!($this->sock && $this->smtp_ok())) {
             $this->log_write("Warning: Cannot connect to mx host ".$host."\n");
             $this->log_write("Error: ".$errstr." (".$errno.")\n");
             continue;
           }
            $this->log_write("Connected to mx host ".$host."\n");
           return TRUE;
        }
        $this->log_write("Error: Cannot connect to any mx hosts (".implode(", ", $MXHOSTS).")\n");
  return FALSE;
 }

  function smtp_message($header, $body)
  {
      fputs($this->sock, $header."\r\n".$body);
      $this->smtp_debug("> ".str_replace("\r\n", "\n"."> ", $header."\n> ".$body."\n> "));
    return TRUE;
  }

  function smtp_eom()
  {
      fputs($this->sock, "\r\n.\r\n");
      $this->smtp_debug(". [EOM]\n");
    return $this->smtp_ok();
  }

  function smtp_ok()
  {
       $response = str_replace("\r\n", "", fgets($this->sock, 512));
       $this->smtp_debug($response."\n");
       if (!ereg("^[23]", $response)) {
           fputs($this->sock, "QUIT\r\n");
           fgets($this->sock, 512);
            $this->log_write("Error: Remote host returned \"".$response."\"\n");
          return FALSE;
       }
   return TRUE;
  }

  function smtp_putcmd($cmd, $arg = "")
  {
     if ($arg != "") {
          if($cmd=="") $cmd = $arg;
          else $cmd = $cmd." ".$arg;
     }
    fputs($this->sock, $cmd."\r\n");
    $this->smtp_debug("> ".$cmd."\n");
   return $this->smtp_ok();
  }

  function smtp_error($string)
  {
      $this->log_write("Error: Error occurred while ".$string.".\n");
   return FALSE;
  }

  function log_write($message)
  {
       $this->logs .= $message;
       $this->smtp_debug($message);
       if ($this->log_file == "") {
         return TRUE;
       }
       $message = date("M d H:i:s ").get_current_user()."[".getmypid()."]: ".$message;
       if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, "a"))) {
            $this->smtp_debug("Warning: Cannot open log file \"".$this->log_file."\"\n");
        return FALSE;
       }
       flock($fp, LOCK_EX);
       fputs($fp, $message);
       fclose($fp);
    return TRUE;
  }

  function strip_comment($address)
  {
     $comment = "\([^()]*\)";
     while (ereg($comment, $address)) {
         $address = ereg_replace($comment, "", $address);
    }
     return $address;
  }

  function get_address($address)
  {
      $address = ereg_replace("([ \t\r\n])+", "", $address);
      $address = ereg_replace("^.*<(.+)>.*$", "\1", $address);
    return $address;
  }

  function smtp_debug($message)
  {
    if ($this->debug) {
        echo $message;
    }
  }
} // end class smtp
  $smtp =   new smtp(CS_Mailsmtp,'25',true,CS_Mailuser,CS_Mailpass,CS_Mailname); 

//escape函数
function escape($str){
  preg_match_all("/[\x80-\xff].|[\x01-\x7f]+/",$str,$r);
  $ar=$r[0];
  foreach($ar as $k=>$v){
       if(ord($v[0]) <128){
           $ar[$k] = rawurlencode($v);
       }else{
           $ar[$k] = "%u".bin2hex(iconv("GBK","UCS-2",$v));
       }
  }
 return join("",$ar);
}

//获取图片信息
function piclink($Table='pic',$Url) {
	if(substr($Url,0,7)=="http://"){
             $picurl=$Url;
	}elseif(empty($Url)){
             $picurl="http://".CS_WebUrl.CS_WebPath."public/images/nopic.gif";
	}else{
             if($Table=='logo'){     
                  $picurl="http://".CS_WebUrl.CS_WebPath."annex/logo/big/".$Url."";
             }elseif($Table=='pic'){     
                  $picurl="http://".CS_WebUrl.CS_WebPath."annex/pic/".$Url."";
             }elseif($Table=='dance'){     
                  $picurl=CS_WebPath."annex/dance/".$Url."";
             }elseif($Table=='news'){     
                  $picurl=CS_WebPath."annex/news/".$Url."";
             }elseif($Table=='topic'){     
                  $picurl="http://".CS_WebUrl.CS_WebPath."annex/topic/".$Url."";
             }
	}
  return $picurl;
}

//会员相关连接
function userlink($Classid,$Uid,$ID=0,$Pages=1){
  if(CS_Usermode==0){ //伪静态开启
       if(CS_Uymmode==0){ //二级域名开启
              if($Classid=='index'){
                       $userlink="http://".$Uid.".".CS_Uymurl."";
              }elseif($Classid=='pick'||$Classid=='picx'||$Classid=='tdance'){
                       $userlink="http://".$Uid.".".CS_Uymurl."/".$Classid."-".$ID.".html";
              }else{
                       $userlink="http://".$Uid.".".CS_Uymurl."/".$Classid."-".$Pages.".html";
              }
       }else{
              if($Classid=='index'){
                       $userlink="http://".CS_WebUrl.CS_WebPath."home/".$Uid.".html";
              }elseif($Classid=='pick'||$Classid=='picx'||$Classid=='tdance'){
                       $userlink="http://".CS_WebUrl.CS_WebPath."home/".$Classid."-".$Uid."-".$ID.".html";
              }else{
                       $userlink="http://".CS_WebUrl.CS_WebPath."home/".$Classid."-".$Uid."-".$Pages.".html";
              }
       }
  }else{
       if(CS_Uymmode==0){ 
              if($Classid=='index'){
                       $userlink="http://".$Uid.".".CS_Uymurl."";
              }elseif($Classid=='pick'||$Classid=='picx'||$Classid=='tdance'){
                       $userlink="http://".$Uid.".".CS_Uymurl."/?op=".$Classid."&id=".$ID;
              }else{
                       $userlink="http://".$Uid.".".CS_Uymurl."/?op=".$Classid."&pages=".$Pages;
              }
       }else{
              if($Classid=='index'){
                       $userlink="http://".CS_WebUrl.CS_WebPath."home/?uid=".$Uid;
              }elseif($Classid=='pick'||$Classid=='picx'||$Classid=='tdance'){
                       $userlink="http://".CS_WebUrl.CS_WebPath."home/?op=".$Classid."&uid=".$Uid."&id=".$ID;
              }else{
                       $userlink="http://".CS_WebUrl.CS_WebPath."home/?op=".$Classid."&uid=".$Uid."&pages=".$Pages;
              }
       }
  }
 return $userlink;
}


/*
   网站动态连接  
	  type   =   类型   list为分类 ，show为内容，play为播放
	  fid    =   栏目   dance为舞曲 ，news为文章，zj为专集
          sort   =   排序   id为默认，new为更新时间，hits为总人气，yue月人气，zhou周人气，ri日人气，fav收藏人气，down下载人气，ding被顶人气，reco推荐星际，play正在播放
	  cid    =   分类ID
	  id     =   数据ID
	  pid    =   分页ID
          
          地址连接参数                (?m=type-fid-sort-id-pid.html)    http://127.0.0.1/?m=list-dance-id-1-1.html
*/

function LinkUrl($type,$fid,$sort='id',$cid=1,$id=1,$pid=1){

      if($type=='so'){
         if(CS_Webmode==2){
            $linkurl=CS_WebPath.$type."-".$fid."-".$sort."-".$cid."-".$pid.".html";
         }else{
            $linkurl=CS_WebPath."?cs=".$type."-".$fid."-".$sort."-".$cid."-".$pid.".html";
         }
            return $linkurl;
            exit();
      }
      switch(CS_Webmode){

         case '1':  //动态模式

               if($type=="list"){  //分类
                   if($fid=="zj"){
                      $linkurl=CS_WebPath."?cs=".$type."-".$fid."-".$sort."-".$pid.".html";
                   }else{
                      $linkurl=CS_WebPath."?cs=".$type."-".$fid."-".$sort."-".$cid."-".$pid.".html";
                   }
               }else{  //内容，播放
                   if($fid=="zj"){
                      $linkurl=CS_WebPath."?cs=".$type."-".$fid."-".$sort."-".$id."-".$pid.".html";
                   }else{
                      $linkurl=CS_WebPath."?cs=".$type."-".$fid."-".$sort."-".$id.".html";
                   }
               }

         break;
         case '2':  //伪静态模式

               if($type=="list"){  //分类
                   if($fid=="zj"){
                      $linkurl=CS_WebPath.$type."-".$fid."-".$sort."-".$pid.".html";
                   }else{
                      $linkurl=CS_WebPath.$type."-".$fid."-".$sort."-".$cid."-".$pid.".html";
                   }
               }else{  //内容，播放
                   if($fid=="zj"){
                      $linkurl=CS_WebPath.$type."-".$fid."-".$sort."-".$id."-".$pid.".html";
                   }else{
                      $linkurl=CS_WebPath.$type."-".$fid."-".$sort."-".$id.".html";
                   }
               }

         break;
         case '3':  //静态模式

		      if(CS_Mark==0){ ///////////ID排序

                                    if($type=="list"){  //分类

					   if($fid=="dance"){       //舞曲列表
                                                     $linkurl=CS_WebPath.CS_Dname."/".$sort."-".$cid."-".$pid.".".CS_Suffix;
					   }elseif($fid=="news"){   //文章列表
                                                     $linkurl=CS_WebPath.CS_Nname."/".$sort."-".$cid."-".$pid.".".CS_Suffix;
					   }elseif($fid=="zj"){     //专集列表
                                                     $linkurl=CS_WebPath.CS_Tname."/".$sort."-".$pid.".".CS_Suffix;
					   } 

                                    }else{     //内容，播放

					   if($fid=="dance"){       //舞曲
                                                      $linkurl=CS_WebPath.CS_Dname."/".$fid."-".$id.".".CS_Suffix;
					   }elseif($fid=="news"){   //文章
                                                      $linkurl=CS_WebPath.CS_Nname."/".$fid."-".$id.".".CS_Suffix;
					   }elseif($fid=="zj"){     //专集
                                                      $linkurl=CS_WebPath.CS_Tname."/".$fid."-".$sort."-".$id."-".$pid.".".CS_Suffix;
                                           }
                                    }

		      }elseif(CS_Mark==1){ ///////////ID目录

                                    if($type=="list"){  //分类

					   if($fid=="dance"){       //舞曲列表
                                                     $linkurl=CS_WebPath.CS_Dname."/".$cid."/".$sort."/".$pid."/";
					   }elseif($fid=="news"){   //文章列表
                                                     $linkurl=CS_WebPath.CS_Nname."/".$cid."/".$sort."/".$pid."/";
					   }elseif($fid=="zj"){     //专集列表
                                                     $linkurl=CS_WebPath.CS_Tname."/".$sort."/".$pid."/";
					   } 

                                    }else{     //内容，播放

					   if($fid=="dance"){       //舞曲
                                                      $linkurl=CS_WebPath.CS_Dname."/".$id."/";
					   }elseif($fid=="news"){   //文章
                                                      $linkurl=CS_WebPath.CS_Nname."/".$id."/";
					   }elseif($fid=="zj"){     //专集
                                                      $linkurl=CS_WebPath.CS_Tname."/".$id."/".$sort."/".$pid."/";
                                           }
                                    }

		      }elseif(CS_Mark==2){ ////////别名目录

				   IF($fid=="zj"){  //专集别名
				        $AliasName=GetAlias("topic",$id);
				   }Else{
					$AliasName=GetAlias("class",$cid);
				   }


                                    if($type=="list"){  //分类

					   if($fid=="dance"){       //舞曲列表
                                                     $linkurl=CS_WebPath.CS_Dname."/".$AliasName."/".$sort."/".$pid."/";
					   }elseif($fid=="news"){   //文章列表
                                                     $linkurl=CS_WebPath.CS_Nname."/".$AliasName."/".$sort."/".$pid."/";
					   }elseif($fid=="zj"){     //专集列表
                                                     $linkurl=CS_WebPath.CS_Tname."/".$sort."/".$pid."/";
					   } 

                                    }else{     //内容，播放

					   if($fid=="dance"){       //舞曲播放
                                                      $linkurl=CS_WebPath.CS_Dname."/".$AliasName."/".$id."/";
					   }elseif($fid=="news"){   //文章内容
                                                      $linkurl=CS_WebPath.CS_Nname."/".$AliasName."/".$id."/";
					   }elseif($fid=="zj"){     //专集内容
                                                      $linkurl=CS_WebPath.CS_Tname."/".$AliasName."/".$sort."/".$pid."/";
                                           }
                                    }


		      }elseif(CS_Mark==3){ ////////日期目录


                                    if($type=="list"){  //分类

					   if($fid=="dance"){       //舞曲列表
                                                     $linkurl=CS_WebPath.CS_Dname."/".$sort."/".$pid."/";
					   }elseif($fid=="news"){   //文章列表
                                                     $linkurl=CS_WebPath.CS_Nname."/".$sort."/".$pid."/";
					   }elseif($fid=="zj"){     //专集列表
                                                     $linkurl=CS_WebPath.CS_Tname."/".$sort."/".$pid."/";
					   } 

                                    }else{     //内容，播放

					   if($fid=="dance"){       //舞曲
                                                      $linkurl=CS_WebPath.CS_Dname."/".GetData('topic',$id)."/".$id."/";
					   }elseif($fid=="news"){   //文章
                                                      $linkurl=CS_WebPath.CS_Nname."/".GetData('news',$id)."/".$id."/";
					   }elseif($fid=="zj"){     //专集
                                                      $linkurl=CS_WebPath.CS_Tname."/".GetData('dance',$id)."/".$sort."/".$pid."/";
                                           }
                                    }
                      }

         break;
      }
  return $linkurl;

}
//删除目录 
class del_path { 
     function wm_chief_delpath($del_path) { 
           if(!file_exists($del_path))//目标目录不存在则建立 
           {
               echo"目录不存在";
               return false;
           } 
           $hand=opendir($del_path); 
           $i=0; 
           while($file=readdir($hand)) 
           {$i ; 
           if($i==1||$i==2) 
           {continue;} 
           if(!(strchr($file,"."))) 
           { 
           $del_s_path=$del_path."/".$file; 
           $this->wm_chief_delpath($del_s_path); 
           } 
           else 
           { 
           $del_file=$del_path."/".$file; 
           $this->wm_chief_file($del_file); 
           } 
           } 
           closedir($hand); 
           $this->wm_chief_path($del_path); 
           return true; 
           } 
           //删除文件 
           function wm_chief_file($del_file) 
           { 
              @unlink($del_file); 
           } 
           //删除目录 
           function wm_chief_path($del_path) 
           { 
             @rmdir($del_path); 
           } 
} 

//判断是否生成
function HtmlShow($id,$url,$html){
   $SpanShow="&nbsp;&nbsp;<img src='../res/images/html.gif' style='cursor:hand' id='html_".$id."' onclick='Htmlgo(".$id.",\"".$url."\")'>";
   $spanurl=substr($html,strlen(CS_WebPath));
   if(file_exists("../../".$spanurl)){
         $SpanShow="";
   }
  return $SpanShow;
}

//获取分页数目	
function getpagenum($Mark_Text){
	preg_match('/\{csdjcms:(pagenum)\s*([a-zA-Z=]*)\s*([\d]*)\}/',$Mark_Text,$pagearr);
	if(!empty($pagearr)){
		if(trim($pagearr[3])!=""){
			$pagenum=$pagearr[3];
		}else{
			$pagenum=10;
		}	
	}else{
		$pagenum=10;
	}
	unset($pagearr);
 return $pagenum;
}

//获取英文别名
function GetAlias($Table,$CID){
   global $db;
   $row=$db->getrow("select CS_AliasName from ".Getdbname($Table)." where CS_ID=".$CID."");
   if($row){
         $aliasname=$row['CS_AliasName'];
   }else{
         $aliasname="unknow";
   }
 return $aliasname;
}

//获取日期目录
function GetData($Table,$CID){
   global $db;
   $row=$db->getrow("select CS_AddTime from ".Getdbname($Table)." where CS_ID=".$CID."");
   if($row){
         $CS_Data=explode(" ",$row['CS_AddTime']);
         $CS_Data=CS_ReplaceStr($CS_Data[0],"-","");
   }else{
         $CS_Data=date('Ymd');
   }
 return $CS_Data;
}

//获取下载权限
function Downqx($vip){
   if($vip==1){
         $qx='普通会员';
   }elseif($vip==2){
         $qx='VIP会员';
   }else{
         $qx='游客下载';
   }
 return $aliasname;
}

//获取数据库表全名
function Getdbname($Table){
    $Table=CS_SqlPrefix.$Table;
 return $Table;
}

//威客网盘
function getvdisk($url){
     $dyurls = "http://dj.chshcms.com/vdisk.php/".$url."/chshcms.mp3";
  return $dyurls;
}

//飞速网盘
function getrayfile($url){
        $CHshdjcms_a=explode('http://www.rayfile.com/files/',$url);
        $CHshdjcms_a=$CHshdjcms_a[1];
        $CHshdjcms_b=explode('/',$CHshdjcms_a);
        $CHshdjcms_c=$CHshdjcms_b[0];
        $rayfileurl="http://dj.chshcms.com/rayfile.php/".$CHshdjcms_c."/csdj.mp3";
return $rayfileurl;
}

//官方网盘
function getcsdj($user,$id,$type='mp3.php'){
        $csdjurl="http://up.chshcms.com/".$type."/".$user."/".$id."/csdj.mp3";
return $csdjurl;
}

//获取远程文件内容
function geturl($url){
     if(function_exists('curl_init')){
         $ch = curl_init();
         $timeout = 30;
         curl_setopt ($ch,CURLOPT_URL,$url);
         curl_setopt ($ch,CURLOPT_RETURNTRANSFER,1);
         curl_setopt ($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
         $handles = curl_exec($ch);
         curl_close($ch);
      }else{
         $handles = @file_get_contents($url);
      }
  return $handles;
}

//获取舞曲属性
function DjData($type,$File) {
   if(PHP_OS=="WINNT"){

       $player= new COM("WMPlayer.OCX");
       $media = $player->newMedia($File);
       $time = $media->duration; //获取持续时间
       $s_bitrate = $media->getItemInfo(Bitrate); //获取位速
       $size=$media->getItemInfo(FileSize);//大小 
       $time = sprintf("%01.0f", $time);
       $s_duration = strftime("%H:%M:%S",$time-28800);
       $s_bitrate = str_replace(substr($s_bitrate,-3),"",$s_bitrate)." Kbps";
       $s_size=formatsize($size);
       if($type=="sj"){
	   return $s_duration;
       }elseif($type=="yz"){
	   return $s_bitrate;
       }else{
	   return $s_size;
       }
   }else{
      return '未知';
   }
}

//大小转换
function formatsize($size) {
	$prec=3;
	$size = round(abs($size));
	$units = array(0=>" B ", 1=>" KB", 2=>" MB", 3=>" GB", 4=>" TB");
	if ($size==0) return str_repeat(" ", $prec)."0$units[0]";
	$unit = min(4, floor(log($size)/log(2)/10));
	$size = $size * pow(2, -10*$unit);
	$digi = $prec - 1 - floor(log($size)/log(10));
	$size = round($size * pow(10, $digi)) * pow(10, -$digi);
	return $size.$units[$unit];
}

//时间格式转换
function datetime($TimeTime){
    $limit=time()-strtotime($TimeTime);
    if ($limit <5) {$show_t = "刚刚";}
    if ($limit >= 5 and $limit <60) {$show_t = $limit."秒前";}
    if ($limit >= 60 and $limit <3600) {$show_t = sprintf("%01.0f",$limit/60)."分钟前";}
    if ($limit >= 3600 and $limit <86400) {$show_t = sprintf("%01.0f",$limit/3600)."小时前";}
    if ($limit >= 86400 and $limit <2592000) {$show_t = sprintf("%01.0f",$limit/86400)."天前";}
    if ($limit >= 2592000 and $limit <31104000) {$show_t = sprintf("%01.0f",$limit/2592000)."个月前";}
    if ($limit >= 31104000) {$show_t = $TimeTime;}
  return $show_t;
}

//加入版权
function csdjcopyright($Mark_Text){
        $temp = explode("<head>", $Mark_Text, 2);   
        $content= explode("</head>", $temp[1], 2); 
        $Mark_Text='<head>'.$content[0].'    <meta name="generator" content="CsDjcms v3.0" />
    <meta name="author" content="CsDjcms Team and Chshcms UI Team" />
    <meta name="copyright" content="2009-2013 Chshcms.com Inc." />
    <link href="'.CS_WebPath.'public/css/webox.css" rel="stylesheet" type="text/css">
    <script src="'.CS_WebPath.'public/js/jquery.js"></script>
    <script src="'.CS_WebPath.'public/js/webox.js"></script>
</head>';
        $Mark_Text=$temp[0].$Mark_Text.$content[1];
     return $Mark_Text;
}

//长度控制
function getlen($para='',$val='',$res=''){//控制符号：如len ,控制内容值 如:5，控制的记录:name
	if(!empty($para) && !empty($val)){
		if(is_numeric($val)){
			$cont=cnsubstr($res,intval($val));
		}else{
			$cont=$res;
			}
	}else{
		$cont=$res;
		}
	return $cont;	
}

//获取会员信息
function getuser($Uid,$Name){
	global $db;
        $sql="select * from ".Getdbname('user')." where CS_Name='".$Name."'";
	$row=$db->getRow($sql);
	if($row){
		if($Uid=='pic'){
			$rec=piclink('logo',$row['CS_Logo']);
		}elseif($Uid=='qq'){
                        $rec=$row['CS_QQ'];
		}elseif($Uid=='uid'){
			$rec=$row['CS_ID'];
		}elseif($Uid=='email'){
			$rec=$row['CS_Email'];
		}elseif($Uid=='city'){
			$rec=$row['CS_City'];
		}elseif($Uid=='nichen'){
			$rec=$row['CS_Nichen'];
		}elseif($Uid=='vip'){
		    if($row['CS_Vip']==2){
			$rec="黄冠会员";
		    }elseif($row['CS_Vip']==1){
			$rec="VIP会员";
		    }else{
			$rec="普通会员";
		    }
		}elseif($Uid=='sex'){
		    if($row['CS_Sex']==1){
			$rec="男";
		    }else{
			$rec="女";
		    }
		}
               if($rec){
		return $rec;	
               }else{
		return "未知";	
               }
	}else{
		return "未知";	
	}		
}

//获取会员分类数目
function getusercount($name='',$type){
	global $db;
	$sql="select count(CS_ID) as rc from ".Getdbname($type)."  where CS_User='".$name."'";
	$row=$db->getRow($sql);
	if($row){
		return $row['rc'];
	}else{
		return "0";
	}
}

//获取标签数据总数
function gettagscount($tags='',$type){
	global $db;
	$sql="select count(CS_ID) as rc from ".Getdbname($type)."  where CS_Tags='".$tags."'";
	$row=$db->getRow($sql);
	if($row){
		return $row['rc'];
	}else{
		return "0";
	}
}

//获取分类名称		
function getclass($id){
	global $db;
        $sql="select CS_Name from ".Getdbname('class')." where CS_ID=".$id."";
	$row=$db->getRow($sql);
	if($row){
		return $row['CS_Name'];
	}else{
		return "未知分类";	
	}		
}

//获取舞曲视听全部地址
function playurl($Url,$Fid){
             global $db;
             if($Fid==0){
                 return $Url;
	     }else{
                 $row=$db->getrow("Select * from Getdbname('fwqip') where CS_ID=".$Fid."");
                 if($row){
                       $Url=$row['CS_Playip'].$Url;
                       return $Url;
	         }else{
                      return $Url;
	         }
	     }
}

//获取分类舞曲数目
function getclasscount($id='',$type='1',$tid=0){
	global $db;
	if($type=='1'){
		$sql="select count(CS_ID) as rc from ".Getdbname('dance')." where CS_CID=$id";
	}else{
		$sql="select count(CS_ID) as rc from ".Getdbname('news')." where CS_CID=$id";
	}

        if($tid==1) $sql.=" and DATEDIFF(DATE(CS_AddTime),'".date('Y-m-d')."')=0";  //获取今日更新

	$row=$db->getRow($sql);
	if($row){
		return $row['rc'];
	}else{
		return "获取失败";
	}
}

//获取相册参数
function getpic($classid='url',$ID){
	global $db;
	$row=$db->getRow("select count(CS_ID) as rc from ".Getdbname('photo')." where CS_CID=".$ID."");
	if($classid=='count'){
                 if($row){
                       $rec=$row['rc'];
                 }else{
                       $rec=0;
                 }
	}else{
             if($row['rc']>0){
		$row=$db->fetch_array($db->query("select * from ".Getdbname('photo')." where CS_CID=".$ID." and CS_YID=0 order by CS_ID asc limit 1"));
                 if($row['CS_Url']){
                       $rec=piclink('pic',$row['CS_Url']);
                 }else{
                       $rec="http://".CS_WebUrl.CS_WebPath."public/images/nopic.gif";
                 }
             }else{
                       $rec="http://".CS_WebUrl.CS_WebPath."public/images/nopic.gif";
             }
	}
	return $rec;
}

//表情转换
function facehtml($str)  
 {  
 if (empty($str)) return false;  
 $str = htmlspecialchars($str); 
 $str = str_replace( '[em:1]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/1.gif border=0>", $str); 
 $str = str_replace( '[em:2]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/2.gif border=0>", $str); 
 $str = str_replace( '[em:3]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/3.gif border=0>", $str); 
 $str = str_replace( '[em:4]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/4.gif border=0>", $str); 
 $str = str_replace( '[em:5]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/5.gif border=0>", $str); 
 $str = str_replace( '[em:6]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/6.gif border=0>", $str); 
 $str = str_replace( '[em:7]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/7.gif border=0>", $str); 
 $str = str_replace( '[em:8]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/8.gif border=0>", $str); 
 $str = str_replace( '[em:9]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/9.gif border=0>", $str); 
 $str = str_replace( '[em:10]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/10.gif border=0>", $str); 
 $str = str_replace( '[em:11]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/11.gif border=0>", $str); 
 $str = str_replace( '[em:12]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/12.gif border=0>", $str); 
 $str = str_replace( '[em:13]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/13.gif border=0>", $str); 
 $str = str_replace( '[em:14]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/14.gif border=0>", $str); 
 $str = str_replace( '[em:15]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/15.gif border=0>", $str); 
 $str = str_replace( '[em:16]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/16.gif border=0>", $str); 
 $str = str_replace( '[em:17]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/17.gif border=0>", $str); 
 $str = str_replace( '[em:18]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/18.gif border=0>", $str); 
 $str = str_replace( '[em:19]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/19.gif border=0>", $str); 
 $str = str_replace( '[em:20]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/20.gif border=0>", $str); 
 $str = str_replace( '[em:21]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/21.gif border=0>", $str); 
 $str = str_replace( '[em:22]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/22.gif border=0>", $str); 
 $str = str_replace( '[em:23]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/23.gif border=0>", $str); 
 $str = str_replace( '[em:24]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/24.gif border=0>", $str); 
 $str = str_replace( '[em:25]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/25.gif border=0>", $str); 
 $str = str_replace( '[em:26]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/26.gif border=0>", $str); 
 $str = str_replace( '[em:27]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/27.gif border=0>", $str); 
 $str = str_replace( '[em:28]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/28.gif border=0>", $str); 
 $str = str_replace( '[em:29]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/29.gif border=0>", $str); 
 $str = str_replace( '[em:30]', "<img src=http://".CS_WebUrl.CS_WebPath."public/faces/30.gif border=0>", $str); 
 return $str;  
 }  

//输出安全的html
function h($text, $tags = null){
	$text	=stripslashes(html_entity_decode($text));
	$text	=	trim($text);
	//完全过滤注释
	$text	=	preg_replace('/<!--?.*-->/','',$text);
	//完全过滤动态代码
	$text	=	preg_replace('/<\?|\?'.'>/','',$text);
	//完全过滤js
	$text	=	preg_replace('/<script?.*\/script>/','',$text);

	$text	=	str_replace('[','&#091;',$text);
	$text	=	str_replace(']','&#093;',$text);
	$text	=	str_replace('|','&#124;',$text);
	//过滤换行符
	$text	=	preg_replace('/\r?\n/','',$text);
	//br
	$text	=	preg_replace('/<br(\s\/)?'.'>/i','[br]',$text);
	$text	=	preg_replace('/(\[br\]\s*){10,}/i','[br]',$text);
	//过滤危险的属性，如：过滤on事件lang js
	while(preg_match('/(<[^><]+)( lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i',$text,$mat)){
		$text=str_replace($mat[0],$mat[1],$text);
	}
	while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){
		$text=str_replace($mat[0],$mat[1].$mat[3],$text);
	}
	if(empty($tags)) {
		$tags = 'table|td|th|tr|i|b|u|strong|img|p|br|div|strong|em|ul|ol|li|dl|dd|dt|a';
	}
	//允许的HTML标签
	$text	=	preg_replace('/<('.$tags.')( [^><\[\]]*)>/i','[\1\2]',$text);
	//过滤多余html
	$text	=	preg_replace('/<\/?(html|head|meta|link|base|basefont|body|bgsound|title|style|script|form|iframe|frame|frameset|applet|id|ilayer|layer|name|script|style|xml)[^><]*>/i','',$text);
	//过滤合法的html标签
	while(preg_match('/<([a-z]+)[^><\[\]]*>[^><]*<\/\1>/i',$text,$mat)){
		$text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text);
	}
	//转换引号
	while(preg_match('/(\[[^\[\]]*=\s*)(\"|\')([^\2=\[\]]+)\2([^\[\]]*\])/i',$text,$mat)){
		$text=str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text);
	}
	//过滤错误的单个引号
	while(preg_match('/\[[^\[\]]*(\"|\')[^\[\]]*\]/i',$text,$mat)){
		$text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
	}
	//转换其它所有不合法的 < >
	$text	=	str_replace('<','&lt;',$text);
	$text	=	str_replace('>','&gt;',$text);
	$text	=	str_replace('"','&quot;',$text);
	 //反转换
	$text	=	str_replace('[','<',$text);
	$text	=	str_replace(']','>',$text);
	$text	=	str_replace('|','"',$text);
	$text	=	str_replace('&#091;','[',$text);
	$text	=	str_replace('&#093;',']',$text);
	$text	=	str_replace('&#124;','|',$text);
	//过滤多余空格
	$text	=	str_replace('  ',' ',$text);
	return $text;
}

//获取最新版本
function getXmlVersion($url='http://www.chshcms.cn/vip/version.xml'){
	$doc = new DOMDocument();
	$cc=$doc->load($url);
	$ver = $doc->getElementsByTagName("csdjcms");	
	foreach( $ver as $v )
	{
		$ver = $v->getElementsByTagName( "version" );
		if(function_exists("mb_convert_encoding")){
			$version =  mb_convert_encoding($ver->item(0)->nodeValue,"GBK","UTF-8");  
			}
		else{
			$version = iconv( "UTF-8",  "GBK//IGNORE" , $ver->item(0)->nodeValue);
			}
	}
	return $version;
}

//获取需要升级文件
function getupgrade($url='http://www.chshcms.cn/vip/up.xml'){
	$doc = new DOMDocument();
	$cc=$doc->load($url);
	$ver = $doc->getElementsByTagName("upgrade");	
	foreach( $ver as $v )
	{
		$ver = $v->getElementsByTagName( "up" );
		if(function_exists("mb_convert_encoding")){
			$Filename =  mb_convert_encoding($ver->item(0)->nodeValue,"GBK","UTF-8");  
			}
		else{
			$Filename = iconv( "UTF-8",  "GBK//IGNORE" , $ver->item(0)->nodeValue);
			}
	}
	return $Filename;
}


//获取需要升级文件内容
function getupdata($filename){
        $url="http://vip.chshcms.com/".$filename;
        $FileContent=@file_get_contents($url);
        if(!$FileContent){
           $ch = curl_init($url);
           curl_setopt($ch, CURLOPT_TIMEOUT, 1);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
           $FileContent = curl_exec($ch);
           curl_close ($ch);
        }
    return $FileContent;
}

//判断远程文件是否存在  
function remote_file_exists($url) {
	$curl = curl_init($url); // 不取回数据
	curl_setopt($curl, CURLOPT_NOBODY, true);
	curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); // 发送请求
	$result = curl_exec($curl);
	$found = false; // 如果请求没有发送失败
	if ($result !== false) {

		/** 再检查http响应码是否为200 */
		$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		if ($statusCode == 200) {
			$found = true;
		}
	}
	curl_close($curl);

	return $found;
}

//写入文件
function write_file($l1, $l2=''){
	$dir = dirname($l1);
	if(!is_dir($dir)){
		mkdirss($dir);
	}
	return @file_put_contents($l1, $l2);
}

//递归创建文件
function mkdirss($dirs,$mode=0777) {
	if(!is_dir($dirs)){
		mkdirss(dirname($dirs), $mode);
		return @mkdir($dirs, $mode);
	}
	return true;
}

// 数组保存到文件
function arr2file($filename, $arr=''){
	if(is_array($arr)){
		$con = var_export($arr,true);
	} else{
		$con = $arr;
	}
	$con = "<?php\nreturn $con;\n?>";//\n!defined('IN_MP') && die();\nreturn $con;\n
	write_file($filename, $con);
}

//获取主域名
function Host_User() {
    if($_SERVER['HTTP_HOST']=="127.0.0.1"){
           return $_SERVER['HTTP_HOST'];
    }else{
       preg_match('/[\w][\w-]*\.(?:com\.cn|com|cn|co|net|org|gov|cc|so|name|dj|biz|info)(\/|$)/isU', $_SERVER['HTTP_HOST'], $domain);
       return rtrim($domain[0], '/');
    }
}

// urlencode解码
function rurlencode($string) {
      $key=rawurldecode($string);
      $e=mb_detect_encoding($key, array('UTF-8', 'GBK'));
      if($e=='UTF-8'){
          $key=iconv('UTF-8', 'GB2312', $key);
      }
    return $key;
}


//后台错误提示信息
function Admin_Error($str,$ErrUrl='/') {

      $str="<!doctype html><html><head><meta charset=\"gbk\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\" /><title>提示信息 - ".CS_WebName."</title><link href=\"".CS_WebPath."public/css/cscms.css\" rel=\"stylesheet\" /></head><body><div class=\"wrap\"><div id=\"error_tips\"><h2>提示信息</h2><div class=\"error_cont\"><ul><li>".$str."</li></ul><div class=\"error_return\">&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"javascript:history.back()\" class=\"btn\">返回</a><script>setTimeout(\"window.location.href ='".$ErrUrl."'\", 10000);</script></div></div></div></body></html>";

 return $str;  
}

//错误提示信息
function Web_Error($str,$ErrUrl='/') {

      $str="<!doctype html><html><head><meta charset=\"gbk\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\" /><title>提示信息 - ".CS_WebName."</title><link href=\"".CS_WebPath."public/css/cscms.css\" rel=\"stylesheet\" /></head><body><div class=\"wrap\"><div id=\"error_tips\"><h2>系统错误信息提示</h2><div class=\"error_cont\"><ul><li><font color=#ff6600>错误信息：</font>".$str."</li></ul><div class=\"error_return\">&nbsp;&nbsp;<a href=\"".$ErrUrl."\" class=\"btn\">重试</a>&nbsp;&nbsp;<a href=\"javascript:history.back()\" class=\"btn\">返回</a>&nbsp;&nbsp;<a href=\"/\" class=\"btn\">回到首页</a></div></div></div><div align=\"center\" style=\"color:#FF3300;margin:5pt;font-family:Verdana\">Copyright  2008-2013 <a href=\"http://www.Chshcms.cn/\">Chshcms</a> Technology Co.</div></div></body></html>";

 return $str;  
}

//会员错误提示
function Msg_Error($title,$url){
        if($url=='window.close();'){
             $url="window.opener=null;window.open('','_self','');window.close();";
             $url1='javascript:window.close();';
        }else{
             $url1=$url;
             $url="window.location.href ='".$url."';";
        }
	echo "<title>提示信息 - ".CS_WebName."</title>
	<style type=\"text/css\">
	a{ text-decoration: none; color: #003366 }
	a:hover	{ text-decoration: underline }
	body{ font-size: 12px; }
	table{ font: 12px Tahoma, Verdana; color: #000000 }
	.tableborder{ background: #0080FF; border: 1px solid #0080FF }
	.header{ font: 12px Tahoma, Verdana; color: #FFFFFF; font-weight: bold; background-color: #0080FF }
	.header a{ color: #FFFFFF }
	</style>
	<table width='98%' border=0 align=center cellpadding=3 cellspacing=1>
	     <tr>
		<td height=150>
			<table width='40%' border=0 align=center cellpadding=3 cellspacing=1 class='tableborder'>
				<tr class='header'><td height=25><div align=center>".CS_WebName."&nbsp;&nbsp;--&nbsp;&nbsp;信息提示</div>
				</td></tr>
				<tr>
					<td height=110 bgcolor='#FFFFFF'><div align=center><b>".$title."</b><br><br><a href='".$url1."'>如果您的浏览器没有自动跳转，请点击这里</a></div></td>
				</tr>
			</table>
		</td>
	     </tr>
	</table><script>setTimeout(\"".$url."\", 3000);</script>";
}