<?php
/*LGPL copyright ... */
class A_MailWith_SMTP extends \Amail\A_Mail{
  public $do_debug;       // the level of debug to perform
  public $Debugoutput     = "echo";
  public $do_verp = false;
  public $Timelimit       = 30;
  private $smtp_conn;
  private $helo_rply;
  /**
   * Initialize the class so that the data is in a known state.
   * @access public
   * @return SMTP
   */
  public function __construct(){
    parrent::__construct("SMTP",25,15);
    $this->smtp_conn = 0;
    $this->error = null;
    $this->helo_rply = null;
    $this->do_debug = 0;
  }
  /**
   * Connect to the server specified or use default SMTP_PORT 25.
   * SMTP CODE SUCCESS: 220
   * SMTP CODE FAILURE: 421
   * @access public
   * @param string $host the host of the server
   * @param int $port the port to use
   * @param int $tval give up after ? secs (time to try)
   * @return bool
   */
  public function Connect($host, $port = 0, $tval = 30) {
    $this->error = null;
    if(!$this->IsConnect()){return;}
    if(empty($port)) {  $port = $this->DEFAULD_SMTPPORT;}
    $this->smtp_conn = @fsockopen($host,$port,$errno,$errstr,$tval);// connect to smtp server
    if(empty($this->smtp_conn)){//isconnection
      $this->error = array("error" => "Failed to connect to server","errno" => $errno,"errstr" => $errstr);
      $this->__DEBUG("SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF . '<br />');
      return false;
    }
    // SMTP server can take longer to respond, give longer timeout for first read
    // Windows does not have support for this timeout function
    if(substr(PHP_OS, 0, 3) != "WIN") {
        $max = ini_get('max_execution_time');
        if ($max != 0 && $tval > $max) { // don't bother if unlimited
            @set_time_limit($tval);
        }
        stream_set_timeout($this->smtp_conn, $tval, 0);
    }
    // get any announcement
    $announce = $this->get_lines();
    $this->__INFO("FROM SERVER:" . $announce . $this->CRLF);
    return true;
  }
  /**
   * Initiate a TLS communication with the server.
   * SMTP CODE 220 Ready to start TLS
   * SMTP CODE 501 Syntax error (no parameters allowed)
   * SMTP CODE 454 TLS not available due to temporary reason
   * @access public
   * @return bool success
   */
  public function StartTLS() {
    $this->error = null; # to avoid confusion
    if(!$this->IsConnect()){return;}
    $rply = $this->__TRAFIC("STARTTLS" . $this->CRLF);
    $this->__INFO("FROM SERVER:" . $rply . $this->CRLF);
    if(substr($rply,0,3) != 220){//SMTP RESPONSECODE
      $this->setERROR($rply,"STARTTLS not accepted from server");
      return false;
    }
    // Begin encrypted connection
    return !stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
  }
  /**
   * Performs SMTP authentication.  Must be run after running the
   * Hello() method.  Returns true if successfully authenticated.
   * @access public
   * @param string $username
   * @param string $password
   * @param string $authtype
   * @param string $realm
   * @param string $workstation
   * @return bool
   */
  public function Authenticate($username, $password, $authtype='LOGIN', $realm='', $workstation='') {
    if (empty($authtype)) {
      $authtype = 'LOGIN';
    }
    switch ($authtype) {
      case 'PLAIN':
        // Start authentication
        $rply = $this->__TRAFIC("AUTH PLAIN" . $this->CRLF);
        if(substr($rply,0,3) != 334){//SMTP RESPONSECODE
          $this->setERROR($rply,"AUTH not accepted from server");
          return false;
        }
        $rply = $this->__TRAFIC(base64_encode("\0".$username."\0".$password) . $this->CRLF);
        return substr($rply,0,3) == 235|| $this->setERROR($rply,"Authentication not accepted from server");
        break;
      case 'LOGIN':
        $rply = $this->__TRAFIC("AUTH LOGIN" . $this->CRLF);// Start authentication
        if(substr($rply,0,3) != 334){//SMTP RESPONSECODE
          $this->setERROR($rply,"AUTH not accepted from server");
          return false;
        }        
        $rply = $this->__TRAFIC(base64_encode($username).$this->CRLF); // Send encoded username
        if(substr($rply,0,3) != 334) {//SMTP RESPONSECODE
          $this->setERROR($rply,"Username not accepted from server");
          return false;
        }
        $rply = $this->__TRAFIC(base64_encode($password).$this->CRLF); // Send encoded password
        return substr($rply,0,3) == 235|| $this->setERROR($rply,"Password not accepted from server");
        break;
      case 'NTLM':
        /*
         * ntlm_sasl_client.php
         ** Bundled with Permission
         ** How to telnet in windows: http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx
         ** PROTOCOL Documentation http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication
         */
        require_once('ntlm_sasl_client.php');
        $temp = new stdClass();
        $ntlm_client = new ntlm_sasl_client_class;
        if(! $ntlm_client->Initialize($temp)){//let's test if every function its available
            $this->error = array("error" => $temp->error);
            $this->__DEBUG("You need to enable some modules in your php.ini file: " . $this->error["error"] . $this->CRLF);
            return false;
        }
        $msg1 = $ntlm_client->TypeMsg1($realm, $workstation);//msg1
        $rply = $this->__TRAFIC("AUTH NTLM " . base64_encode($msg1) . $this->CRLF);
        if(substr($rply,0,3) != 334) {//SMTP RESPONSECODE
            $this->setERROR($rply,"AUTH not accepted from server");          
            return false;
        }
        $challange = substr($rply,3);//though 0 based, there is a white space after the 3 digit number....//msg2
        $challange = base64_decode($challange);
        $ntlm_res = $ntlm_client->NTLMResponse(substr($challange,24,8),$password);
        $msg3 = $ntlm_client->TypeMsg3($ntlm_res,$username,$realm,$workstation);//msg3
        // Send encoded username
        $rply = $this->__TRAFIC(base64_encode($msg3) . $this->CRLF);        
        return substr($rply,0,3) == 235|| $this->setERROR($rply,"Could not authenticate"); 
        break;
    }
    return false;
  }
  /**
   * Returns true if connected to a server otherwise false
   * @access public
   * @return bool
   */
  public function IsConnect($methodName="") {
    if(!empty($this->smtp_conn)) {
      $sock_status = socket_get_status($this->smtp_conn);
      if($sock_status["eof"]) {
        // the socket is valid but we are not connected
        $this->__DEBUG("NOTICE:" . $this->CRLF . "EOF caught while checking if connected");
        $this->Close();
        return false;
      }
      return true; // everything looks good
    }
    $this->error = array("error" => "Called ".$methodName." without being connected");
    return false;
  }
  /**
   * Closes the socket and cleans up the state of the class.
   * It is not considered good to use this function without
   * first trying to use QUIT.
   * @access public
   * @return void
   */
  public function Close() {
    $this->error = null; // so there is no confusion
    $this->helo_rply = null;
    if(!empty($this->smtp_conn)) {
      // close the connection and cleanup
      fclose($this->smtp_conn);
      $this->smtp_conn = 0;
    }
  }
  /**
   * Issues a data command and sends the msg_data to the server
   * finializing the mail transaction. $msg_data is the message
   * that is to be send with the headers. Each header needs to be
   * on a single line followed by a <CRLF> with the message headers
   * and the message body being seperated by and additional <CRLF>.
   *
   * Implements rfc 821: DATA <CRLF>
   *
   * SMTP CODE INTERMEDIATE: 354
   *     [data]
   *     <CRLF>.<CRLF>
   *     SMTP CODE SUCCESS: 250
   *     SMTP CODE FAILURE: 552,554,451,452
   * SMTP CODE FAILURE: 451,554
   * SMTP CODE ERROR  : 500,501,503,421
   * @access public
   * @param string $msg_data
   * @return bool
   */
  public function Data($msg_data) {
    $this->error = null; // so no confusion is caused
    if(!$this->IsConnect()){return;}
    $rply = $this->__TRAFIC("DATA" . $this->CRLF);
    $this->__INFO("FROM SERVER:" . $rply . $this->CRLF );
    if(substr($rply,0,3) != 354) {//SMTP RESPONSECODE
        $this->setERROR($rply,"DATA command not accepted from server");
        return false;
    }
    /* the server is ready to accept data!
     * according to rfc 821 we should not send more than 1000
     * including the CRLF
     * characters on a single line so we will break the data up
     * into lines by \r and/or \n then if needed we will break
     * each of those into smaller lines to fit within the limit.
     * in addition we will be looking for lines that start with
     * a period '.' and append and additional period '.' to that
     * line. NOTE: this does not count towards limit.
     */
    // normalize the line breaks so we know the explode works
    $msg_data = str_replace("\r\n","\n",$msg_data);
    $msg_data = str_replace("\r","\n",$msg_data);
    $lines = explode("\n",$msg_data);
    /* we need to find a good way to determine is headers are
     * in the msg_data or if it is a straight msg body
     * currently I am assuming rfc 822 definitions of msg headers
     * and if the first field of the first line (':' sperated)
     * does not contain a space then it _should_ be a header
     * and we can process all lines before a blank "" line as
     * headers.
     */
    $field = substr($lines[0],0,strpos($lines[0],":"));
    $in_headers = false;
    if(!empty($field) && !strstr($field," ")) {
      $in_headers = true;
    }
    $max_line_length = 998; // used below; set here for ease in change
    while(list(,$line) = @each($lines)) {
      $lines_out = null;
      if($line == "" && $in_headers) {
        $in_headers = false;
      }
      // ok we need to break this line up into several smaller lines
      while(strlen($line) > $max_line_length) {
        $pos = strrpos(substr($line,0,$max_line_length)," ");
        // Patch to fix DOS attack
        if(!$pos) {
          $pos = $max_line_length - 1;
        } else {
          $pos = $pos + 1;
        }
        $lines_out[] = substr($line,0,$pos);
        $line = substr($line,$pos);
        /* if processing headers add a LWSP-char to the front of new line
         * rfc 822 on long msg headers
         */
        if($in_headers) {
          $line = "\t" . $line;
        }
      }
      $lines_out[] = $line;
      // send the lines to the server
      while(list(,$line_out) = @each($lines_out)) {
        if(strlen($line_out) > 0 && substr($line_out, 0, 1) == ".") {
            $line_out = "." . $line_out;
        }
        fputs($this->smtp_conn,$line_out . $this->CRLF);
      }
    }
    // message data has been sent
    $rply = $this->__TRAFIC($this->CRLF . "." . $this->CRLF);
    $this->__INFO("SMTP -> FROM SERVER:" . $rply . $this->CRLF);
    return substr($rply,0,3) == 250|| $this->setERROR($rply,"DATA not accepted from server"); 
  }
  /**
   * Sends the HELO command to the smtp server.
   * This makes sure that we and the server are in
   * the same known state.
   *
   * Implements from rfc 821: HELO <SP> <domain> <CRLF>
   *
   * SMTP CODE SUCCESS: 250
   * SMTP CODE ERROR  : 500, 501, 504, 421
   * @access public
   * @param string $host
   * @return bool
   */
  public function Hello($host = '') {
    $this->error = null; // so no confusion is caused
    if(!$this->IsConnect()){return;}
    // if hostname for HELO was not specified send default
    if(empty($host)) {
      // determine appropriate default to send to server
      $host = "localhost";
    }
    // Send extended hello first (RFC 2821)
    return $this->SendHello("EHLO", $host)||$this->SendHello("HELO", $host);
  }
  /**
   * Sends a HELO/EHLO command.
   * @param string $hello
   * @param string $host
   * @return bool
   */
  private function SendHello($hello, $host) {
    $rply = $this->__TRAFIC($hello . " " . $host . $this->CRLF);
    $this->__INFO("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />');
    $this->helo_rply = $rply;
    return substr($rply,0,3) == 250|| $this->setERROR($rply,$hello." not accepted from server");    
  }
  /**
   * Starts a mail transaction from the email address specified in
   * $from. Returns true if successful or false otherwise. If True
   * the mail transaction is started and then one or more Recipient
   * commands may be called followed by a Data command.
   *
   * Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
   *
   * SMTP CODE SUCCESS: 250
   * SMTP CODE SUCCESS: 552,451,452
   * SMTP CODE SUCCESS: 500,501,421
   * @param string $from
   * @return bool
   */
  public function Mail($from) {
    $this->error = null; // so no confusion is caused
    if(!$this->IsConnect()){return;}
    $useVerp = ($this->do_verp ? " XVERP" : "");
    $rply = $this->__TRAFIC("MAIL FROM:<".$from.">".$useVerp.$this->CRLF);
    $this->__INFO("SMTP -> FROM SERVER:".$rply.$this->CRLF.'<br />');    
    return substr($rply,0,3) == 250|| $this->setERROR($rply,"MAIL not accepted from server");
  }
  /**
   * Sends the quit command to the server and then closes the socket
   * if there is no error or the $close_on_error argument is true.
   *
   * Implements from rfc 821: QUIT <CRLF>
   *
   * SMTP CODE SUCCESS: 221
   * SMTP CODE ERROR  : 500
   * @param bool $close_on_error
   * @return bool
   */
  public function Quit($close_on_error = true) {
    $this->error = null; // so there is no confusion
    if(!$this->IsConnect()){return;}
    // get any good-bye messages
    $byemsg = $this->__TRAFIC("quit" . $this->CRLF);
    $this->__INFO("SMTP -> FROM SERVER:" . $byemsg . $this->CRLF);
    $rval = true;
    $e = null;
    if(substr($rply,0,3) != 221) {//SMTP RESPONSECODE
      $rval = false;
      $this->__DEBUG("SMTP -> ERROR: SMTP server rejected quit command: " . $byemsg . $this->CRLF . '<br />');
    }
    if(empty($e) || $close_on_error) {
      $this->Close();
    }
    return $rval;
  }
  /**
   * Sends the command RCPT to the SMTP server with the TO: argument of $to.
   * Returns true if the recipient was accepted false if it was rejected.
   *
   * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
   *
   * SMTP CODE SUCCESS: 250,251
   * SMTP CODE FAILURE: 550,551,552,553,450,451,452
   * SMTP CODE ERROR  : 500,501,503,421
   * @param string $to
   * @return bool
   */
  public function Recipient($to) {
    $this->error = null; // so no confusion is caused
    if(!$this->IsConnect()){return;}
    $rply = $this->__TRAFIC("RCPT TO:<".$to.">".$this->CRLF);
    $this->__INFO("SMTP -> FROM SERVER:".$rply.$this->CRLF);
    return substr($rply,0,3) == 250 ||substr($rply,0,3) == 251 || $this->setERROR($rply,"RCPT not accepted from server");
  }
  /**
   * Sends the RSET command to abort and transaction that is
   * currently in progress. Returns true if successful false
   * otherwise.
   * Implements rfc 821: RSET <CRLF>
   * SMTP CODE SUCCESS: 250
   * SMTP CODE ERROR  : 500,501,504,421
   * @return bool
   */
  public function Reset() {
    $this->error = null; // so no confusion is caused
    if(!$this->IsConnect()){return false;}
    $rply = $this->__TRAFIC("RSET" . $this->CRLF);
    $this->__INFO("SMTP -> FROM SERVER:" . $rply . $this->CRLF );
    return substr($rply,0,3) == 250|| $this->setERROR($rply,"RSET failed"); 
  }
  /**
   * Starts a mail transaction from the email address specified in
   * $from. Returns true if successful or false otherwise. If True
   * the mail transaction is started and then one or more Recipient
   * commands may be called followed by a Data command. This command
   * will send the message to the users terminal if they are logged
   * in and send them an email.
   * Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
   * SMTP CODE SUCCESS: 250
   * SMTP CODE SUCCESS: 552,451,452
   * SMTP CODE SUCCESS: 500,501,502,421
   * @param string $from
   * @return bool
   */
  public function SendAndMail($from) {
    $this->error = null; // so no confusion is caused
    if(!$this->IsConnect()){return;}
    $rply = $this->__TRAFIC("SAML FROM:" . $from . $this->CRLF);
    $this->__INFO("SMTP -> FROM SERVER:" . $rply . $this->CRLF );
    return substr($rply,0,3) == 250|| $this->setERROR($rply,"SAML not accepted from server"); 
  }
  /**
   * Implements from rfc 821: TURN <CRLF>
   * SMTP CODE SUCCESS: 250
   * SMTP CODE FAILURE: 502
   * SMTP CODE ERROR  : 500, 503
   * @return bool
   */
  public function Turn() {
    return false;
  }
  /**
  * Get the current error
  * @return array
  */
  public function getError() {
    return $this->error;
  }
  private function __TRAFIC($command){
    fputs($this->smtp_conn,$command);
    return $this->get_lines();
  }
  /**
   * Read in as many lines as possible
   * either before eof or socket timeout occurs on the operation.
   * With SMTP we can tell if we have more lines to read if the
   * 4th character is '-' symbol. If it is a space then we don't
   * need to read anything else.
   * @return string
   */
  private function get_lines(){
    $data = "";
    $endtime = 0;
    /* If for some reason the fp is bad, don't inf loop */
    if (!is_resource($this->smtp_conn)) {                           return $data;    }
    stream_set_timeout($this->smtp_conn, $this->Timeout);
    if ($this->Timelimit > 0) {
      $endtime = time() + $this->Timelimit;
    }
    while(is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
        $str = @fgets($this->smtp_conn,515);
        $this->__FOLLOW('SMTP -> get_lines(): $data was "'.$data.'"'.$this->CRLF.'<br />'.'--->: $str is "'.$str.'"'.$this->CRLF);
        $data .= $str;
        $this->__FOLLOW('SMTP -> get_lines(): $data is "'.$data.'"'.$this->CRLF);
        // if 4th character is a space, we are done reading, break the loop
        if(substr($str,3,1) == " ") { break; }
        // Timed-out? Log and break
        if($this->istimeout($endtime)){
            break;
        }
    }
    return $data;
  }
  private function istimeout($endtime){
      $info = stream_get_meta_data($this->smtp_conn);
      if ($info['timed_out']) {             
          $this->__FOLLOW("SMTP -> get_lines(): timed-out (" . $this->Timeout . " seconds)");
          return true;
      }
      if ($endtime && time() > $endtime){// Now check if reads took too long 
         $this->__FOLLOW("SMTP -> get_lines(): timelimit reached (" . $this->Timelimit . " seconds)");
          return true;  
      }
      return false;
  }
}
?>