Location: PHPKode > projects > Laikwan WMC > wmc_20070325/imap/index.php
<?

// wmc lib
require_once("../wmcLib/clean.php");
require_once("../wmcLib/mime.php");

// pear mimeDecode
require_once 'Mail/mimeDecode.php';

//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------

function print_folders($server, $user, $pass){
	$mbox = imap_open("{".$server."}", $user, $pass);
	if ($mbox == false) {
		echo "<status>imap_open failed</status>\n";
		return;
	}
	
	$folders = imap_listmailbox($mbox, "{*}", "*");
	if ($folders == false) {
		echo "<status>imap_listmailbox failed</status>\n";
	} else {
		echo "<msgType>folders</msgType>\n";
		asort($folders);
		foreach ($folders as $val) {
			echo "<folder><name>" . substr($val, 3) . "</name></folder>\n";
		}
	}

	imap_close($mbox);

/*	echo "<msgType>folders</msgType>\n";
	foreach($hm->get_folders() as $f) {
		echo (($f->name == 'inbox' || $f->name == 'sentitems' || $f->name == 'deleteditems' || $f->name == 'msnpromo' ||  $f->name == 'bulkmail') 
					? "<box>" : "<folder>"); 
		echo "<name>".$f->name."</name>";
		echo "<unread>".$f->unread."</unread>";
		echo "<total>".$f->visible."</total>";
		echo (($f->name == 'inbox' || $f->name == 'sentitems' || $f->name == 'deleteditems' || $f->name == 'msnpromo' ||  $f->name == 'bulkmail') 
					? "</box>" : "</folder>"); 
		echo "\n";
	}*/

}


//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------


function print_emails($server, $user, $pass, $folder){
	$mbox = imap_open("{".$server."}".$folder, $user, $pass);
	if ($mbox == false) {
		echo "<status>imap_open $folder failed</status>\n";
		return;
	}

	$headers = imap_headers($mbox);
	if ($headers == false) {
		echo "<status>imap_headers $folder failed</status>\n";
	} else {
		echo "<msgType>emails</msgType>\n";
		foreach ($headers as $val) {
			$h = parseImapHeadersString($val);

			echo "<email>\n";
			echo "<url>" . $folder . ';;;' . $h['msgnum'] . "</url>";
			
			$sender = $h['from'] ;
			$subj = $h['subj'] ;
			$size = $h['len'] ;						
			$date = $h['date'] ;						
			if(strpos($h['flags'], 'U') == -1){ // unseen
				$sender = '&lt;b&gt;' . $sender . '&lt;/b&gt;';
				$subj = '&lt;b&gt;' . $subj . '&lt;/b&gt;';
				$date = '&lt;b&gt;' . $date . '&lt;/b&gt;';						
				$size = '&lt;b&gt;' . $size . '&lt;/b&gt;';						
			}
			echo "<sender>" . $sender . "</sender>";
			echo "<subj>" . $subj . "</subj>";
			echo "<date>" . $date . "</date>";
			echo "<size>" . $size . "</size>";
			echo "</email>";

/*
			echo "<email>\n";
			echo "<url>" . urlencode($i->url) . "</url>";
			
			$sender = ($folder=='sentitems' ? "To: " . $i->to : $i->from) ;
			$subj = $i->subject ;
			$size = $i->size  ;						
			$date = $i->date  ;						
			if($i->new){
				$sender = '&lt;b&gt;' . $sender . '&lt;/b&gt;';
				$subj = '&lt;b&gt;' . $subj . '&lt;/b&gt;';
				$date = '&lt;b&gt;' . $date . '&lt;/b&gt;';						
				$size = '&lt;b&gt;' . $size . '&lt;/b&gt;';						
			}
			echo "<sender>" . $sender . "</sender>";
			echo "<subj>" . $subj . "</subj>";
			if($folder!='msnpromo' && $folder!='sentitems'){
				echo "<date>" . $date . "</date>";
			}
			echo "<size>" . $i->size . "</size>";

			print "</email>";
*/
		}
	}
	imap_close($mbox);

}
//-------------------------------------------------------------------

function toMemorySizeStr($num){
	$k = round( $num/1024 ).'KB';
	if($k > 1024){
		return round( $num/1024/1024  ).'MB';
	}
	return $k;
}

//-------------------------------------------------------------------


/*
== full len ==
  F D    1)18-Feb-2006 Lai Kwan Wong        test me (1858 chars)<br />
 U      11)18-Mar-2006 Lai Kwan Wong        Fw: Conv w/ igor and nat (374477 chars)<br />

== parsing after ')' ==
           11                    33                       58 
0123456789=123456789=123456789=123456789=123456789=123456789=123456789=1234
18-Mar-2006 Lai Kwan Wong        Fw: Conv w/ 0123 and 456 (374477 chars)<br />
*/

function parseImapHeadersString($str){
	$arr = array();

	// split by ')' to find msgnum
	$first_close_par = strpos($str, ')');
	$tmp1 = substr($str, 0, $first_close_par); // non-regexp
	$tmp2 = substr($str, $first_close_par+1); // non-regexp
	
	// before ')' 
	preg_match('/^(.+) (\d+)$/', $tmp1, $matches);
	$arr['flags'] = $matches[1];
	$arr['msgnum'] = $matches[2];

	// after ')' 
	$last_open_par = strrpos($tmp2, '(');

//	$arr['date'] = substr($tmp2, 0, 11);
	// date
	$monthsHash = array("Jan"=>"01","Feb"=>"02","Mar"=>"03",
			"Apr"=>"04","May"=>"05","Jun"=>"06",
			"Jul"=>"07","Aug"=>"08","Sep"=>"09",
			"Oct"=>"10","Nov"=>"11","Dec"=>"12");
	$datetime = substr($tmp2, 0, 11);
	$a = explode("-", $datetime);
	$dd  = sprintf("%02d", $a[0]);
	$mm = sprintf("%02d", $monthsHash[$a[1]]); 
	$yy  = $a[2];
	$datetime = $yy."-".$mm."-".$dd;
	$arr['date'] = $datetime;

	$arr['from'] = substr($tmp2, 12, 33-12);
	$arr['subj'] = substr($tmp2, 33, $last_open_par-33);
//	$arr['len']  = toMemorySizeStr( substr($tmp2, $last_open_par+1, strlen($tmp2)-($last_open_par+8) ) );
	$arr['len']  = substr($tmp2, $last_open_par+1, strlen($tmp2)-($last_open_par+8) ) ;

	//print_r($arr);
	return $arr;
}

//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------


function print_msg($server, $user, $pass, $folder, $msgno){

	$mbox = imap_open("{".$server."}".$folder, $user, $pass);
	if ($mbox == false) {
		echo "<status>imap_open $folder failed</status>\n";
		return;
	}

	// create the raw msg
	$mbody = imap_body($mbox, $msgno);
	$mheader = imap_fetchheader($mbox, $msgno);
	$msg = $mheader . $mbody;

	// =========================================
	// todo: might move to common fcn
	// following code is very similar to hail/main.php print_email() 

	// setup mail_mimedecode
	$params['include_bodies'] = true;
	$params['decode_bodies']  = true;
	$params['decode_headers'] = true;
	$decoder = new Mail_mimeDecode($msg);
	$structure = $decoder->decode($params);

	// headers
	$headers = $structure->headers;
	$to = $headers['to'];
	$from = $headers['from'];
	$subject = $headers['subject'];
	$date = $headers['date'];

	print "<msgType>conv</msgType>\n";
	print "<title>" . wmcClean_noHtmlForXmlElt($subject) . "</title>\n";


	print "<msg>\n";
	print "<sender>" . wmcClean_noHtmlForXmlElt($from) . "</sender>\n";
	print "<recv_email>" . wmcClean_noHtmlForXmlElt($to) . "</recv_email>\n";
	print "<date_easy>" . wmcClean_noHtmlForXmlElt($date) . "</date_easy>\n";

	// body
	$bodies = wmcMime_getMainBodyOfMsg($structure);
	if(!$bodies){
		print_r($structure);
	}

	// attachments
	$attached = wmcMime_getAttachmentListOfMsg($structure);
	if($attached != 0){
		for($i = 0 ; $i<count($attached); $i++){
			$url		= "getAttachment.php?mail_url=" . urlencode($_GET['mail_url']) . "&attach_num=" . $attached[$i]['attach_num'];
			$filename	= $attached[$i]['desc'];
			print "<attachment>" .
					"<url>" . wmcClean_noHtmlForXmlElt($url) . "</url>" .
					"<filename>" .  wmcClean_noHtmlForXmlElt($filename) . "</filename></attachment>\n" ;
		}
	}

	if($bodies['html'] && $bodies['plain']){
		print "<html>" . wmcClean_cleanDataForXmlElt($bodies['html']) . "</html>";
		print "<alt_txt>" . wmcClean_cleanDataForXmlElt($bodies['plain']) . "</alt_txt>";
	}else if($bodies['html']){
		print "<html>" . wmcClean_cleanDataForXmlElt($bodies['html']) . "</html>";
	}else if($bodies['plain']){
		print "<html>" . wmcClean_cleanDataForXmlElt($bodies['plain']) . "</html>";
	}

	print "</msg>";

	// end similar code to hail/main.php print_email() 
	// =========================================

	imap_close($mbox);
}

//-------------------------------------------------------------------

function delete_msg($server, $user, $pass, $folder, $msgno){

	$mbox = imap_open("{".$server."}".$folder, $user, $pass);
	if ($mbox == false) {
		echo "<status>imap_open $folder failed</status>\n";
		return;
	}

	// create the raw msg
	$success = imap_delete($mbox, $msgno);
	if ($success === false) {
		echo "<status>imap_delete $msgno failed</status>\n";
	}else{
		$success = imap_expunge($mbox);
		if ($success === false) {
			echo "<status>imap_expunge $msgno failed</status>\n";
		}else{
			echo "<status>success</status>";
		}
	}
	imap_close($mbox);
}


//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------

// headers
header("Content-type: text/xml; charset=utf-8");  // must use text/xml for ajax/xmlhttp to work :(
header("Expires: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

// session
@ini_set("session.use_cookies",	 0);
@ini_set("session.use_trans_sid", 1);					 
session_start();

flush();

echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n";
echo "<root>\n";

//-------------------------------------------------------------------

$server = $_SESSION['imap']['server'] ;
$user = $_SESSION['imap']['user'] ;
$pass = $_SESSION['imap']['pass'] ;


// successful
if (isset($server) && isset($user) && isset($pass)){

	$act = isset($_REQUEST["act"])?$_REQUEST["act"]:"";
	if ($act == 'folders') {
		print_folders($server, $user, $pass);
	} else if($act == 'emails'){
		$folder = $_REQUEST['folder'] ;
		print_emails($server, $user, $pass, $folder);
	} else if($act == 'msg'){
		$msg = $_REQUEST['msg'] ;
		list($folder, $msgno) = split(';;;', $msg) ;
		print_msg($server, $user, $pass, $folder, $msgno);
	} else if($act == 'del'){
		$msg = $_REQUEST['msg'] ;
		list($folder, $msgno) = split(';;;', $msg) ;
		delete_msg($server, $user, $pass, $folder, $msgno);
	} else {
		print "<status>Unknown/unsupported request $act</status>\n";
	}


}else{
	print "<status>Your login expired</status>\n";
}

//-------------------------------------------------------------------

echo "</root>\n";


?>
Return current item: Laikwan WMC