<?php
//数据库连接
class mysql
{
  var $table;
  var $field;
  var $where;
  function open($sqlhost,$sqluser,$sqlpw,$sqldb)
  {
    if(!isset($sqlhost) or $sqlhost=="")
	{
      $con = mysql_connect(c_sqlhost,c_sqluser,c_sqlpw);
      mysql_select_db(c_sqldb, $con);
	}
	else
	{
      $con = mysql_connect($sqlhost,$sqluser,$sqlpw);
      mysql_select_db($sqldb, $con);
	}
    mysql_query("SET NAMES 'GBK'"); 
  }
  function close()
  {
    mysql_close();
  }
  function assignment()
  {
    $rs = mysql_query("SELECT ".$this->field." FROM ".c_sqlprefix.$this->table." WHERE ".$this->where."");
    while($rs1 = mysql_fetch_array($rs))
    {
      $rs2[] = $rs1;
    }
	return $rs2;
  }
  function write()
  {
    mysql_query("INSERT INTO ".c_sqlprefix.$this->table."(".$this->field.") VALUES (".$this->where.")");
  }
  function upgrade()
  {
    mysql_query("UPDATE ".c_sqlprefix.$this->table." SET ".$this->field." WHERE ".$this->where."");
  }
  function delete()
  {
    mysql_query("DELETE FROM ".c_sqlprefix.$this->table." WHERE ".$this->where."");
  }
  function exist($type)
  {
    if($type==1)
	{
      $rs = mysql_fetch_array(mysql_query("SELECT ".$this->field." FROM ".c_sqlprefix.$this->table." WHERE ".$this->where.""));
	  if(empty($rs))
        return 0;
	  else
	    return $rs;
	}
	else
	{
	  $rs = mysql_num_rows(mysql_query("SELECT ".$this->field." FROM ".c_sqlprefix.$this->table." WHERE ".$this->where.""));
	  return $rs;
	}
  }
  //主题页显示内容预览
  function listcontent($content)
  {
	preg_match_all('/\[img\](.*?)\[\/img\]/',$content,$tupian);
    $content=preg_replace('/\[img\](.*?)\[\/img\]/','',$content);
    $content=$this->mysubstr($content,0,104);
    $content=str_replace('<br />',' ',$content);
    if(count($tupian[1])!="0")
      $content=$content."<br />";
    for ($i=0;$i<count($tupian[1]);$i++)
    {
	  $content=$content.'<img src="'.$tupian[1][$i].'" onload="javascript:if(this.height>50)this.height=50">';
    }
	return $content;
  }
  //每日打卡
  function punch($bid,$uid,$bf,$isuser,$uf,$action)
  {
    $yztime=date('Y-m-d',strtotime(date('Y-m-d H:i:s'))+$core_time*3600);
	$rs = mysql_num_rows(mysql_query("SELECT * FROM ".c_sqlprefix."punch WHERE uid='".$uid."' and bid='".$bid."' and published like '%".$yztime."%'"));
	if(!$rs and $action=="punch")
    {
      mysql_query("INSERT INTO ".c_sqlprefix."punch (uid, bid, published) VALUES ('".$uid."', '".$bid."', '".$yztime."')");
      //更新吧排名（用户打卡）
      $this->upranking($bf,$bid);
      if($isuser=="1")
	  {
        $this->table="bar_user";
        $this->field="integral=integral+".$uf;
        $this->where="uid='".$uid."' and bid='".$bid."'";
        $this->upgrade();
      }
      $rs=1;
    }
	return $rs;
  }
  //发送短消息
  function message($content,$addresser,$addressee,$time,$type)
  {
    if($type=="3")
	{
      $type="2";
	}
	mysql_query("INSERT INTO ".c_sqlprefix."message(content,addresser,addressee,sent,type) VALUES ('".$content."','".$addresser."','".$addressee."','".$time."','".$type."')");
  }
  //写入新鲜事
  function newswrite($cid,$published,$belong,$type)
  {
	mysql_query("INSERT INTO ".c_sqlprefix."new(cid, published, belong, type) VALUES ('".$cid."','".$published."','".$belong."','".$type."')");
  }
  //吧排名增减
  function upranking($int,$bid)
  {
    mysql_query("UPDATE ".c_sqlprefix."bar SET ranking = ranking+".$int." WHERE id='".$bid."'");
  }
  //吧会员积分增减
  function upbaruser($int,$bid,$uid)
  {
    mysql_query("UPDATE ".c_sqlprefix."bar_user SET integral = integral+".$int." WHERE uid='".$uid."' and bid='".$bid."'");
  }
  //用户积分记录
  function upintegral($username,$objects,$integral,$type,$time)
  {
	$sid = rand(1000,9999).strtotime($time);
	if($type<=3)
	  mysql_query("UPDATE ".c_sqlprefix."user SET integral=integral-".$integral." WHERE username='".$username."'");
	else
	  mysql_query("UPDATE ".c_sqlprefix."user SET integral=integral+".$integral." WHERE username='".$username."'");
    mysql_query("INSERT INTO ".c_sqlprefix."integral_log(sid,username,objects,integral,type,operatetime) VALUES ('".$sid."','".$username."','".$objects."','".$integral."','".$type."','".$time."')");
  }
  //余额原因变化说明
  function payso($type,$int)
  {
    switch ($type)
    {
      case 1:
        $xx['types']="支付宝充值";
        $xx['moneys']="+".$int;
		break;
	  case 2:
        $xx['types']="手工充值";
        $xx['moneys']="+".$int;
		break;
      case 3:
        $xx['types']="手工扣款";
        $xx['moneys']="-".$int;
		break;
      case 4:
        $xx['types']="积分充值";
        $xx['moneys']="+".$int;
		break;
	  case 5:
        $xx['types']="兑换积分扣款";
        $xx['moneys']="-".$int;
		break;
	  case 6:
        $xx['types']="充值VIP会员";
        $xx['moneys']="-".$int;
		break;
      case 7:
        $xx['types']="充值达人";
        $xx['moneys']="-".$int;
		break;
      case 8:
        $xx['types']="购买多彩程序授权";
        $xx['moneys']="-".$int;
		break;
      case 9:
        $xx['types']="下载收费附件";
        $xx['moneys']="-".$int;
		break;
      case 10:
        $xx['types']="收费附件被下载";
        $xx['moneys']="+".$int;
		break;
    }
	return $xx;
  }
  //积分原因变化说明
  function integralso($type,$int,$so)
  {
    switch ($type)
    {
      case 0:
        $xx['type']="管理员操作：".$so;
        $xx['integral']="-".$int;
		break;
	  case 1:
        $xx['type']="下载收费附件";
        $xx['integral']="-".$int;
		break;
      case 2:
        $xx['type']="积分兑换为余额";
        $xx['integral']="-".$int;
		break;
      case 3:
        $xx['type']="购买道具卡";
        $xx['integral']="-".$int;
		break;
	  case 6:
        $xx['type']="向首页推荐主题获得通过";
        $xx['integral']="+".$int;
		break;
	  case 7:
        $xx['type']="推广用户注册";
        $xx['integral']="+".$int;
		break;
      case 8:
        $xx['type']="推广用户访问";
        $xx['integral']="+".$int;
		break;
      case 9:
        $xx['type']="收费附件被下载";
        $xx['integral']="+".$int;
		break;
      case 10:
        $xx['type']="每日登录";
        $xx['integral']="+".$int;
		break;
      case 11:
        $xx['type']="发起投票";
        $xx['integral']="+".$int;
		break;
      case 12:
        $xx['type']="发布主题";
        $xx['integral']="+".$int;
		break;
      case 13:
        $xx['type']="发表回复";
        $xx['integral']="+".$int;
		break;
      case 14:
        $xx['type']="发布的主题被回复";
        $xx['integral']="+".$int;
		break;
      case 15:
        $xx['type']="管理员操作：".$so;
        $xx['integral']="+".$int;
		break;
      case 16:
        $xx['type']="余额兑换为积分";
        $xx['integral']="+".$int;
		break;
	  case 17:
        $xx['type']="每日签到";
        $xx['integral']="+".$int;
		break;
    }
	return $xx;
  }
  //更新吧排名
  function newranking($int,$ctime)
  {
	$ztdate=date('Y-m-d',strtotime(date('Y-m-d'))+$ctime*3600-86400);
    $jtdate=date('Y-m-d');
	$rs = mysql_num_rows(mysql_query("SELECT * FROM ".c_sqlprefix."bar WHERE uprdate<='".$ztdate."'"));
	if($rs)
    {
      mysql_query("UPDATE ".c_sqlprefix."bar SET rankingq=rankings, rankings=ranking, ranking=ranking*".$int.", uprdate='".$jtdate."' WHERE uprdate='".$ztdate."'");
	  mysql_query("UPDATE ".c_sqlprefix."bar SET rankingq=rankings, rankings = 0 , ranking= 0,uprdate='".$jtdate."' WHERE uprdate<'".$ztdate."'");
	}
  }
  //是否是会员/具有管理权限
  function isuorm($uid,$bid,$type)
  {
	if($type==1)//是否是会员
      $rs=mysql_num_rows(mysql_query("SELECT * FROM ".c_sqlprefix."bar_user WHERE uid = '".$uid."' and bid = '".$bid."'"));
	elseif($type==2)//是否是吧主
	  $rs=mysql_num_rows(mysql_query("SELECT * FROM ".c_sqlprefix."bar_user WHERE uid = '".$uid."' and bid = '".$bid."' and rank = 2"));
	else//是否属于管理团队
	  $rs=mysql_num_rows(mysql_query("SELECT * FROM ".c_sqlprefix."bar_user WHERE uid = '".$uid."' and bid = '".$bid."' and rank > 0"));
	return $rs;
  }
  //是否是VIP会员/达人
  function isvord($uid,$type)
  {
    $rztime=date('Y-m-d H:i:s',strtotime(date('Y-m-d H:i:s'))+$core_time*3600);
	if($type==1)//是否是VIP
      $rs=mysql_num_rows(mysql_query("SELECT * FROM ".c_sqlprefix."vip WHERE uid = '".$uid."' and type = '".$type."' and etime>'".$rztime."'"));
	elseif($type==2)//是否是达人
	  $rs=mysql_num_rows(mysql_query("SELECT * FROM ".c_sqlprefix."vip WHERE uid = '".$uid."' and type = '".$type."' and etime>'".$rztime."'"));
	elseif($type==3)//是否是VIP，返回信息
	{
      $type=1;
	  $rs=mysql_fetch_array(mysql_query("SELECT * FROM ".c_sqlprefix."vip WHERE uid = '".$uid."' and type = '".$type."' and etime>'".$rztime."'"));
	  if(empty($rs))
        $rs=0;
	}
	elseif($type==4)//是否是达人，返回信息
	{
      $type=2;
	  $rs=mysql_fetch_array(mysql_query("SELECT * FROM ".c_sqlprefix."vip WHERE uid = '".$uid."' and type = '".$type."' and etime>'".$rztime."'"));
	  if(empty($rs))
        $rs=0;
	}
	return $rs;
  }
  //日志写入
  function logwrite($content,$username,$published,$type)
  {
	mysql_query("INSERT INTO ".c_sqlprefix."log(operate, username, operatetime, ip, type) VALUES ('".$content."','".$username."','".$published."','".$_SERVER['REMOTE_ADDR']."','".$type."')");
  }
  //会员等级显示
  function djpd($djlb,$bjf,$djjf)
  {
    $rs=split("\|", $djlb);
    $rs1=split("\|", $bjf);
    for ($count=17;$count>=0;$count--)
    {
      if($djjf>=$rs1[$count])
	  {
        $txt='<div class="userdjm"><div class="userdjl">'.$rs[$count].'</div><div class="userdjr3">'.($count+1).'</div></div>';
	    break;
	  }
    }
    return $txt;  
  }
  //是否具有发贴权限
  function rankpost($lock,$master,$corepost,$barpost,$isuser)
  {
	$txt=1;
	if($lock==1 and $master==0)
	  $txt=2;//主题被锁定
	elseif($barpost>2 and $master==0)
	  $txt=5;//只允许管理团队发贴
	elseif($barpost>1 and $isuser==0)
	  $txt=4;//只允许会员发贴
	elseif($corepost==0 and $barpost>0 and !isset($_COOKIE["core_user_name"]))
	  $txt=3;//禁止游客发贴
	return $txt;
  }
  //广告位展示
  function adshow($site,$bid)
  {
	if($bid!="0")
	{
	  $bad=mysql_fetch_array(mysql_query("SELECT code FROM ".c_sqlprefix."ad WHERE site = ".$site." and ranges = 3 and rid=".$bid." order by rand() limit 1"));
	  if(!empty($bad))
	  {
		$bad['code']=str_replace('*h*','"',$bad['code']);
		$ad=str_replace('*d*',"'",$bad['code']);
	    return $ad;
	  }
	  $this->table="bar";
	  $this->field="barclass";
      $this->where="id=".$bid;
	  if($bar=$this->exist(1))
	  {
	    $cad=mysql_fetch_array(mysql_query("SELECT code FROM ".c_sqlprefix."ad WHERE site = ".$site." and ranges = 2 and rid=".$bar['barclass']." order by rand() limit 1"));
	    if(!empty($cad))
	    {
		  $cad['code']=str_replace('*h*','"',$cad['code']);
		  $ad=str_replace('*d*',"'",$cad['code']);
	      return $ad;
	    }
	  }
	}
	$qad=mysql_fetch_array(mysql_query("SELECT code FROM ".c_sqlprefix."ad WHERE site = ".$site." and ranges = 1 and pid not like '%|".$bid."|%' order by rand() limit 1"));
	$qad['code']=str_replace('*h*','"',$qad['code']);
	$ad=str_replace('*d*',"'",$qad['code']);
	return $ad;
  }
  //截取字符
  function mysubstr($str,$start,$len)
  {
    $tmpstr = ""; 
    $strlen = $start + $len; 
    for($i=0;$i<$strlen;$i++)
	{ 
      if(ord(substr($str,$i,1))>0xa0)
	  { 
        $tmpstr.=substr($str,$i,2); 
        $i++;
	  }
	  else 
        $tmpstr .= substr($str, $i, 1); 
    } 
    return $tmpstr; 
  }
  //附件显示
  function fileshow($file)
  {
    $txt="";
	$txts="";
	$yz=1;
    $files = split("\|", $file);
    for($i=0;$i<count($files);$i++)
    {
	  $this->table="upload";
      $this->where="id = '".$files[$i]."'";
      $filess[$i]=$this->exist(1);
	  if(($filess[$i]['filetype']>=3 or $filess[$i]['price']!="0") and $yz==1)
	  {
        $txt.="<br>&nbsp;<table style='font-size:12px' width='100%' cellpadding='2' border='0' cellspacing='0'><tr><td style='font-weight:bold'><span style='font-size:18px; color:#F00'>".count($files)." </span>个附件</td><td width='70' style='color:#999'>售价</td><td width='70' style='color:#999'>大小</td><td width='70' style='color:#999'>下载</td><td width='70' style='color:#999'>时间</td></tr><tr><td colspan='6'><hr size='1' color='C0C1C1'></td></tr>";
	    $yz=0;
	  }
	  if($filess[$i]['filetype']<3 and $filess[$i]['price']=="0")
        $txts.="<br />图片附件：<br /><a href='url.php?id=".$files[$i]."' target=_blank><img src='url.php?id=".$files[$i]."' border=0 onload='javascript:if(this.width>500)this.width=500' title='点击这里用新窗口浏览图片'></a>";
      else
      {
		$time=$date=substr($filess[$i]['uptime'],0,10);
        $price="免费";
        if($filess[$i]['price']!="0")
		{
          if($filess[$i]['pricetype']=="1")
	        $price=$filess[$i]['price']."点积分";
          else
		    $price=$filess[$i]['price']."元余额";
		}
        $txt.="<tr><td><a href='url.php?id=".$files[$i]."' target='_blank' rel='nofollow'>".$filess[$i]['oldfilename']."</a></td><td style='color:#F00'>".$price."</td><td style='color:#999'>".number_format($filess[$i]['filesize']/1024,0)."KB</td><td>".$filess[$i]['nums']."次</td><td style='color:#999'>".$time."</td></tr><tr><td colspan='6'><hr size='1' color='C0C1C1'></td></tr>";
      }
    }
	if($yz==0)
      $txt.="</table>";
	$txt=$txts.$txt;
	return $txt;
  }
}
//获取mac地址
class GetMacAddr
{
  /**
  获取网卡的MAC地址原码；目前支持WIN/LINUX系统
  获取机器网卡的物理（MAC）地址
  **/
  var $return_array = array(); // 返回带有MAC地址的字串数组
  var $mac_addr;
  function GetMacAddr($os_type)
  {
    switch(strtolower($os_type))
	{
      case "linux":
        $this->forLinux();
        break;
      case "solaris":
        break;
      case "unix":
        break;
      case "aix":
        break;
      default:
        $this->forWindows();
        break;
    }
    $temp_array = array();
    foreach ($this->return_array as $value )
	{
      if(preg_match("/[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f]/i",$value,$temp_array))
	  {
        $this->mac_addr = $temp_array[0];
        break;
      }
    }
    unset($temp_array);
    return $this->mac_addr;
  }
  function forWindows()
  {
    @exec("ipconfig /all", $this->return_array);
    if($this->return_array)
      return $this->return_array;
    else
	{
      $ipconfig = $_SERVER["WINDIR"]."\system32\ipconfig.exe";
      if(is_file($ipconfig))
        @exec($ipconfig." /all", $this->return_array);
      else
        @exec($_SERVER["WINDIR"]."\system\ipconfig.exe /all", $this->return_array);
        return $this->return_array;
    }
  }
  function forLinux()
  {
    @exec("ifconfig -a", $this->return_array);
    return $this->return_array;
  }
}
//smtp 邮件发送
class smtp
{
  /* Public Variables */
  var $smtp_port;//smtp_port 端口号
  var $time_out;
  var $host_name;//服务器主机名
  var $log_file;
  var $relay_host;//服务器主机地址
  var $debug;
  var $auth;//验证
  var $user;//服务器用户名
  var $pass;//服务器密码
  /* Private Variables */
  var $sock;
  /* Constractor 构造方法*/
  function smtp($relay_host = "", $smtp_port = 25,$auth = false,$user,$pass)
  {
    $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->host_name = "localhost"; //is used in HELO command
    $this->log_file ="";
    $this->sock = FALSE;
  }
  /* Main Function */
  function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "")
  {
    $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:By Redhat (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)));
    $sent = TRUE;
    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;
  }
  /* Private Functions */
  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 HELO command");
      if (!$this->smtp_putcmd("", base64_encode($this->pass)))
        return $this->smtp_error("sending HELO command");
    }#
    if (!$this->smtp_putcmd("MAIL", "FROM:<".$from.">"))
      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->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."<br>";
  }
  function get_attach_type($image_tag)
  { //
    $filedata = array();
    $img_file_con=fopen($image_tag,"r");
    unset($image_data);
    while ($tem_buffer=AddSlashes(fread($img_file_con,filesize($image_tag))))
      $image_data.=$tem_buffer;
    fclose($img_file_con);
    $filedata['context'] = $image_data;
    $filedata['filename']= basename($image_tag);
    $extension=substr($image_tag,strrpos($image_tag,"."),strlen($image_tag)-strrpos($image_tag,"."));
    switch($extension)
	{
      case ".gif":
        $filedata['type'] = "image/gif";
        break;
      case ".gz":
        $filedata['type'] = "application/x-gzip";
        break;
      case ".htm":
        $filedata['type'] = "text/html";
        break;
      case ".html":
        $filedata['type'] = "text/html";
        break;
      case ".jpg":
        $filedata['type'] = "image/jpeg";
        break;
      case ".tar":
        $filedata['type'] = "application/x-tar";
        break;
      case ".txt":
        $filedata['type'] = "text/plain";
        break;
      case ".zip":
        $filedata['type'] = "application/zip";
        break;
      default:
        $filedata['type'] = "application/octet-stream";
        break;
    }
    return $filedata;
  }
}
//数据库备份
class db
{
  var $linkid;
  var $sqlid;
  var $record;
  function db($host="",$username="",$password="",$database="")
  {
    if(!$this->linkid)    @$this->linkid = mysql_connect($host, $username, $password) or die("连接服务器失败.");
    @mysql_select_db($database,$this->linkid) or die("无法打开数据库");
    return $this->linkid;
  }
  function query($sql)
  {
    mysql_query("SET NAMES gbk;");
    if($this->sqlid=mysql_query($sql,$this->linkid)) return $this->sqlid;
    else 
	{
      $this->err_report($sql,mysql_error);
      return false;
	}
  }
  function nr($sql_id="")
  {
    if(!$sql_id) $sql_id=$this->sqlid;
    return mysql_num_rows($sql_id);
  }
  function nf($sql_id="")
  {
    if(!$sql_id) $sql_id=$this->sqlid;
    return mysql_num_fields($sql_id);
  }
  function nextrecord($sql_id="")
  {
    if(!$sql_id) $sql_id=$this->sqlid;
    if($this->record=mysql_fetch_array($sql_id))    return $this->record;
    else return false;
  }
  function f($name)
  {
    if($this->record[$name]) return $this->record[$name];
    else return false;
  }
  function close(){mysql_close($this->linkid);}
  function lock($tblname,$op="WRITE"){if(mysql_query("lock tables ".$tblname." ".$op)) return true; else return false;}
  function unlock(){if(mysql_query("unlock tables")) return true; else return false;}
  function ar(){return @mysql_affected_rows($this->linkid);}
  function i_id(){return mysql_insert_id();}
  function err_report($sql,$err)
  {
   echo "Mysql查询错误<br>";
   echo "查询语句：".$sql."<br>";
   echo "错误信息：".$err;
  }
}
function write_file($sql,$filename)
{
  $re=true;
  if(!@$fp=fopen("./backup/".$filename,"w+")) {$re=false; echo "failed to open target file";}
  if(!@fwrite($fp,$sql)) {$re=false; echo "failed to write file";}
  if(!@fclose($fp)) {$re=false; echo "failed to close target file";}
  return $re;
}
function down_file($sql,$filename)
{
  ob_end_clean();
  header("Content-Encoding: none");
  header("Content-Type: ".(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') ? 'application/octetstream' : 'application/octet-stream'));
  header("Content-Disposition: ".(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') ? 'inline; ' : 'attachment; ')."filename=".$filename);
  header("Content-Length: ".strlen($sql));
  header("Pragma: no-cache");
  header("Expires: 0");
  echo $sql;
  $e=ob_get_contents();
  ob_end_clean();
}
function writeable($dir)
{
  if(!is_dir($dir)){@mkdir($dir, 0777);}
  if(is_dir($dir))
  {
    if($fp = @fopen("$dir/test.test", 'w'))
	{
      @fclose($fp);
      @unlink("$dir/test.test");
      $writeable = 1;
    } 
    else{$writeable = 0;}
  }
  return $writeable;
}
function make_header($table)
{
  global $d;
  $sql="DROP TABLE IF EXISTS ".$table."\n";
  $d->query("show create table ".$table);
  $d->nextrecord();
  $tmp=preg_replace("/\n/","",$d->f("Create Table"));
  $sql.=$tmp."\n";
  return $sql;
}
function make_record($table,$num_fields)
{
  global $d;
  $comma="";
  $sql='';
  $sql .= "INSERT INTO ".$table." VALUES(";
  for($i = 0; $i < $num_fields; $i++) 
  {$sql .= ($comma."'".mysql_escape_string($d->record[$i])."'"); $comma = ",";}
  $sql .= ")\n";
  return $sql;
}
//其他
function is_ip($gonten)
{
  $ip = explode(".",$gonten);
    for($i=0;$i<count($ip);$i++)
    {
      if($ip[$i]>255){
      return (0);
    }
  }
  return ereg("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$",$gonten);
}
function ip_three($ip)
{
  $rs=split("\.", $ip);
  $ip=$rs[0].".".$rs[1].".".$rs[2].".*";
  return $ip;
}
function replacemandf($content,$str)
{
  $rs=$str."|";
  $content=str_replace($rs,"",$content);
  $rs="|".$str;
  $content=str_replace($rs,"",$content);
  $content=str_replace($str,"",$content);
  return $content;
}
function submitfilter($submit)
{
  if(!eregi("^[0-9]+$",$submit))
  {
    Header("Location: index.php");
    exit();
  }
}
function bn_replace($content)
{
  $content=str_replace("|","",$content);
  $content=str_replace(" ","",$content);
  $content=str_replace("（","",$content);
  $content=str_replace("）","",$content);
  $content=str_replace("&lt;","",$content);
  $content=str_replace("&gt;","",$content);
  return $content;
}
function html_replace($content)
{
  $content=trim($content);
  $content=str_replace("　","",$content);
  $content=str_replace(",","，",$content);
  $content=str_replace("(","（",$content);
  $content=str_replace(")","）",$content);
  $content=str_replace("%20","％20",$content);
  $content=str_replace("%27","％27",$content);
  $content=str_replace("&","&amp;",$content);
  $content=str_replace("<","&lt;",$content);
  $content=str_replace(">","&gt;",$content);
  $content=str_replace("'","&#39;",$content);
  return $content;
}
function html_replacef($content)
{
  $content=str_replace("，",",",$content);
  $content=str_replace("（","(",$content);
  $content=str_replace("）",")",$content); 
  $content=str_replace("&amp;","&",$content);
  $content=str_replace("&lt;","<",$content);
  $content=str_replace("&gt;",">",$content);
  $content=str_replace("&#39;","'",$content);
  return $content;
}
function autourl($content)
{
  $content=preg_replace("/\[url\](.*?)\[\/url\]/","<a href=\"\\1\" target=_blank>\\1</a>",$content);
  return $content;
}
function post_replace($content)
{
  $content=str_replace("<br />","<br>",$content);
  $content=str_replace(" ","&nbsp;",$content);
  $preg = '/\[swf\](.*)\[\/swf\]/';
  preg_match_all($preg, $content, $rs);
  for($i=0;$i<count($rs[1]);$i++)
  {
    if(!eregi(".swf",$rs[1][$i]))
    {
	  $content=str_replace("[swf]".$rs[1][$i]."[/swf]","<br><span style='color:#FF0000'>作者插入的非有效视频，系统自动屏蔽</span><br>",$content);
    }
  }
  $preg = '/\[img\](.*)\[\/img\]/';
  preg_match_all($preg, $content, $rs);
  for($i=0;$i<count($rs[1]);$i++)
  {
    if(strlen($rs[1][$i])<10)
    {
	  $content=str_replace("[img]".$rs[1][$i]."[/img]","<br><span style='color:#FF0000'>作者插入的非有效图片，系统自动屏蔽</span><br>",$content);
    }
  }
  $content=autourl($content);
  $content=preg_replace("/\[img\](.*?)\[\/img\]/","<a href=\"\\1\" target=_blank><img src=\"\\1\" border=0 onload=\"javascript:if(this.width>600)this.width=600\" title=\"点击这里用新窗口浏览图片\"></a>",$content);
  $content=preg_replace("/\[swf\](.*?)\[\/swf\]/","<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6\,0\,29\,0\" width=\"520\" height=\"420\"><param name=quality value=high><param name=\"SRC\" value=\"\\1\"><embed src=\"\\1\" quality=high pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\" type=\"application/x-shockwave-flash\" width=\"550\" height=\"360\"></embed></object>", $content);
  $content=preg_replace("/\[wmv\](.*?)\[\/wmv\]/","<embed src=\"\\1\" type=\"audio/x-pn-realaudio-plugin\" controls=\"ControlPanel\,StatusBar\" height=40 width=320 autostart=\"false\" loop=\"1\">", $content);
  $content=preg_replace("/\[quote\](.+?)\[\/quote\]/is","<div style='width:98%; padding-top:10px; line-height:20px; background:#F7F7F7; border:#CCCCCC 1px solid;'><blockquote>以下为引用内容：<hr>\\1</blockquote></div>", $content);
  return $content;
}
function message_replace($content,$page,$url)
{
  $content=str_replace("<br />","<br>",$content);
  $preg = '/\[url\](.*)\#(.*)\[\/url\]/';
  preg_match($preg, $content, $rs);
  $content=autourl($content);
  return $content;
}
function autolink($content)
{
  $content=preg_replace("(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)","[url]\\0[/url]",$content);
  $content=str_replace("[img][url]","[img]",$content);
  $content=str_replace("[/url][/img]","[/img]",$content);
  $content=str_replace("[swf][url]","[swf]",$content);
  $content=str_replace("[/url][/swf]","[/swf]",$content);
  $content=str_replace("[wmv][url]","[wmv]",$content);
  $content=str_replace("[/url][/wmv]","[/wmv]",$content);
  $content=str_replace("[url][url]","[url]",$content);
  $content=str_replace("[/url][/url]","[/url]",$content);
  return $content;
}
//伪静态网址
function htmlurl($barurl,$file,$id,$page,$rewrite)
{
  if($rewrite=="1")
    $url=$barurl.$file."-".$id."-".$page.".html";
  else
  {
	if($file=="list")
      $url=$barurl."?list=".$id."&page=".$page;
    else
	  $url=$barurl.$file.".php?id=".$id."&page=".$page;
  }
  return $url;
}
//分页
function pages($topicamount,$pagenumber,$presentpage,$file,$get,$id,$html)
{
  $page['count']=$topicamount;
  $page['pages']=ceil($topicamount/$pagenumber);
  $page['linkshow']="<a href=".$file.".php?page=".$presentpage.$get.$id.">".($presentpage+1)."</a>";
  if($html=="1")
    $page['linkshow']="<a href=".$file."-".$id."-".$presentpage.".html>".($presentpage+1)."</a>";
  for($i=1;$i<=2;$i++)
  {
    if($presentpage+1+$i<=$page['pages'] && $html=="0")
      $page['linkshow']=$page['linkshow']." <a href=".$file.".php?page=".($presentpage+$i).$get.$id.">[".($presentpage+1+$i)."]</a>";
	elseif($presentpage+1+$i<=$page['pages'] && $html=="1")
      $page['linkshow']=$page['linkshow']." <a href=".$file."-".$id."-".($presentpage+$i).".html>[".($presentpage+1+$i)."]</a>";
  }
  for($i=1;$i<=2;$i++)
  {
    if($presentpage-$i>=0 && $html=="0")
      $page['linkshow']="<a href=".$file.".php?&page=".($presentpage-$i).$get.$id.">[".($presentpage+1-$i)."]</a> ".$page['linkshow'];
	elseif($presentpage-$i>=0 && $html=="1")
      $page['linkshow']="<a href=".$file."-".$id."-".($presentpage-$i).".html>[".($presentpage+1-$i)."]</a> ".$page['linkshow'];
  }
  if($page['pages']>1 && $presentpage+1<$page['pages'] && $html=="0")
    $page['linkshow']=$page['linkshow']." <a href=".$file.".php?page=".($presentpage+1).$get.$id.">[下一页]</a> <a href=".$file.".php?page=".($page['pages']-1).$get.$id.">[尾页]</a>";
  elseif($page['pages']>1 && $presentpage+1<$page['pages'] && $html=="1")
    $page['linkshow']=$page['linkshow']." <a href=".$file."-".$id."-".($presentpage+1).".html>[下一页]</a> <a href=".$file."-".$id."-".($page['pages']-1).".html>[尾页]</a>";
  if($page['pages']>1 && $presentpage!=0 && $html=="0")
    $page['linkshow']="<a href=".$file.".php?&page="."0".$get.$id.">[首页]</a> <a href=".$file.".php?&page=".($presentpage-1).$get.$id.">[上一页]</a> ".$page['linkshow'];
  elseif($page['pages']>1 && $presentpage!=0 && $html=="1")
    $page['linkshow']="<a href=".$file."-".$id."-0.html>[首页]</a> <a href=".$file."-".$id."-".($presentpage-1).".html>[上一页]</a> ".$page['linkshow'];
  if($page['pages']<2)
    $page['linkshow']="";
  return $page;
}
function GetCurUrl() 
{ 
  if(!empty($_SERVER["REQUEST_URI"])) 
  { 
    $scriptName = $_SERVER["REQUEST_URI"]; 
    $nowurl = $scriptName; 
  } 
  else 
  { 
    $scriptName = $_SERVER["PHP_SELF"]; 
    if(empty($_SERVER["QUERY_STRING"])) 
      $nowurl = $scriptName; 
    else
      $nowurl = $scriptName."?".$_SERVER["QUERY_STRING"];
  }
  $nowurl = str_replace("&","=and=",$nowurl);
  return $nowurl; 
}
function random($length)
{ 
    $hash = ''; 
    $chars = '123456789abcdefghijkmnpqrstuvwxyz'; 
    $max = strlen($chars) - 1; 
    mt_srand((double)microtime() * 1000000); 
    for($i = 0; $i < $length; $i++)
	{ 
      $hash .= $chars[mt_rand(0, $max)]; 
    } 
    return $hash; 
}
function geturldata($url)  
{
  if(function_exists(curl_init))
  {
    $ch = curl_init();  
    curl_setopt ($ch, CURLOPT_URL, $url);  
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);  
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);  
	curl_setopt ($ch, CURLOPT_TIMEOUT,10);  
    $content = curl_exec($ch);  
  }
  else
    $content = 1; 
  return $content;
}
function book_geturldata($url,$urls) 
{
  if(function_exists(curl_init))
  {
    $ch = curl_init();  
    curl_setopt ($ch, CURLOPT_URL, $url);
	curl_setopt ($ch, CURLOPT_REFERER, $urls);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,120);  
	curl_setopt ($ch, CURLOPT_TIMEOUT,600);  
	curl_setopt ($ch, CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"); 
    $content = curl_exec($ch);  
  }
  else
    $content = "0"; 
  return $content;
}
function GrabImage($url,$filename,$urls)
{
  $img = book_geturldata($url,$urls);
  if(!strpos($img,'无法找到该页'))
  {
    $fp2=fopen($filename, "a"); 
    fwrite($fp2,$img); 
    fclose($fp2);
  }
  return $filename; 
}
function check_wap()
{   
  return stristr($_SERVER['HTTP_VIA'],"wap")?true:false;  
}
function task($type,$num,$belong,$prefix)
{
  $where="state!='0' and state != '3'";
  if($belong!="0")
    $where="belong='".$belong."' and ".$where;
  if($type=="pboutique")//精华
    $rs = mysql_query("SELECT id,theme,author,published FROM ".$prefix."topic WHERE boutique ='1' and ".$where." order by published desc limit 0,".$num);
  elseif($type=="precommend")//推荐
    $rs = mysql_query("SELECT id,theme,author,published FROM ".$prefix."topic WHERE recommend !='0' and ".$where." order by published desc limit 0,".$num);
  elseif($type=="pnew")//最新发布
    $rs = mysql_query("SELECT id,theme,author,published FROM ".$prefix."topic WHERE ".$where." order by published desc limit 0,".$num);
  elseif($type=="prenew")//最新回复
    $rs = mysql_query("SELECT id,theme,author,published FROM ".$prefix."topic WHERE ".$where." order by republished desc limit 0,".$num);
  elseif($type=="pclick")//最高点击
    $rs = mysql_query("SELECT id,theme,author,published FROM ".$prefix."topic WHERE ".$where." order by click desc limit 0,".$num);
  elseif($type=="preply")//最高回复
    $rs = mysql_query("SELECT id,theme,author,published FROM ".$prefix."topic WHERE ".$where." order by reply desc limit 0,".$num);
  while($taskrs = mysql_fetch_array($rs))
  {
    $task[] = $taskrs;
  }
  return $task;
}
function encode($txt)
{
  $encode =mb_detect_encoding($txt , array('ASCII','GB2312','GBK','UTF-8','BIG5'));
  if($encode!="EUC-CN")
    $txt=iconv($encode, "gb2312", $txt);
  return $txt;
}
function wappost_replace($content)
{
  $content=str_replace("<br />","<br>",$content);
  $content=str_replace(" ","&nbsp;",$content);
  $preg = '/\[swf\](.*)\[\/swf\]/';
  preg_match_all($preg, $content, $rs);
  for($i=0;$i<count($rs[1]);$i++)
  {
    if(!eregi(".swf",$rs[1][$i]))
	  $content=str_replace("[swf]".$rs[1][$i]."[/swf]","<br><span style='color:#FF0000'>用户插入的不是有效视频</span><br>",$content);
  }
  $content=preg_replace("/\[url\](.*?)\[\/url\]/","<a href=\"\\1\" target=_blank>\\1</a>",$content);
  $content=preg_replace("/\[img\]images(.*?)\[\/img\]/","<img src=\"images\\1\" border=0>",$content);
  $content=preg_replace("/\[img\](.*?)\[\/img\]/","<a href=\"\\1\" target=_blank>查看原图</a><img src=\"\\1\" border=0 width=\"200\">",$content);
  $content=preg_replace("/\[swf\](.*?)\[\/swf\]/","<br><span style='color:#FF0000'>视频无法在手机版播放</span><br>", $content);
  $content=preg_replace("/\[wmv\](.*?)\[\/wmv\]/","<br><span style='color:#FF0000'>音乐无法在手机版播放</span><br>", $content);
  $content=preg_replace("/\[quote\](.+?)\[\/quote\]/is","<div style='width:98%; padding-top:10px; line-height:20px; background:#F7F7F7; border:#CCCCCC 1px solid;'><blockquote>以下为引用内容：<hr>\\1</blockquote></div>", $content);
  return $content;
}
function jump($url)
{
  Header("Location: ".$url);
  exit();
}
error_reporting(0);
?>