<?
//   XUL Webmail, a web based mailclient
//
//   Copyright (C) 2004 Wouter van Wijk (wvw a@t dds.nl),
//
//   This program is free software; you can redistribute it and/or modify
//   it under the terms of the GNU General Public License as published by
//   the Free Software Foundation; either version 2 of the License, or
//   (at your option) any later version.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program; if not, write to the Free Software
//   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//

include('global.php');

$imap_trash = 'INBOX.Trash';
$imap_drafts = 'INBOX.Drafts';
$imap_sent = 'INBOX.Sent';



function deleteMessage($mailbox, $idarray) {
//	moveMessage($mailbox, 'INBOX.Trash', $idarray);
	$mbox = imap_open($_SESSION['server'].$mailbox, $_SESSION['user'], $_SESSION['pass']) or die("can't connect: ".imap_last_error());
	//get correct message id's
//	$newidarray = array();
//	foreach ($idarray as $val) {
		$newid = imap_msgno($mbox, $idarray);
		imap_delete($mbox, $newid);
		imap_expunge($mbox);
		imap_close($mbox);
}

function moveMessageToTrash($mailbox, $idarray) {
// Well... just guess
// strange: if I use $imap_trash here, it won't work
// don't call me stupid, Wanda!

	if ($mailbox == 'INBOX.Trash') {
		deleteMessage($mailbox, $idarray);
	} else {
		copymoveMessage($mailbox, 'INBOX.Trash', $idarray, 'move');
	}
}

function copymoveMessage($sourcemailbox, $targetmailbox, $idarray, $action) {
//	move a message to another folder
//		echo $sourcemailbox.'-'.$targetmailbox.'-'.$idarray;
	if($sourcemailbox != $targetmailbox) {
		$mbox = imap_open($_SESSION['server'].$sourcemailbox, $_SESSION['user'], $_SESSION['pass']) or die("can't connect: ".imap_last_error());
		//get correct message id's
//		$newidarray = array();
//		foreach ($idarray as $val) {
			$newid = imap_msgno($mbox, $idarray);
//			$newidarray[] = $newid;
//			echo $idarray.'-'.$newid;
//			echo $idarray.'-'.$newid;
//		}
		if ($action == 'copy') {
			$result = imap_mail_copy($mbox, $idarray, $targetmailbox, CP_UID);
		} else {
			$result = imap_mail_move($mbox, $idarray, $targetmailbox, CP_UID);
		}
//		echo imap_last_error();
		$result = imap_expunge($mbox);
//		echo $result;
//		echo imap_last_error();
		imap_close($mbox);
	}
}

function getMailboxes () {
	/*
	Gets mailboxes from imap/pop3 address

	Puts the values in the mailbox result array, which in turn is processed to rdf by mailboxlist.php

	*/
	$mailboxlist = array ();

	$mbox = imap_open($_SESSION['server'], $_SESSION['user'], $_SESSION['pass'], OP_HALFOPEN) or die("can't connect: ". $_SESSION['server'] . ' '.$_SESSION['user']. '. Error: ' .imap_last_error());

	$list = imap_getmailboxes($mbox, $_SESSION['server'], "*");
	$i = 0;
//	sort($list);
	foreach($list as $val) {
		$name = $val->name;

		//remove server bits
		$name = ereg_replace($_SESSION['server'], '', $name);

		$mailboxlist[$i]['id'] = $name;
		$mailboxlist[$i]['name'] = $name;
		$mailboxlist[$i]['childof'] = 0;
		$i++;
	}

	imap_close($mbox);

	//build the childof tree
	$resultlist = array ();
	foreach($mailboxlist as $val) {
		$name = $val['name'];
		$pos = strrpos($name, '.');
		$childof = -1;
    		if ($pos == true) {
			$parent = substr($name, 0, $pos);
			$name = substr($name, $pos - strlen($name) + 1 );
			foreach($mailboxlist as $val2) {
				$name2 = $val2['name'];
				if($name2 == $parent) {
						$childof = $val2['id'];
						break;
				}
			}
		}
		$val['name'] =  $name;
		$val['childof'] =  $childof;
		$resultlist[] = $val;
	}
	return $resultlist;
}

function getaMessage($mailbox, $id) {
	/*
	Gets a message from imap/pop3
	*/
	$mbox = imap_open($_SESSION['server'].$mailbox, $_SESSION['user'], $_SESSION['pass']) or die("can't connect: ".imap_last_error());
	$newid = imap_msgno($mbox, $id);
//	echo $mailbox.'-'.$newid.'-'.$id.'-'.imap_last_error()."<br/>\n";
	$headers = imap_header($mbox, $newid);
	$body = nl2br(htmlspecialchars(stripslashes(trim(imap_body($mbox, $newid)))));
//	$structure = imap_fetchstructure($mbox, $id);
	imap_close($mbox);
	return( $body );
}

function getMessages($mailbox, $fromid, $maxnumber) {
	/*
	Gets messages from imap/pop3

	Puts the values in the messagelist result array, which in turn is processed to rdf by messagelist.php
	fromid and maxnumber are values to control which and the number of messages

	*/
	$messagelist = array ();
	$mbox = imap_open($_SESSION['server'].$mailbox, $_SESSION['user'], $_SESSION['pass']) or die("can't connect:".imap_last_error().'-'.$_SESSION['user'].'-'.$_SESSION['server']);

	// get total number of messages
	$totalmsg = imap_num_msg($mbox);
	//print $totalmsg;
	$until = $totalmsg - 10;

	//temporary limit
	if ($until < 0) { $until = 0; }

	// iterate through messages
	for($i=$totalmsg; $i>$until; $i--) {
		// get header and structure
		$headers = imap_header($mbox, $i);
		$structure = imap_fetchstructure($mbox, $i);

		// correction for empty subject
		if ($headers->Subject == "") {
			$messagelist[$i]['subject'] = "No subject";
		}
		else {
			$messagelist[$i]['subject'] = $headers->Subject;//.' - '.imap_uid($mbox, $i);
		}
		$messagelist[$i]['date'] = $headers->Date;
		$messagelist[$i]['id'] = imap_uid($mbox, $i);
		$messagelist[$i]['fromaddress'] = substr($headers->fromaddress,0,100);
	}
	imap_close($mbox);
	return $messagelist;
}

function getMessageSource($mailbox, $id) {
// Gets a the source of a message from imap/pop3
	$mbox = imap_open($_SESSION['server'].$mailbox, $_SESSION['user'], $_SESSION['pass']) or die("can't connect: ".imap_last_error());
	$newid = imap_msgno($mbox, $id);
	$headers = imap_fetchheader($mbox, $newid);
	$body = imap_body($mbox, $newid);
	$source = $headers."\n".$body;
//	$structure = imap_fetchstructure($mbox, $id);
	imap_close($mbox);
	return( $source );
}

function makeServerString ($server, $port, $protocol, $usessl) {
//create the server string with which the backend can work
	$server = $server .':'.$port;
	if ($usessl) {
		$server = $server . '/ssl';
	}
	if ($pop3) {
		$server = $server . '/pop3';
	}
	return('{' . $server .'}');
}

function moveFolder($folder, $target) {
	//move a folder
}

function emptyTrash() {
	$mbox = imap_open($_SESSION['server'].'INBOX.Trash', $_SESSION['user'], $_SESSION['pass']) or die("can't connect: ".imap_last_error());

	// get total number of messages
	$totalmsg = imap_num_msg($mbox);
//	echo $totalmsg.$imap_trash.imap_last_error();
	// iterate through messages
	for($i=0; $i <= $totalmsg; $i++) {
		imap_delete($mbox, $i);
	}
	imap_expunge($mbox);
	imap_close($mbox);
	return (imap_last_error() . '-'.$totalmsg);
}

function createMailbox ($inmailbox, $name) {
	$mbox = imap_open($_SESSION['server'].$imap_trash, $_SESSION['user'], $_SESSION['pass']) or die("can't connect: ".imap_last_error());
	imap_createmailbox($mbox, imap_utf7_encode($_SESSION['server'].$inmailbox.'.'.$name));
	imap_close($mbox);
	return (imap_last_error());
}

function deleteMailbox ($name) {
	$mbox = imap_open($_SESSION['server'].$imap_trash, $_SESSION['user'], $_SESSION['pass']) or die("can't connect: ".imap_last_error());
	imap_deletemailbox($mbox, imap_utf7_encode($_SESSION['server'].$name));
	imap_close($mbox);
	return (imap_last_error());
}

function renameMailbox ($oldname, $newname) {
	$mbox = imap_open($_SESSION['server'].$imap_trash, $_SESSION['user'], $_SESSION['pass']) or die("can't connect: ".imap_last_error());
	imap_renamemailbox($mbox, imap_utf7_encode($_SESSION['server'].$oldname), imap_utf7_encode($_SESSION['server'].$newname));
	imap_close($mbox);
	return (imap_last_error());
}

?>
