<?php
include('includes/cron_application_top.php');
include(DIR_WS_CLASSES.'class.mail.php');

$accounts = array();
$mailaccounts_query = xtc_db_query("SELECT * FROM email_accounts");
while( $mailaccounts = xtc_db_fetch_array($mailaccounts_query) ){
	$pop = new POP3();
	$decoder = new Mail_Parser;
	if (!$pop->connect($mailaccounts['server'], 110))
		die(print_r($pop->error));
	if (!$pop->login($mailaccounts['username'], $mailaccounts['password']))
	   die(print_r($pop->error));

	$num_msg = $pop->getNumMsgs();
	$emailcount = 0;

	for($i=0;$i<$num_msg;$i++){
		$mail = $pop->getMail( ($i+1) );
		$mail =& $decoder->decode($mail);
		
		$from = $mail->extract_email($mail->getSender());

		$reply_to = $mail->headers['reply-to']['value'];
        if(!empty($reply_to))
        	$from = $mail->extract_email($reply_to);

        $message = '';
		if ($mail->isMultipart()) {
	        while ($part =& $mail->walk()) {
	        	list($main, $sub) = $part->getContentType(true);
	            if ($part->getHeader('content-disposition') == 'attachment') {
	               		//$name = $part->getFileName();
	               		//$name = saveFile($part->getMessage(), $name);
	               		//echo 'Attachment: <b><a href="files/'.$name.'">'.$name.'</a></b><br>';
	            } else {
	            	if ($main == 'text' or $main == 'message') {
	            		$message = $part->getMessage();
	                }
	            }
	       	}
	       	if($message == '')
	       		$message = "[SYSTEM:] ".YES_MAIL_WITH_ATTACHMENTS;
	    } else {
	       	$message = $mail->getMessage();
	    }

    	if(strlen($mail->getMessageId())>3){
    		$double_check_query = xtc_db_query(sprintf("SELECT emails_id FROM emails WHERE messageid='%s' and recipient='%s'",$mail->getMessageId(),$mailaccounts['email_address']));
    		if(!xtc_db_num_rows($double_check_query)){
	    		$insert_sql_array = array(
	    			'recipient'=>$mailaccounts['email_address'],
	    			'from_name'=>$from['name'],
	    			'from_email'=>$from['email'],
	    			'body'=>$message,
	    			'messageid'=>$mail->getMessageId(),
	    			'date_saved'=>'now()',
	    			'subject'=>$mail->getSubject(),
	    			'own_mail'=>0,
	    			'customers_id'=>0,
	    			'editor'=>0,
	    			'reply_id'=>0
	    		);
	    		xtc_db_perform('emails',$insert_sql_array);
    		} // end if doublecheck
    	}
	} // end for emails in pop

	if(DELETE_EMAILS_AFTER_SAVE == 'True'){
		for($i=0;$i<$num_msg;$i++){
			$pop->delMsg(($i+1));
		}
	}

	$pop->close();
}
exit;
?>
