<?php
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 utf8;");
    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 bn_replace($content)
{
  $content=str_replace("(","",$content);
  $content=str_replace(")","",$content);
  $content=str_replace("<","",$content);
  $content=str_replace(">","",$content);
  $content=str_replace(" ","",$content);
  $content=str_replace("","%20;",$content);
  $content=str_replace("","%27;",$content);
  return $content;
}
function html_replace($content)
{
  $content=trim($content);
  $content=str_replace("&","&amp;",$content);
  $content=str_replace("<","&lt;",$content);
  $content=str_replace(">","&gt;",$content);
  $content=str_replace("","%20;",$content);
  $content=str_replace("","%27;",$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);
    }
  }
  $content=preg_replace("/\[url\](.*)\[\/url\]/","<a href=\"\\1\" target=_blank>\\1</a>",$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);
  if($rs[2]!="")
  {
    $page=floor($rs[2]/$page);
	$content=str_replace("[url]".$url."read.php?","[url]".$url."read.php?page=".$page."&",$content);
  }
  $content=preg_replace("/\[url\](.*)\[\/url\]/","<a href=\"\\1\" target=_blank>\\1</a>",$content);
  return $content;
}
function in_replace($content)
{
  $content=preg_replace("/\[url\](.*)\[\/url\]/","<a href=\"\\1\" target=_blank>\\1</a>",$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 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>";
  elseif($page['pages']>1 && $presentpage+1<$page['pages'] && $html=="1")
    $page['linkshow']=$page['linkshow']." <a href=".$file."-".$id."-".($presentpage+1).".html>[下一页]</a>";
  if($page['pages']>1 && $presentpage!=0 && $html=="0")
    $page['linkshow']="<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."-".($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);  
    $content = curl_exec($ch);  
  }
  else
    $content = 1; 
  return $content;
}
function str_substr($start,$end,$str)
{
  $temp=explode($start,$str,2);      
  $content=explode($end,$temp[1],2);      
  return $content[0];      
}
function submitfilter($type,$submit)
{
  if($type==1 and !eregi("^[0-9]+$",$submit))
  {
    Header("Location: index.php");
    exit();
  }
  else
  {
    str_replace("%20","",$submit);
    str_replace("%27","",$submit);
	return $submit;  
  }
}
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;
}
?>