<?php

$basedir = dirname(__FILE__);

require_once($basedir."/moblog_lib.php");
require_once($basedir."/mail.class.php");

if ($moblog_cfg['use_imap']) {
	if (!function_exists('imap_open')){
		debug("There doesn't seem to be IMAP support in your PHP. " . 
			"Set \$moblog_cfg['use_imap'] to false and try again.");
		exit(1);
	}

	$server = array(
		'type'      => $moblog_cfg['imap_protocol'],
		'server'    => $moblog_cfg['pop_host'],
		'secure'    => $moblog_cfg['imap_secure'],
		'mailbox'   => $moblog_cfg['imap_mailbox'],
		'username'  => $moblog_cfg['pop_user'],
		'password'  => $moblog_cfg['pop_pass']
	);
}

// First we check if the interval has passed, so we can check the mailbox
$skip = false;

$messages = array();

if (file_exists($pivot_path."db/moblogtimer.txt")) {
	$timer = implode("",file($pivot_path."db/moblogtimer.txt"));
	$diff = mktime() - $timer;
	$messages[] = "[diff is: $diff]";

	if ($diff < $moblog_cfg['interval']) {
		$skip = true;
	}

} else {
	$messages[] = "No timer yet: ".$pivot_path."db/moblogtimer.txt";
}


// If skip is not true, we fetch mail..
if (!$skip) {

	$messages[] =  "Checking email..";

	// Create the class and fetch the list of available emails..
	if ($moblog_cfg['use_imap']) {
		$mail = new Mail;
		if (!$mail->connect($server)) {
			debug("Moblog: No connection (using IMAP extension).");
			exit(1);
		} else {
			$messages[] = "Moblog: OK connection (using IMAP extension).\n";
		}
		$mail->parse_messages();
		if (is_array($mail->messages)) {
			$listing = $mail->messages;
		} else {
			$listing = array();
		}
	} else {
	
		$pop3 = new Net_POP3();
		$ret = $pop3->connect($host , $port );
		if (!$ret) {
			debug("Moblog: No connection.");
			exit(1);
		} elseif (PEAR::isError( $ret= $pop3->login($user , $pass,'USER' ) )){
			debug("Moblog: error logging in: " . $ret->getMessage());
			exit(1);
		} else {
			$messages[] = "Moblog: OK connection.\n";
		}
		$listing = $pop3->getListing();
	}

	$messages[] = count($listing)." email found on the server.";
	
	chdir(__WEBLOG_ROOT . "/pivot/");
	require_once("pv_core.php");
	
	$regen = false;

	// Then we iterate through the list..
	foreach ($listing as $list_item) {

		if ($moblog_cfg['use_imap']) {
			$msg_id = $list_item['message_id'];
			$email = $list_item['rawdata'];
		} else {
			$msg_id = $list_item['msg_id'];
			$email = $pop3->getMsg( $msg_id );
		}
		$messages[] = "fetched mail $msg_id";
	
		if (!$moblog_cfg['leave_on_server']) {
			if ($moblog_cfg['use_imap']) {
				$mail->delete($list_item['msgno']);
			} else {
				$pop3->deleteMsg($msg_id);
			}
			$messages[] = "Message was deleted from the server..";
		} else {
			$messages[] = "Message was left on the server (if supported)..";
		}
	
		// Perhaps save a local copy..
		if($moblog_cfg['save_mail']) {
			$filename = __MOBLOG_ROOT.'/mail/' . date("Ymd-His") . "-" . $msg_id . ".eml";
			if ($fp = fopen( $filename, "w" )) {
				fwrite($fp, $email);
				$messages[] = "Local copy saved as: $filename";
				fclose($fp);
			} else {
				$messages[] = "Alas! Woe is me! I couldn't save a local copy.";
			}
	
		}
	
		$entry = array();
	
		// Parse and post the email..
		parse_email($email);
	
		compose_entry();
	
		$regen = true;
	
	}
        
	
	if ($moblog_cfg['use_imap']) {
		$mail->close();
	} else {
		$pop3->disconnect();
	}
	
	if ($regen) {
		// regenerate entry, frontpage and archive..
		generate_pages($Pivot_Vars['piv_code'], TRUE, TRUE, TRUE);
		$messages[] = "Rebuilt the weblog's frontpage..";
	}

	$fp = fopen($pivot_path."db/moblogtimer.txt", "wb");
	fwrite($fp, mktime());
	fclose($fp);

}


$messages[] = "Done!";

$fp = fopen($pivot_path."db/mobloglog.txt", "ab");
fwrite($fp, date("Y-m-d H:i:s")."\n");
fwrite($fp, implode("\n",$messages));
fwrite($fp, "\n\n--------------------------\n\n");
fclose($fp);

?>
