<?php



/*	Comments here */



if (!in_array(php_sapi_name(),array('cli','cgi-fcgi')))

	die("Sorry, CLI calls only.");



require_once(dirname(__FILE__)."/common.inc.php");



$ns = @fsockopen($account['hostname'],$account['port_num'],$errno,$errstr,5);

if (!$ns)

	msg("ERROR","Failed to connect to server {$account['hostname']}:{$account['port_num']} (error #$errno: ".trim($errstr).")");

else

{//connected

	$s = fgets($ns,1024);

   	fputs($ns,"user {$account['username']}\n");

	$s = fgets($ns,1024);

   	fputs($ns,"pass {$account['password']}\n");

	$s = fgets($ns,1024);

	if (substr($s,0,3)!="+OK")

		msg("ERROR","Unable to open mailbox: ".trim($s));

	else

	{//logged-in

	

		$rules = rules();



    	fputs($ns,"stat\n");

		$s = fgets($ns,1024);

		list (,$total,) = explode(' ',$s);

		if (!$total)

		{

			if (defined("LOG_NO_MESSAGES") && LOG_NO_MESSAGES)

		    	msg("INFO","No new messages in the mailbox");

		}

		else

		{//some new messages

			for ($j=1;$j<=$total;$j++)

			{

			    fputs($ns,"retr $j\n");

				$raw = "";

				while (($s = fgets($ns,1024))&&(trim($s)!='.'))

				{

					if (!$raw && ($s[0] == '+') ) continue; //+OK octets message, skip it

 					$raw .= $s;

				}



				$headers = array();

				$prev = "";



				$ss = explode ("\n",$raw);

				for ($i=0;$i<count($ss);$i++)

				{

					$s = $ss[$i]."\n";

					if (!trim($s))

						break; //body left



					if (($s[0]==" ")||($s[0]=="\t"))

						$prev .= $s; //header continues

					else

					{

						if ($prev)

							add_parsed_header($headers,$prev);

						$prev = $s;

					}

				}

				add_parsed_header($headers,$prev);



				$body = null;

				for ($i=$i;$i<count($ss);$i++)

				{

					$body .= $ss[$i]."\n";

				}

				$body = trim($body);



				$match = false;



				foreach ($rules as $rule)

				{

					//msg("COMPARE",$rule['incoming']." vs ".$headers['Envelope-to'].' + '.$headers['To']);

					if (there_is_a_match($headers['Envelope-to'], $rule['incoming']) || there_is_a_match($headers['To'], $rule['incoming']))

					{

						$match = true;



						if ($rule['optin'])

							send_optins($rule['incoming'], $headers, $body, $rule['optin']);

						if ($rule['forward'])

							send_forwards($rule['incoming'], $headers, $body, $rule['forward']);



						msg("INFO", $rule['incoming'].' - '.implode(",",$rule['optin']).' - '.implode(",",$rule['forward']) );



						break;

					}

				}



				if (!$match)

				{

					if (defined("ACTION_BOUNCE") && ACTION_BOUNCE)

					{

						$to = extract_address($headers['To']);

						$return = get_reply_to($headers);

						$subject = parse_bounce($bounce['subject'],$to);

						$message = parse_bounce($bounce['message'],$to);

						send_mail($return,$subject,$message,array(),$bounce['headers']);

					}

					msg("WARNING","No match for $to");

				}



				if (defined("ACTION_DELETE") && ACTION_DELETE)

					fputs($ns,"DELE $j\n");



			}

		}

    	fputs($ns,"QUIT\n");

	}

	@fclose($ns);

}

