Location: PHPKode > scripts > txtSQL MailBox > txtsql-mailbox/class.inc
<?
class rc4crypt {

	function endecrypt ($pwd, $data, $case) {

		if ($case == 'de') {

			$data = urldecode($data);

		}

		$key[] = "";
		$box[] = "";
		$temp_swap = "";
		$pwd_length = 0;

		$pwd_length = strlen($pwd);

		for ($i = 0; $i < 255; $i++) {

			$key[$i] = ord(substr($pwd, ($i % $pwd_length)+1, 1));
			$box[$i] = $i;

		}

		$x = 0;

		for ($i = 0; $i < 255; $i++) {

			$x = ($x + $box[$i] + $key[$i]) % 256;
			$temp_swap = $box[$i];

			$box[$i] = $box[$x];
			$box[$x] = $temp_swap;

		}

		$temp = "";
		$k = "";

		$cipherby = "";
		$cipher = "";

		$a = 0;
		$j = 0;

		for ($i = 0; $i < strlen($data); $i++) {

			$a = ($a + 1) % 256;
			$j = ($j + $box[$a]) % 256;

			$temp = $box[$a];
			$box[$a] = $box[$j];

			$box[$j] = $temp;

			$k = $box[(($box[$a] + $box[$j]) % 256)];
			$cipherby = ord(substr($data, $i, 1)) ^ $k;

			$cipher .= chr($cipherby);

		}

		if ($case == 'de') {

			$cipher = urldecode(urlencode($cipher));

		} else {

			$cipher = urlencode($cipher);

		}

		return $cipher;

	}

}

class POP3{
	var $hostname;
	var $user;
	var $password;
	var $apop="";
	var $port=110;
	var $DEBUG=0;
	var $exit = true;
	var $has_error = false;
	
	// convert charsets to HTML 
	var $charsets = array("iso-8859-1" => array( 
                        array("/=\r\\\n/", "/=3D/", "/=20/", "/=B4/", 
                              "/=22/", "/=26/", "/=3C/", "/=3E/", 
                              "/=([0-9A-Fa-f][0-9A-Fa-f])/e"), 
                        array("\n", "=", " ", "'", 
                              "&#34;", "&#38;", "&#60;", "&#62;", 
                              "'&#' . hexdec('\\1') . ';'") 
                                            ) 
                                ); 


	/* Private variables - DO NOT ACCESS */

	var $connection=0;
	var $greeting = "";
	var $state="DISCONNECTED";
	var $must_update=0;
	
	function POP3($hostname,$user,$password,$apop="") {
		$this->hostname = $hostname;
		$this->user = $user;
		$this->password = $password;
		$this->apop = $apop;
	}

 	function AddError($error) {
 		$this->has_error = true;
 		echo "<br><br><center>\n";
		echo "<table border='0' width='400' cellpadding='0' cellspacing='0'>\n";
  		echo "<tr>\n";
    	echo "<th width='100%' class=\"bgrowcolor3\">\n";
    	echo "<b class=\"font2\"><b>Error:</b></b></th></tr><tr>\n";
  		echo "<td width='100%' class=\"bgrowcolor1\" align='center'><b class=\"font1\">\n";
  		echo $error."</b>\n";
  		echo "</td>\n";
  		echo "</tr>\n";
		echo "</table>\n";
		echo "</center><br><br>\n";
 		
 		$this->CloseConnection();
 		if ($this->exit) exit;
	}
	function POP3Command($command, $result="") {
		if ($this->DEBUG) echo "<b>Sending Command: </b>".$command."<br>";flush();
		@fputs($this->connection, "$command\r\n");
		$result = @fgets($this->connection, 100);
				
		if (eregi("^(\+OK)", $result)) :
			if ($this->DEBUG) echo "<b>Result OK: </b><br>";flush();
			return true;
		else :
			$this->AddError($result);
		endif;
	}
 	function OpenConnection() {
 		if ($this->DEBUG) echo "<b>Openning Connection to: </b>".$this->hostname."<br>";flush();
 		if($this->hostname=="") 
   			$this->AddError("You must specified a valid hostname");
   		$this->connection = fsockopen($this->hostname,$this->port, &$errno, &$errstr);
		if ($this->DEBUG) echo "<b>Connection opened </b><br>";flush();
   		if (!($this->connection)) :
   			if ($errno == 0) 
   				 $this->AddError("Invalid Mail Server Name");
   			$this->AddError($errno." ".$errstr);
   		endif;
		return true;
 	}

 	function CloseConnection() {
  		if($this->connection!=0) :
   			fclose($this->connection);
   			$this->connection=0;
		endif;
 	}

 	function Open() {
  		if($this->state!="DISCONNECTED")
   			$this->AddError("1 a connection is already opened");
  		$this->OpenConnection();
			$this->greeting = @fgets($this->connection, 100);
  			if(GetType($this->greeting)!="string" OR strtok($this->greeting," ")!="+OK") :
   				$this->CloseConnection();
   				$this->AddError("2 POP3 server greeting was not found");
  			endif;
  		$this->greeting=strtok("\r\n");
  		$this->must_update=0;
  		$this->state="AUTHORIZATION";
  		$this->Login();
  		return true;
 	}
 
 /* Close method - this method must be called at least if there are any
     messages to be deleted */

 	function Close() {
  		if($this->state=="DISCONNECTED")
   			$this->AddError("no connection was opened");
  		if($this->must_update) 
   			$this->POP3Command("QUIT");
  		$this->CloseConnection();
  		$this->state="DISCONNECTED";
  		return true;
 	}

 /* Login method - pass the user name and password of POP account.  Set
     $apop to 1 or 0 wether you want to login using APOP method or not.  */

	function Login() {
  		if($this->state!="AUTHORIZATION")
   			$this->AddError("connection is not in AUTHORIZATION state");
  		if($this->apop) :
   			$this->POP3Command("APOP $this->user ".md5($this->greeting.$this->password));
  		else :
  			$this->POP3Command("USER $this->user");
  			$this->POP3Command("PASS $this->password");
  		endif;
  		$this->state="TRANSACTION";
 	}

	/* Statistics method - pass references to variables to hold the number of
     messages in the mail box and the size that they take in bytes.  */

	function Stats($msg=""){
  		if($this->state!="TRANSACTION")
   			$this->AddError("connection is not in TRANSACTION state");
  		if ($msg == "") :
  			$this->POP3Command("STAT", &$result);
  		else :
  			$this->POP3Command("LIST $msg", &$result);
  		endif;
  		$p = explode(" ", $result);
  		$stat["message"] = $p[1];
  		$stat["size"] = $p[2];
  		return $stat;
 	}

	function GetHeaders($message=1) {
		$this->POP3Command("TOP $message 0");
		for ($headers="";;) {
			$line = fgets($this->connection, 100);
	  		if (trim($line) == "." OR feof($this->connection)) {
	  			break;		
			}
	  		$headers .= $line;
	  	}
		return $headers;
	}

	function GetMessageID($message="") {
		if ($message) :
			$this->POP3Command("UIDL $message", &$result);
			$id = explode (" ", $result);	
			return ereg_replace("[<>]","",$id[2]);
		else :
			$this->POP3Command("UIDL") ;
			while (!feof($this->connection)) :
				$line = fgets($this->connection, 100);
				if (trim($line) == ".") {
				  	break;		
				}
				$part = explode (" ", $line);
				$part[1] = ereg_replace("[<>]","",$part[1]);
				$id[$part[0]] = $part[1];	
			endwhile;
			return $id;			
		endif;

	}

	function GetMessage($msg=1) {
		$i = 0;	
		$this->POP3Command("RETR $msg");	
		for ($m="";;) {
			$line = fgets($this->connection, 100);
			if (trim($line) == "." OR feof($this->connection)) {
			  	break;		
			}			
			if (chop($line) == ""  AND $i < 1) :
				$message["header"] = $m;
				$i++;
			endif;
			if ($i > 0) 
				$messagebody .= $line;	
			$m .= $line;
		}
		$message["body"] = $messagebody;
		$message["full"] = $m;
		return $message;
	}

	
  	function convertCharset($str, $charset) 
	{ 
	    $charset = strtolower($charset); 
	    if (!isset($this->charsets[$charset][0]) || empty($this->charsets[$charset][0])) 
	      return $str; 
	    else 
	      return preg_replace($this->charsets[$charset][0], $this->charsets[$charset][1],$str); 
	} 



	function decodeISO($str) {
	    if(eregi("=\?iso-8859-1.+=",$str)) {
		$str = $this->convertCharset($str,"iso-8859-1");
		$str = eregi_replace("(^=\?iso-8859-1\?q\?)|\?|=","",$str);
	    }
	    return $str;
	}

	function ListMessage($msg) {
		$list = array();
		$list["has_attachment"] = false;
		$list["size"] = '';
		$this->POP3Command("RETR $msg");	
		for ($m="";;) {
			$line = fgets($this->connection, 100);
	
			$list["size"] += strlen($line);
			if (trim($line) == "." OR feof($this->connection)) {
			  	break;		
			}

			if (eregi("^Subject: (.*)", $line, $reg)) {
				$reg[1] = $this->decodeISO($reg[1]);
				$list["subject"] = $reg[1];
			}

			if (eregi("^Date: (.*)", $line, $reg)) {
				$reg[1] = $this->decodeISO($reg[1]);
				$date = $reg[1];
			}

			if (eregi("^From: (.*)", $line, $reg)) {
				$reg[1] = $this->decodeISO($reg[1]);
				$from = $reg[1];
			}

			if (eregi("^Content-Disposition: attachment", $line) OR eregi("^Content-Disposition: inline", $line)) 
				$list["has_attachment"] = true;;
		}

		// eregi("(.+) (.+) (.+) ([0-9]{1,2})([0-9]{1,2}) (.+):(.+):(.+) .+", $date, $dreg);
		eregi("(.+) (.+) (.+) .+", $date, $dreg);
		$list["date"] = $dreg[1]." ".$dreg[2]." ".$dreg[3];
	

		//$from = eregi_replace("<|>|\[|\]|\(|\)|\"|\'|(mailto:)|(^=\?iso-8859-1.+=)", "", $from);
		$from = eregi_replace("<|>|\[|\]|\(|\)|\"|\'|(mailto:)", "", $from);
 	
		if (eregi("(.*)? (.+@.+\\..+)", $from)) :
   			eregi("(.*)? (.+@.+\\..+)", $from, $reg);
   			$list["sender"]["name"] = $reg[1];
   			$list["sender"]["email"] = $reg[2];
 		else :
 			eregi("(.+@.+\\..+)", $from, $reg);
 			$list["sender"]["name"] = $reg[1];
 			$list["sender"]["email"] = $reg[1];
		endif;
		return $list;				
	}

 	function DeleteMessage($message) {
  		if($this->state!="TRANSACTION")
   			$this->AddError("connection is not in TRANSACTION state");
  		$this->POP3Command("DELE $message");
		$this->must_update=1;
  		return true;
 	}

 	function ResetDeletedMessages() {
  		if($this->state!="TRANSACTION")
   			$this->AddError("connection is not in TRANSACTION state");
  		$this->POP3Command("RSET");
  		$this->must_update=0;
  		return("");
 	}

 	function NOOP() {
  		if($this->state!="TRANSACTION")
   			$this->AddError("connection is not in TRANSACTION state");
  		$this->POP3Command("NOOP");
  		return("");
  	}
};





class DecodeMessage{
  var $header;
  var $body;
  var $fullmessage;
  var $auto_decode = true;
  var $attachment_path;
  var $choose_best = true;
  var $best_format = "text/html";

  function InitHeaderAndBody($header, $body) {
    $this->header = $header;
    $this->body = $body;
    $this->fullmessage = chop($header)."\t\n\t\n".ltrim($body);
  }
  function Body() {
    return trim($this->body);
  }
  function InitMessage($msg) {
    $i = 0;
    $m = "";
    $messagebody = "";
    $line = explode("\n",trim($msg));
    for ($j=0;$j<count($line);$j++) {
      if (chop($line[$j]) == ""  AND $i < 1) :
        $this->header = $m;
        $i++;
      endif;
      if ($i > 0)
        $messagebody .= $line[$j]."\n";
      $m .= $line[$j]."\n";
    }
    $this->body = $messagebody;
    $this->fullmessage = $msg;
    global $download_dir;
    $this->attachment_path = $download_dir;
  }

  function Headers($field="") {
    if ($field == "") :
      return $this->header;
    else :
      $hd = "";
      $field = $field.":";
      $start = 0;
      $j=0;
      $header = eregi_replace("\r", "\n", $this->header);
      $p = explode("\n", $header);
      do {
        for ($i=$start;$i<count($p);$i++) {
          if (ereg("^($field)", $p[$i]))  :
              $position = $i;
              $hd .= ereg_replace("$field", "",$p[$i]);
              break;
            endif;
        }
        if (ereg("^($field)", $p[$i]))  :
          for ($i=$position+1;$i<count($p);$i++) {
            $tok = strtok($p[$i], " ");
            if (ereg(":$", $tok) AND (!(eregi("^($field)", $tok))))
              break;
            $hd .= ereg_replace("$field", "",$p[$i]);
          }
          $start=$i+1;
        endif;
      } while ($j++ < count($p));
    return $hd;
    endif;
  }

  function ContentType() {
    $c = $this->Headers("Content-Type");
    
//    echo "<br>##### C=$c!";

    $ct = ereg_replace("[[:space:]]", "", $c);

//    echo "<br>##### CT=$ct!";

    if (!(ereg(";", $ct))) :
      $content["type"] = trim($ct);
    else :
      $p = explode (";", $ct);
      for ($i=0;$i<count($p);$i++) {
        if (eregi("^(text)", $p[$i])) :
          $content["type"] = $p[$i];
        elseif (eregi("^(multipart)", $p[$i])) :
          $content["type"] = $p[$i];
        elseif (eregi("^(application)", $p[$i])) :
          $content["type"] = $p[$i];
        elseif (eregi("^(message)", $p[$i])) :
          $content["type"] = $p[$i];
        elseif (eregi("^(image)", $p[$i])) :
          $content["type"] = $p[$i];
        elseif (eregi("^(audio)", $p[$i])) :
          $content["type"] = $p[$i];
        elseif (eregi("^(charset)", $p[$i])) :
          $content["charset"] = eregi_replace("(charset=)|(\")", "", $p[$i]);
        elseif (eregi("^(report-type)", $p[$i])) :
          $content["report-type"] = eregi_replace("(report-type=)|(\")", "", $p[$i]);
        elseif (eregi("^(type)", $p[$i])) :
          $content["subtype"] = eregi_replace("(type=)|(\")", "", $p[$i]);
        elseif (eregi("^(boundary)", $p[$i])) :
          $content["boundary"] = eregi_replace("(boundary=)|(\")", "", $p[$i]);
        elseif (eregi("^(name)", $p[$i])) :
          $content["name"] = eregi_replace("(name=)|(\")", "", $p[$i]);
        elseif (eregi("^(access-type)", $p[$i])) :
          $content["access-type"] = eregi_replace("(access-type=)|(\")", "", $p[$i]);
        elseif (eregi("^(site)", $p[$i])) :
          $content["site"] = eregi_replace("(site=)|(\")", "", $p[$i]);
        elseif (eregi("^(directory)", $p[$i])) :
          $content["directory"] = eregi_replace("(directory=)|(\")", "", $p[$i]);
        elseif (eregi("^(mode)", $p[$i])) :
          $content["mode"] = eregi_replace("(mode=)|(\")", "", $p[$i]);
        endif;
      }
    endif;
    return $content;
  }
  function ContentDisposition() {
    $c = $this->Headers("Content-Disposition");
    $c = ereg_replace("[[:space:]]", "", $c);
    if (!(ereg(";", $c))) :
      $cd["type"] = $c;
    else :
      $p = explode(";", $c);
      for ($i=0;$i<count($p);$i++) {
        if (eregi("^(inline)", $p[$i])) :
          $cd["type"] = $p[$i];
        elseif (eregi("^(attachment)", $p[$i])) :
          $cd["type"] = $p[$i];
        elseif(eregi("^(filename)", $p[$i])) :
          $cd["filename"] = eregi_replace("(filename=)|(\")", "", $p[$i]);
        endif;
      }
    endif;
    return $cd;
  }
  function my_array_shift(&$array) {
    reset($array);
    $key = key($array);
    $val = current($array);
    unset($array[$key]);
    return $val;
  }
  function my_array_compact(&$array) {
    while (list($key, $val) = each($array)) :
        if (chop($val) == '')
          unset($array[$key]);
    endwhile;
  }
   function my_in_array($value, $array) {
    while (list($key, $val) = each($array)) :
        if (strcmp($value, $val) == 0)
          return true;
    endwhile;
    return false;
  }
  function Result() {
    $is_multipart_alternative = false;
    $is_multipart_related = false;
    $found_best = false;
    do {
      $next_message = "";
      do {
        $next_multipart = "";
        $content = $this->ContentType();
        $cd = $this->ContentDisposition();
        if ( eregi("^(multipart)", $content["type"]) ) :

//echo "<br>#### Multipart found";

          if ( eregi("multipart/alternative", $content["type"]) ) :
            $is_multipart_alternative = true;
          endif;
          if ( eregi("multipart/related", $content["type"]) ) :
            $is_multipart_related = true;
          endif;
          $boundary = "--".$content["boundary"];

//echo "<br>#### boundary = $boundary";

          $p = explode($boundary, $this->body);

//echo "<br>#### p count =".count($p);

          for ($i=0;$i<count($p);$i++) {
//    echo "<br>##### Message =".$p[$i];

            $this->InitMessage($p[$i]);
            $content = $this->ContentType();
            $this->ContentDisposition();

//echo "<br>#### content = ".$content["type"];


            if ($is_multipart_related AND (chop($this->Headers("Content-ID")) != '')) :
              $cont["id"] = ereg_replace("[<>]","", $this->Headers("Content-ID"));
              $cont["name"] = $content["name"];
              $contentid[] = $cont;
              unset($cont);
            endif;
            if (eregi("multipart", $content["type"])) :
              $multiparts[] = $p[$i];

//echo "<br>#### assigning multiparts array";

            elseif (eregi("message", $content["type"])) :
              $messages[] = $p[$i];
            elseif ($this->choose_best AND eregi("text/plain", $content["type"]) AND $is_multipart_alternative  AND !($found_best)) :
              $best = $p[$i];
            elseif ($this->choose_best AND eregi($this->best_format, $content["type"]) AND $is_multipart_alternative ) :
              if (eregi("[[:alpha:]]", chop($p[$i]))) :
                $best = $p[$i];
                $found_best = true;
              endif;
            elseif (chop($content["type"]) != '' AND chop($this->body) !='') :
              $parts[] = $p[$i];

//echo "<br>#### creating parts";

            endif;
            #echo "<pre>($i)###".htmlspecialchars($this->header)."</pre>--###<hr>";
          }
          if (chop($best) != '') :
            $parts[] = $best;
          endif;
        else :
          if (eregi("(message)", $content["type"])) :
            $messages[] = $this->fullmessage;
          elseif (chop($this->body) != '') :
            $parts[] = $this->fullmessage;
          endif;
        endif;
        unset($is_multipart_alternative);
        unset($best);
        unset($found_best);
        if (count($multiparts) > 0) :
          $next_multipart = $this->my_array_shift($multiparts);
          $this->InitMessage($next_multipart);
        endif;
      } while ($next_multipart != "");
        if (chop($parts) != '') :


//echo "<br>#### count of parts = ".count($parts);

          for ($i=0;$i<count($parts);$i++) {;
            $this->InitMessage($parts[$i]);
            $ct = $this->ContentType();
            $cd = $this->ContentDisposition();

            if (eregi("text/html", $ct["type"]) AND count($contentid > 0)) :

              for ($k=0;$k<count($contentid);$k++) {
                $filelocation = $this->attachment_path."/".$contentid[$k]["name"];
                $cid = $contentid[$k]["id"];
                $cid = ereg_replace("[[:space:]]", "", $cid);
                $this->body = str_replace("cid:", "", $this->body);
                $this->body = str_replace($cid, $filelocation, $this->body);
              }
            endif;
            if ($this->auto_decode
              AND eregi("attachment", $cd["type"])
              OR eregi("base64", $this->Headers("Content-Transfer-Encoding"))
              ) :

//echo "<br>#### inside autodecode";

                $filename = chop($ct["name"]) ? $ct["name"] : $cd["filename"];
                if (eregi("base64", $this->Headers("Content-Transfer-Encoding"))) :

//echo "<br>#### inside base64";

                  $file = base64_decode($this->body);
                elseif (eregi("quoted-printable", $this->Headers("Content-Transfer-Encoding"))) :
                  $file = quoted_printable_decode($this->body);
                  $file = ereg_replace("(=\n)", "", $this->body);
                  $file = $this->body;
                elseif (eregi("7bit", $this->Headers("Content-Transfer-Encoding"))) :
                  $file = $this->body;
                endif;

	   global $uid;
	   $md5filename = md5($filename.$uid);
                $filepath = $this->attachment_path.$md5filename;
                @unlink($filepath);
                if (chop($filename != '')) :
                  $fp = @fopen($filepath, "a") OR die("Could'nt download attachment file :  \"$filepath\". Please check if proper write permissions are set for the attachment directory.");
                  fwrite($fp, $file);
                  fclose($fp);
                  if (eregi("attachment", $cd["type"]) OR eregi("inline", $cd["type"])) :
                    #echo "\n<p><a href=\"$filepath\">$filename</a><p>";
                    $decoded_part["attachments"] = $filename;
                  endif;
                endif;
            endif;
            if (eregi("^(text)", $ct["type"] )
                AND !(eregi("text/html", $ct["type"] ))
                AND !(eregi("attachment", $cd["type"] ))
                OR (chop($ct["type"]) == "")
               ) :
              $decoded_part["body"]["type"] = $ct["type"];
              $decoded_part["body"]["body"] = $this->body;
            elseif (eregi("text/html", $ct["type"] ) AND !(eregi("attachment", $cd["type"] ))) :
              $decoded_part["body"]["type"] = $ct["type"];
              $decoded_part["body"]["body"] = $this->body;
              #echo "<pre>($parts_count)###".htmlspecialchars($ct["type"])."</pre>--###<hr>";

            endif;
             $dp[] = $decoded_part;
             unset($decoded_part);
           }

        endif;
        $message[] = $dp;
        unset($dp);
        unset($is_multpart_related);
        unset($contentid);
        unset($parts);
        if (count($messages) > 0) :
          $this->my_array_compact($messages);
          $next_message = $this->my_array_shift($messages);
          $this->InitMessage($next_message);
          $this->InitMessage($this->body);
        endif;
    } while ($next_message != "");
    return $message;
  }
  function MessageID() {
    return ereg_replace("[<>]","",$this->Headers("Message-ID"));
  }
};
?>
Return current item: txtSQL MailBox