<?php

/* Just add ur incoming mail server address and type of port in connection string then use corresponding functions to
fetch body and attachments
*/
class receiveMail
{
	var $server='networds.datatask.net';
	var $username='raporty+networds.datatask.net';
	var $password='zzX2lzI-=&>L';
	var $marubox='mail.networds.datatask.net';					
	var $email='raporty@networds.datatask.net';
				
function receiveMail() //Constructure
{
	
	$strConnect="{localhost:110/pop3/notls}INBOX";
	
	$this->server			=	$strConnect;
	/*$this->username			=	$username;
	$this->password			=	$password;
	$this->email			=	$EmailAddress;*/
}



function connect($name,$pass) //Connect To the Mail Box
{

	$host1= "{localhost:110/pop3/notls}INBOX";
	$this->marubox=imap_open($host1,$name,$pass);
	return $this->marubox;
}

function GetAttech($mid,$path=null) // Get Atteced File from Mail
{
	$struckture = imap_fetchstructure($this->marubox,$mid);	
	$ar="";
	foreach($struckture->parts as $key => $value)
	{
		$enc=$struckture->parts[$key]->encoding;
		if($struckture->parts[$key]->ifdparameters)
		{
			$name=$struckture->parts[$key]->dparameters[0]->value;
			$message = imap_fetchbody($this->marubox,$mid,$key+1);
			if ($enc == 0)
			$message = imap_8bit($message);
			if ($enc == 1)
			$message = imap_8bit ($message);
			if ($enc == 2)
			$message = imap_binary ($message);
			if ($enc == 3)
			$message = imap_base64 ($message); 
			if ($enc == 4)
			$message = quoted_printable_decode($message);
			if ($enc == 5)
			$message = $message;			
			
			return $message;
			
			//$fp=fopen($path.$name,"r");
			//fwrite($fp,$message);
			//fclose($fp);
			//$ar=$ar.$name.",";
		}
	}
	//$ar=substr($ar,0,(strlen($ar)-1));
	//return $ar;
}
function getHeaders($mid) // Get Header info
{
	$mail_header=imap_header($this->marubox,$mid);
	$sender=$mail_header->from[0];
	$sender_replyto=$mail_header->reply_to[0];
	if(strtolower($sender->mailbox)!='mailer-daemon' && strtolower($sender->mailbox)!='postmaster')
	{
		@$mail_details=array(
				'from'=>strtolower($sender->mailbox).'@'.$sender->host,
				'fromName'=>$sender->personal,
				'toOth'=>strtolower($sender_replyto->mailbox).'@'.$sender_replyto->host,
				'toNameOth'=>$sender_replyto->personal,
				'subject'=>$mail_header->subject,
				'to'=>strtolower($mail_header->toaddress)
			           );
	}
	return $mail_details;
}

function get_mime_type(&$structure) //Get Mime type Internal Private Use
{ 
	$primary_mime_type = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER"); 
		
	if($structure->subtype) { 
			return $primary_mime_type[(int) $structure->type] . '/' . $structure->subtype; 
			} 
			return "TEXT/PLAIN"; 
} 

function get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false) //Get Part Of Message Internal Private Use
{ 
	if(!$structure) { 
			$structure = imap_fetchstructure($stream, $msg_number); 
		    } 
	if($structure) { 
			if($mime_type == $this->get_mime_type($structure))
			{ 
				if(!$part_number) 
				{ 
					$part_number = "1"; 
				} 
				$text = imap_fetchbody($stream, $msg_number, $part_number); 
				if($structure->encoding == 3) 
				{ 
					return imap_base64($text); 
				} 
				else if($structure->encoding == 4) 
				{ 
					return imap_qprint($text); 
				} 
				else
				{ 
					return $text; 
				} 
			} 
			if($structure->type == 1) /* multipart */ 
			{ 
				while(list($index, $sub_structure) = each($structure->parts))
				{ 
					if($part_number)
					{ 
						$prefix = $part_number . '.'; 
					} 
					$data = $this->get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1)); 
					if($data)
					{ 
						return $data; 
					} 
				} 
			} 
		} 
		return false; 
	} 
function getTotalMails() //Get Total Number off Unread Email In Mailbox
{
	$headers=imap_headers($this->marubox);
	$cnt=count($headers);
	if($cnt>100)
	{
		return(100);
	}
	else
	{
		return count($headers);
	}
}

function getBody($mid) // Get Message Body
{
	$body = $this->get_part($this->marubox, $mid, "TEXT/HTML");
	if ($body == "")
	$body = $this->get_part($this->marubox, $mid, "TEXT/PLAIN");
	if ($body == "") { 
			return "";
		       }
		
	return $body;
}

function deleteMails($mid) // Delete That Mail
{
	imap_delete($this->marubox,$mid) or die('Could Not Execute Mail Delete Operation');	
	imap_expunge($this->marubox);
}

function nomsg()
{

	$chk=imap_status($this->marubox, "{localhost:110/pop3/notls}INBOX", SA_ALL);

	if($chk)
	{
		return($chk->messages);
	}
}

function close_mailbox() //Close Mail Box
{
	imap_close($this->marubox,CL_EXPUNGE);
}

function check_attachment($mid)
{
  	$struct = imap_fetchstructure($this->marubox, $mid);
    print_r($struct);   
	$parts = $struct->parts;

	$i = 0;

	if (!$parts)
	{ 
			/* Simple message, only 1 piece */
          			$attachment = array(); /* No attachments */
          			$content = imap_body($this->marubox, $mid);
	} 
	else
	{
			 /* Complicated message, multiple parts */
                 			$endwhile = false;
                 			$stack = array(); /* Stack while parsing message */
                  		$content = "";    /* Content of message */
          			$attachment = array(); /* Attachments */
       
            			while (!$endwhile) 
           			{
           	 		if (!$parts[$i]) 
			{
              				if (count($stack) > 0) 
				{
                					$parts = $stack[count($stack)-1]["p"];
                					$i     = $stack[count($stack)-1]["i"] + 1;
                					array_pop($stack);
              				} 
			else{
                				$endwhile = true;
              		      	       }
            		}
         
            		if (!$endwhile) 
		{

              			/* Create message part first (example '1.2.3') */

              			$partstring = "";

              			foreach ($stack as $s) {
                						$partstring .= ($s["i"]+1) . ".";
              		            			}
              					$partstring .= ($i+1);
           
              				if (strtoupper($parts[$i]->disposition) == "ATTACHMENT") 
              				{
	 				/* Attachment */
			//$attachment[] = array("filename" =>$parts[$i]->parameters[0]->value,"filedata" => imap_fetchbody($mbox, $mid,$partstring));
		$attachment=array("filename" =>$parts[$i]->parameters[0]->value,"filedata" => imap_fetchbody($this->marubox, $mid,$partstring));

              				}
            			}

            		if ($parts[$i]->parts) 
           		{
              			$stack[] = array("p" => $parts, "i" => $i);
              			$parts = $parts[$i]->parts;
              			$i = 0;
            		} 
            		else {
              			$i++;
                   	      }
          	} /* while */
        	} /* complicated message */

	if($attachment['filename']=='')
	{
		return(0);
	}
	else
	{
		return($attachment['filename']);
	}		

	}

	function read_attachment($mid)
	{

		$struct = imap_fetchstructure($this->marubox, $mid);

       	 	$parts = $struct->parts;

	        	$i = 0;

	        	if (!$parts)
       		{ 
			/* Simple message, only 1 piece */
          			$attachment = array(); /* No attachments */
          			$content = imap_body($this->marubox, $mid);
        		} 
       		else
         		{
			 /* Complicated message, multiple parts */
                 			$endwhile = false;
                 			$stack = array(); /* Stack while parsing message */
                  		$content = "";    /* Content of message */
          			$attachment = array(); /* Attachments */
       
            		while (!$endwhile) 
           		{
           	 		if (!$parts[$i]) 
			{
              				if (count($stack) > 0) 
				{
                					$parts = $stack[count($stack)-1]["p"];
                					$i     = $stack[count($stack)-1]["i"] + 1;
                					array_pop($stack);
              				} 
				else{
                					$endwhile = true;
              		      	       	      }
            		}
         
            		if (!$endwhile) {

              		/* Create message part first (example '1.2.3') */

              		$partstring = "";

              		foreach ($stack as $s) {
                					$partstring .= ($s["i"]+1) . ".";
              		            		}
              				$partstring .= ($i+1);
           
              				if (strtoupper($parts[$i]->disposition) == "ATTACHMENT") 
              				{
	 				/* Attachment */
			//$attachment[] = array("filename" =>$parts[$i]->parameters[0]->value,"filedata" => imap_fetchbody($mbox, $mid,$partstring));
		$attachment=array("filename" =>$parts[$i]->parameters[0]->value,"filedata" => imap_fetchbody($this->marubox, $mid,$partstring));

              				}
              				elseif (strtoupper($parts[$i]->subtype) == "PLAIN")
             				{ 
					/* Message */
                 					$content .= imap_fetchbody($this->marubox, $mid, $partstring);
              				}
            			}

            			if ($parts[$i]->parts) 
           			{
              				$stack[] = array("p" => $parts, "i" => $i);
              				$parts = $parts[$i]->parts;
              				$i = 0;
            			} 
            			else {
              				$i++;
                   	      	      }
          	} /* while */
        	} /* complicated message */

        	$str=$attachment['filedata'];
	$file=explode(".",$attachment['filename']);

        	$str1=imap_base64($str);
	$file=explode('.',$attachment['filename']);


	$file_path=__FILE__;

	$filepath=explode("class.php",$file_path);

	$doc='test.doc';

	$doc1='textFile.txt';

	$filepath1=$filepath[0].$doc;

	$filepath2=$filepath[1].$doc1;


	if($file[1]=='doc')
	{
		$textFile='test.doc';
		$handle = fopen($textFile, 'w'); 
		fwrite($handle, $str1); 	
		fclose($handle);
		receiveMail::wordToText($filepath1,$filepath2);
	}

	if($file[1]=='rtf')
	{
		$textFile='test.doc';
		$handle = fopen($textFile, 'w'); 
		fwrite($handle, $str1); 	
		fclose($handle);
		receiveMail::wordToText($filepath1,$filepath2);
	}

	if($file[1]=='html')
	{
		$myFile = "sample_html.htm";

		$fh = fopen($myFile, 'w') or die("can't open file");

		$stringData = $str1;

		fwrite($fh, $stringData);

		fclose($fh);

		require_once('class.html2text.inc');

		$filename = 'sample_html.htm';

		$h2t =& new html2text($filename, true);

		$h2t->set_base_url('http://www.example.com');

		$text = $h2t->get_text();

		$myFile = "textFile.txt";

		$fh = fopen($myFile, 'w') or die("can't open file");

		$stringData = $text;

		fwrite($fh, $stringData);

		fclose($fh);

		//receiveMail::filewrite('textFile.txt',$text);
	}

	if($file[1]=='csv')
	{
		$f=fopen('textFile.txt','w');
		fwrite($f,$str1);
		fclose($f);
	}
	
	if($file[1]=='pdf')
	{
		//include('attachmentread.class.php');
		receiveMail::getdata($mid);	
		//include('test2.php');
		$str=receiveMail::pdf2string($attachment['filename']);
		$f=fopen('textFile.txt','w');
		fwrite($f,$str);
		fclose($f);
		unlink($attachment['filename']);
	}

	if($file[1]=='txt')
	{
		$f=fopen('textFile.txt','w');
		fwrite($f,$str1);
		fclose($f);				
	}
}


function wordToText($wordDocPath,$textFilePath)
{
	$word = new COM("word.application") or die("Unable to instanciate Word"); 
	$word->Visible = 0; 
	$word->Documents->Open($wordDocPath);
	$numParagraphs = $word->ActiveDocument->Paragraphs->Count;
	$paraString = ''; 
	for($i = 1; $i <= $numParagraphs; $i++)
	{
		$paraString .= $word->ActiveDocument->Paragraphs[$i];
	} 
	$word->Quit();
 	$handle = fopen($textFilePath, 'w'); 
	fwrite($handle, $paraString); 	
	fclose($handle);
}

function getdecodevalue($message,$coding)
{
	if ($coding == 0) 
	{ 
   		$message = imap_8bit($message); 
	} 
	elseif ($coding == 1) 
	{ 
  		$message = imap_8bit($message); 
	} 
	elseif ($coding == 2) 
	{ 
   		$message = imap_binary($message); 
	} 
	elseif ($coding == 3) 
	{ 
		$message=imap_base64($message); 
	} 
	elseif ($coding == 4) 
	{ 
   		$message = imap_qprint($message); 
	} 
	elseif ($coding == 5) 
	{ 
 		$message = imap_base64($message); 
	}
	return $message;
}


function getdata($id)
{
	$message = array();
	$message["attachment"]["type"][0] = "text";
	$message["attachment"]["type"][1] = "multipart";
	$message["attachment"]["type"][2] = "message";
	$message["attachment"]["type"][3] = "application";
	$message["attachment"]["type"][4] = "audio";
	$message["attachment"]["type"][5] = "image";
	$message["attachment"]["type"][6] = "video";
	$message["attachment"]["type"][7] = "other";
			
	//for ($jk = 1; $jk <= imap_num_msg($mbox); $jk++)
	//{
	$jk=$id;
	$structure = imap_fetchstructure($this->marubox, $jk , FT_UID);    
	$parts = $structure->parts;
	$fpos=2;
	for($i = 1; $i < count($parts); $i++)
	{
		$message["pid"][$i] = ($i);
		$part = $parts[$i];
		if($part->disposition == "ATTACHMENT") 
		{
							
		$message["type"][$i] = $message["attachment"]["type"][$part->type] . "/" .strtolower($part->subtype);
		$message["subtype"][$i] = strtolower($part->subtype);
		$ext=$part->subtype;
		$params = $part->dparameters;
		$filename=$part->dparameters[0]->value;
		$mege="";
		$data="";
		$mege = imap_fetchbody($this->marubox,$jk,$fpos);  
		$filename="$filename";
		$fp=fopen($filename,w);
		$data=receiveMail::getdecodevalue($mege,$part->type);	
		fputs($fp,$data);
		fclose($fp);
		$fpos+=1;
		}
	}
		imap_close($this->marubox);
}

function pdf2string($sourcefile) 
{

	$fp = fopen($sourcefile, 'rb');
	$content = fread($fp, filesize($sourcefile));
	fclose($fp);
	$searchstart = 'stream';
	$searchend = 'endstream';
	$pdfText = '';
	$pos = 0;
	$pos2 = 0;
	$startpos = 0;

	while ($pos !== false && $pos2 !== false) 
	{

		$pos = strpos($content, $searchstart, $startpos);
        		$pos2 = strpos($content, $searchend, $startpos + 1);
        		if ($pos !== false && $pos2 !== false){
						if ($content[$pos] == 0x0d && $content[$pos + 1] == 0x0a) {
                						$pos += 2;
            					     }
		else if ($content[$pos] == 0x0a) {
                					$pos++;
            				              }
	            	if ($content[$pos2 - 2] == 0x0d && $content[$pos2 - 1] == 0x0a) {
                								$pos2 -= 2;
            							               }
		 else if ($content[$pos2 - 1] == 0x0a) {
                						$pos2--;
            					    }

            		$textsection = substr(
                		$content,
                		$pos + strlen($searchstart) + 2,
               	 	$pos2 - $pos - strlen($searchstart) - 1
            		);
            		$data = @gzuncompress($textsection);
            		$pdfText .=receiveMail::pdfExtractText($data);
            		$startpos = $pos2 + strlen($searchend) - 1;

        	}
    }
    	return preg_replace('/(\s)+/', ' ', $pdfText);
  }

 function pdfExtractText($psData)
{
	if (!is_string($psData))
	{
		return '';
	}
	$text = '';
	// Handle brackets in the text stream that could be mistaken for
	// the end of a text field. I'm sure you can do this as part of the
	// regular expression, but my skills aren't good enough yet.
	$psData = str_replace('\)', '##ENDBRACKET##', $psData);
	$psData = str_replace('\]', '##ENDSBRACKET##', $psData);
	preg_match_all(
		'/(T[wdcm*])[\s]*(\[([^\]]*)\]|\(([^\)]*)\))[\s]*Tj/si',
		$psData,
		$matches
		   );
                 for ($i = 0; $i < sizeof($matches[0]); $i++)
	{
        		if ($matches[3][$i] != '')
		{
            			// Run another match over the contents.
            			preg_match_all('/\(([^)]*)\)/si', $matches[3][$i], $subMatches);
            			foreach ($subMatches[1] as $subMatch) 
			{
                				$text .= $subMatch;
            			}
        		}
		else if ($matches[4][$i] != '')
		{
            			$text .= ($matches[1][$i] == 'Tc' ? ' ' : '') . $matches[4][$i];
        		}
    	}

    	// Translate special characters and put back brackets.
    	$trans = array(
        			'...'                => '…',
        			'\205'                => '…',
        			'\221'                => chr(145),
        			'\222'                => chr(146),
        			'\223'                => chr(147),
        			'\224'                => chr(148),
        			'\226'                => '-',
        			'\267'                => '•',
        			'\('                => '(',
        			'\['                => '[',
        			'##ENDBRACKET##'    => ')',
        			'##ENDSBRACKET##'    => ']',
        			chr(133)            => '-',
        			chr(141)            => chr(147),
        			chr(142)            => chr(148),
        			chr(143)            => chr(145),
        			chr(144)            => chr(146),
    		);
    		$text = strtr($text, $trans);
  		return $text;
}

function filewrite($fname,$str)
{
	$f=fopen($fname,'w') or die('Cant open Text File');
	fwrite($f,$str);
	fclose($f);
}

function signout()
{
	unset($_SESSION['name']);

	unset($_SESSION['pass']);

	session_destroy();

	$myFile = "testFile.txt";

	$stringData="";
	
	$fh = fopen($myFile, 'w') or die("can't open file");
	
	$stringData = $body;
	
	fwrite($fh, $stringData);
	
	fclose($fh);
}

function validate_email(	$eml_id)
{
	if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $eml_id)) 
	{
		echo"<font size='2' face='Verdana'>"."Invalid Email_id at".$eml_id."</font>";
	}
}

function sendMail( $from, $to, $body, $subject, $cc,$bcc,$contentType = "text/plain", $charset = "iso-8859-9" )
{
    	    	ini_set("sendmail_from", $from);

    		$headers  = "MIME-Version: 1.0\r\n";

		$headers .= "Content-type: $contentType; charset=$charset\r\n";

		receiveMail::validate_email($to);
   
   		 if( $cc != "" )
    		{
			receiveMail::validate_email($cc);
		        	$headers .= "Cc:  $cc\r\n";
    		}
    		if( $bcc != "" )
    		{
		       receiveMail::validate_email($bcc);	
		        $headers .= "Bcc: $bcc\r\n";
    		}
   
    		$headers .= "From: $from\r\n";

    		$headers .= "To: $to\r\n";

    		if(mail ($to, $subject, $body, $headers ))
		return 1;
		else
		return 0; 
}

function replyMail( $from, $to, $body, $subject, $cc,$bcc,$contentType = "text/plain", $charset = "iso-8859-9" )
{
    	    	ini_set("sendmail_from", $from);

    		$headers  = "MIME-Version: 1.0\r\n";

		$headers .= "Content-type: $contentType; charset=$charset\r\n";

		receiveMail::validate_email($to);
   
   		 if( $cc != "" )
    		{
			receiveMail::validate_email($cc);
		        	$headers .= "Cc:  $cc\r\n";
    		}
    		if( $bcc != "" )
    		{
		       receiveMail::validate_email($bcc);	
		        $headers .= "Bcc: $bcc\r\n";
    		}
   
    		$headers .= "From:$from\r\nReply-To:$to";

    		if(mail ($to, $subject, $body, $headers ))
		return 1;
		else
		return 0; 
}

function forwardMail( $from, $to, $body, $subject, $cc,$bcc,$contentType = "text/plain", $charset = "iso-8859-9" )
{
    	    	ini_set("sendmail_from", $from);

    		$headers  = "MIME-Version: 1.0\r\n";

		$headers .= "Content-type: $contentType; charset=$charset\r\n";

		receiveMail::validate_email($to);
   
   		 if( $cc != "" )
    		{
			receiveMail::validate_email($cc);
		        	$headers .= "Cc:  $cc\r\n";
    		}
    		if( $bcc != "" )
    		{
		       receiveMail::validate_email($bcc);	
		        $headers .= "Bcc: $bcc\r\n";
    		}
   
    		$headers .= "From:$from\r\nForward-To:$to";

    		if(mail ($to, $subject, $body, $headers))
		return 1;
		else
		return 0; 
}

function mail_attach_send($fname,$from,$to,$body,$subject, $cc,$bcc)
{

		ini_set("sendmail_from", $from);

		$fileatt = $fname; // Path to the file
		$fileatt_type = "application/octet-stream"; // File Type
		$fileatt_name = $fname; // Filename that will be used for the file as the attachment

		$email_from = $from; // Who the email is from
		$email_subject = $subject; // The Subject of the email
		$email_txt = $body; // Message that the email has in it

	
		if(!$cc=="")
		{		
			$headers .= "Cc:  $cc\r\n";
		}

		if(!$bcc=="")
		{
			$headers .= "Bcc: $bcc\r\n";

		}

		$headers .= "From: $from\r\n";

    		$headers .= "To: $to\r\n";

		$headers = "From: ".$email_from;

		$file = fopen($fileatt,'rb');
		$data = fread($file,filesize($fileatt));
		fclose($file);

		$semi_rand = md5(time());
		$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

		$headers .= "\nMIME-Version: 1.0\n" .
		"Content-Type: multipart/mixed;\n" .
		" boundary=\"{$mime_boundary}\"";

		$email_message .= "This is a multi-part message in MIME format.\n\n" .
		"--{$mime_boundary}\n" .
		"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
		"Content-Transfer-Encoding: 7bit\n\n" .
		$email_message . "\n\n";

		$data = chunk_split(base64_encode($data));

		$email_message .= "--{$mime_boundary}\n" .
		"Content-Type: {$fileatt_type};\n" .
		" name=\"{$fileatt_name}\"\n" .
		//"Content-Disposition: attachment;\n" .
		//" filename=\"{$fileatt_name}\"\n" .
		"Content-Transfer-Encoding: base64\n\n" .
		$data . "\n\n" .
		"--{$mime_boundary}--\n";

		$ok =@mail($to, $email_subject, $email_message, $headers);
		if($ok)
		{
			echo "<font face=verdana size=2>The file was successfully sent!</font>";
		} 
		else 
		{
			die("Sorry but the email could not be sent. Please go back and try again!");
		}
}	

function insert_sqlite($frm,$to,$cc,$bcc,$sub,$msg)
{
		$db=sqlite_open('sqlite/sent1.sqlite');
		sqlite_query($db, "INSERT INTO sentitems (id,frm,to,cc,bcc,sub,msg) VALUES (NULL,'$frm','$to','$cc','$bcc','$sub','$msg')");
}

}
?>