<?php
// +-------------------------------------------------------------+
// | HiveMail™ version 1.3.1
// +-------------------------------------------------------------+
// | HIVEMAIL™ IS NOT FREE SOFTWARE
// | If you have downloaded this software from a website other
// | than Hivemail or if you have otherwise received
// | this software from someone who is not a representative of
// | this organization you are involved in an illegal activity.
// +-------------------------------------------------------------+
// | $RCSfile: win.monitor.php,v $ - $Revision: 1.17 $
// | $Date: 2004/08/03 04:28:44 $ - $Author: tubedogg $
// +-------------------------------------------------------------+
error_reporting(E_ALL & ~E_NOTICE);
define('ALLOW_LOGGED_OUT', true);
define('SKIP_POP', true);
define('SKIP_SKIN', true);
$templatesused = '';
require_once('./global.php');
header('Content-type: application/xml');

// ############################################################################
// The lowest checking rate that is allowed, in minutes. If this is set to 2, for
// example, users will not be able to configure HiveMonitor to check every minute.
$minrate = 1;
// Default: 1

// ############################################################################
// Log user in
if (empty($_REQUEST['username']) or empty($_REQUEST['password']) or strlen($_REQUEST['password']) != 32) {
	echo 'Incorrect Login';
	exit;
} else {
	$hiveuser = $DB_site->query_first('
		SELECT *
		FROM hive_user
		LEFT JOIN hive_usergroup USING (usergroupid)
		WHERE username = "'.addslashes($_REQUEST['username']).'"
	');
	if (!$hiveuser or (empty($format) and !($hiveuser['perms'] & GROUP_CANUSEMONITOR)) or (!empty($format) and !($hiveuser['perms'] & GROUP_CANUSEFEEDMON)) or $hiveuser['password'] != $_REQUEST['password']) {
		echo 'Incorrect Login';
		exit;
	}
	$hiveuser = decode_user_options($hiveuser, false);
}

// ############################################################################
// Get folders information, message counts and unread messages
$newmsgs = $DB_site->query_first("
	SELECT COUNT(*) AS count
	FROM hive_message
	WHERE userid = $hiveuser[userid]
	AND dateline > $hiveuser[lastvisit]
	AND NOT(status & ".MAIL_OUTGOING.")
");
$hiveuser['foldercache'] = unserialize($hiveuser['foldercache']);
$folders = $msgcounts = $unreads = array();
$sums = '';
foreach ($_folders as $specialfolderid => $specialfolderinfo) {
	$folders["$specialfolderid"] = $specialfolderinfo['title'];
	$sums .= ",\n\t\tSUM(IF(folderid = $specialfolderid, 1, 0)) AS $specialfolderinfo[name]";
}
foreach ($hiveuser['foldercache'] as $thisfolder) {
	$folders["$thisfolder[folderid]"] = $thisfolder['title'];
	$msgcounts["$thisfolder[folderid]"] = $thisfolder['msgcount'];
	$counts["$thisfolder[folderid]"] = 0;
}

$totals = $DB_site->query_first("
	SELECT 1 AS devnul$sums
	FROM hive_message
	WHERE userid = $hiveuser[userid]
	AND folderid < 0
");
foreach ($_folders as $specialfolderid => $specialfolderinfo) {
	$msgcounts["$specialfolderid"] = $totals["$specialfolderinfo[name]"];
	$counts["$specialfolderid"] = 0;
}

$getunreads = $DB_site->query("
	SELECT message.folderid, COUNT(*) AS messages
	FROM hive_message AS message
	LEFT JOIN hive_folder AS folder ON (folder.folderid = message.folderid)
	WHERE message.userid = $hiveuser[userid] AND NOT(status & ".MAIL_READ.")
	GROUP BY message.folderid
");
while ($unread = $DB_site->fetch_array($getunreads)) {
	$unreads["$unread[folderid]"] = $unread['messages'];
}

$getlast100 = $DB_site->query("
	SELECT messageid, folderid, dateline, email, subject
	FROM hive_message
	WHERE userid = $hiveuser[userid] AND NOT(status & ".MAIL_READ.")
	ORDER BY dateline DESC
	LIMIT 0,100
");
while ($getlast = $DB_site->fetch_array($getlast100)) {
	$counts["$getlast[folderid]"]++;
	if ($counts["$getlast[folderid]"] < 5) {
		$messages["$getlast[folderid]"][] = array($getlast['messageid'], $getlast['dateline'], $getlast['email'], $getlast['subject']);
	}
}

// ############################################################################
// Display the data
function encode_xml($text) {
	$xmlf = array('', '&', '"', '<', '>', '\'');
	$xmlr = array('', '&amp;', '&quot;', '&lt;', '&gt;', '&apos;');
	$i = 0;
	while ($i++ <= count($xmlf)) {
		$text = str_replace($xmlf[$i], $xmlr[$i], $text);
	}
	return $text;
}

// RSS feed...
if ($format == 'rss') {
	// ...version 1
	if ($version == 1) {
		$w3cdtf1 = substr(date('Y-m-d\TH:i:sO', (time() + (($hiveuser['timezone'] - getop('timeoffset')) * 3600))), 0, -2).':'.substr(date('Y-m-d\TH:i:sO', (time() + (($hiveuser['timezone'] - getop('timeoffset')) * 3600))), -2);
		echo "<"."?xml version=\"1.0\" encoding=\"iso-8859-1\""."?".">
			  <rdf:RDF
			    xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
			    xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
			    xmlns:sy=\"http://purl.org/rss/1.0/modules/syndication/\"
			    xmlns:admin=\"http://webns.net/mvcb/\"
			    xmlns:cc=\"http://web.resource.org/cc/\"
			    xmlns=\"http://purl.org/rss/1.0/\">

			  <channel rdf:about=\"".getop('appurl')."\">
			  <title>".getop('appname')."</title>
			  <link>".getop('appurl')."</link>
			  <description>HiveMonitor&#8482; For RSS</description>
			  <dc:language>en-us</dc:language>
			  <dc:creator>".$hiveuser['username'].getop('domainname')."</dc:creator>
			  <dc:date>$w3cdtf1</dc:date>
			  <admin:generatorAgent rdf:resource=\"hivemail/\" />

			  <items>
			  <rdf:Seq>";
		foreach ($folders as $folderid => $foldername) {
			echo "<rdf:li rdf:resource=\"".getop('appurl')."/index.php?folderid=".$folderid."\" />";
		}
		echo "</rdf:Seq>
			  </items>

			  </channel>

";

		foreach ($folders as $folderid => $foldername) {
			$foldername = encode_xml(str_replace(array('<', '>', '&', '\'', '"', '[', ']'), array('«', '»', '-', '_', '_', '«', '»'), $foldername));
			echo "<item rdf:about=\"".getop('appurl')."/index.php?folderid=".$folderid."\">
				  <title>".$foldername." ($phrase[unread]: ".intme($unreads["$folderid"])." / $phrase[total]: ".intme($msgcounts["$folderid"]).")</title>
				  <link>".getop('appurl')."/index.php?folderid=".$folderid."</link>
				  <description>";
			if ($counts["$folderid"] > 0) {
				echo encode_xml(dophrase($phrase['last_x_unread_messages_in_folder'], array($counts["$folderid"])).":<br /><br />\n\n");
				$i=0;
				foreach ($messages["$folderid"] as $messageinfo) {
					$i++;
					$dateline = date(getop('dateformat').' '.getop('timeformat'), $messageinfo[1]);
					$subject = encode_xml($messageinfo[3]);
					echo encode_xml("	".$phrase['from'].": $messageinfo[2]<br />\n
							".$phrase['date'].": $dateline<br />\n
							".$phrase['subject'].": $subject<br />\n
							".$phrase['link'].": <a href=\"".getop('appurl')."/read.email.php?messageid=$messageinfo[0]\">".getop('appurl')."/read.email.php?messageid=$messageinfo[0]</a><br />\n");
					if ($i < count($messages["$folderid"])) {
						echo encode_xml("-----<br />\n");
					}
				}
			} else {
				echo $phrase['no_unread_in_folder'];
			}
			echo "</description>
			  <dc:creator>".$hiveuser['username'].getop('domainname')."</dc:creator>
			  <dc:date>$w3cdtf1</dc:date>
			  </item>
			 ";
		}

		echo "</rdf:RDF>";
	} elseif ($version == 2) {
		$w3cdtf2 = substr(date('Y-m-d\TH:i:sO', (time() + (($hiveuser['timezone'] - getop('timeoffset')) * 3600))), 0, -2).':'.substr(date('Y-m-d\TH:i:sO', (time() + (($hiveuser['timezone'] - getop('timeoffset')) * 3600))), -2);
		echo "<"."?xml version=\"1.0\" encoding=\"iso-8859-1\""."?".">
			  <rss version=\"2.0\" 
			    xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
			    xmlns:sy=\"http://purl.org/rss/1.0/modules/syndication/\"
			    xmlns:admin=\"http://webns.net/mvcb/\"
			    xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
			    xmlns:content=\"http://purl.org/rss/1.0/modules/content/\">

			  <channel>
			  <title>".getop('appname')."</title>
			  <link>".getop('appurl')."</link>
			  <description>HiveMonitor&#8482; For RSS</description>
			  <dc:language>en-us</dc:language>
			  <dc:creator>".$hiveuser['username'].getop('domainname')."</dc:creator>
			  <dc:date>$w3cdtf2</dc:date>
			  <generator>HiveMail v1.3.1 / hivemail/</generator>
			  <admin:errorReportsTo rdf:resource=\"mailto:".$hiveuser['username'].getop('domainname')."\"/>
			  <sy:updatePeriod>hourly</sy:updatePeriod>
			  <sy:updateFrequency>1</sy:updateFrequency>
			  <sy:updateBase>2000-01-01T12:00+00:00</sy:updateBase>
			 ";
		foreach ($folders as $folderid => $foldername) {
			$foldername = encode_xml(str_replace(array('<', '>', '&', '\'', '"', '[', ']'), array('«', '»', '-', '_', '_', '«', '»'), $foldername));
			echo "<item>
				  <title>".$foldername." ($phrase[unread]: ".intme($unreads["$folderid"])." / $phrase[total]: ".intme($msgcounts["$folderid"]).")</title>
				  <guid>".getop('appurl')."/index.php?folderid=".$folderid."</guid>
				  <description>";
			if ($counts["$folderid"] > 0) {
				echo encode_xml(dophrase($phrase['last_x_unread_messages_in_folder'], array($counts["$folderid"])).":<br /><br />\n\n");
				$i=0;
				foreach ($messages["$folderid"] as $messageinfo) {
					$i++;
					$dateline = date(getop('dateformat').' '.getop('timeformat'), $messageinfo[1]);
					$subject = encode_xml($messageinfo[3]);
					echo encode_xml($phrase['from'].": $messageinfo[2]<br />\n
						".$phrase['date'].": $dateline<br />\n
						".$phrase['subject'].": $subject<br />\n
						".$phrase['link'].": <a href=\"".getop('appurl')."/read.email.php?messageid=$messageinfo[0]\">".getop('appurl')."/read.email.php?messageid=$messageinfo[0]</a><br />\n");
					if ($i < count($messages["$folderid"])) {
						echo encode_xml("-----<br />\n");
					}
				}
			} else {
				echo $phrase['no_unread_in_folder'];
			}
			echo "</description>
				  <category>".$foldername."</category>
				  </item>";
		}
		echo "</channel>
			  </rss>";

	} elseif ($version == "9" or $version == "91" or empty($version)) {
		echo "<"."?xml version=\"1.0\" encoding=\"iso-8859-1\""."?".">
			  <!-- generator=\"HiveMail version 1.3.1\" -->
			  <rss version=\"0.91\">
			  <channel>
			  <title>".getop('appname')."</title>
			  <link>".getop('appurl')."</link>
			  <description>HiveMonitor&#8482; For RSS</description>
			  <language>en-us</language>
			  <webMaster>".$hiveuser['username'].getop('domainname')."</webMaster>
			  <pubDate>".date('r', (time() + ($hiveuser['timezone'] - getop('timeoffset')) * 3600))."</pubDate>
			  <item>
			  <title>".getop('appname')." (".dophrase($phrase['last_checked_at_x'], array(date(getop('timeformat'), time()))).")</title>
			  <link>".getop('appurl')."</link>
			  <description>";
		$j=0;
		foreach ($folders as $folderid => $foldername) {
			$j++;
			$foldername = str_replace(array('<', '>', '&', '\'', '"', '[', ']'), array('«', '»', '-', '_', '_', '«', '»'), $foldername);
			echo encode_xml($phrase['folder'].": ".$foldername." ($phrase[unread]: ".intme($unreads["$folderid"])." / $phrase[total]: ".intme($msgcounts["$folderid"]).")<br />\n");
			echo encode_xml($phrase['link'].": ".getop('appurl')."/index.php?folderid=".$folderid."<br /><br />\n\n");
			if ($counts["$folderid"] > 0) {
				echo encode_xml(dophrase($phrase['last_x_unread_messages_in_folder'], array($counts["$folderid"])).":<br />\n");
				$i=0;
				foreach ($messages["$folderid"] as $messageinfo) {
					$i++;
					$dateline = date(getop('dateformat').' '.getop('timeformat'), $messageinfo[1]);
					$subject = encode_xml($messageinfo[3]);
					echo encode_xml($phrase['from'].": $messageinfo[2]<br />\n
						  ".$phrase['date'].": $dateline<br />\n
						  ".$phrase['subject'].": $subject<br />\n
						  ".$phrase['link'].": <a href=\"".getop('appurl')."/read.email.php?messageid=$messageinfo[0]\">".getop('appurl')."/read.email.php?messageid=$messageinfo[0]</a><br />\n");
					if ($i < count($messages["$folderid"])) {
						echo encode_xml("-----<br />\n");
					}
				}
				if ($j < count($folders)) {
					echo encode_xml("-------------------<br /><br />\n");
				}
			} else {
				echo encode_xml($phrase['no_unread_in_folder'].".<br />\n-------------------<br /><br />\n");
			}
		}
		echo "</description>
			  </item>
			  </channel>
			  </rss>";
	}
} elseif ($format == 'atom') {
	if ($version == "03" or $version == 3 or empty($version)) {
		$w3cdtfa = substr(date('Y-m-d\TH:i:sO', (time() + (($hiveuser['timezone'] - getop('timeoffset')) * 3600))), 0, -2).':'.substr(date('Y-m-d\TH:i:sO', (time() + (($hiveuser['timezone'] - getop('timeoffset')) * 3600))), -2);
		echo "<"."?xml version=\"1.0\" encoding=\"utf-8\""."?".">
		<feed version=\"0.3\" xmlns=\"http://purl.org/atom/ns#\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xml:lang=\"en\">
		  <title>".getop('appname')."</title>
		  <tagline>HiveMonitor&#8482; For Atom</tagline>
		  <link rel=\"alternate\" type=\"text/html\" href=\"".getop('appurl')."\" />
		  <modified>$w3cdtfa</modified>
		  <generator url=\"hivemail/\" version=\"1.3.1\">HiveMail&#8482;</generator>
		  <author>
			<name>".encode_xml($hiveuser['username'])."</name>
			<email>".encode_xml($hiveuser['username'].getop('domainname'))."</email>
		  </author>\n";
		foreach ($folders as $folderid => $foldername) {
			echo "<entry>\n";
			$foldername = str_replace(array('<', '>', '&', '\'', '"', '[', ']'), array('«', '»', '-', '_', '_', '«', '»'), $foldername);
			echo "<title>$foldername</title>\n";
			echo "<id>".getop('appurl').",$folderid,$w3cdtfa</id>\n";
			echo "<link rel=\"alternate\" type=\"text/html\" href=\"".getop('appurl')."/index.php?folderid=$folderid\" />\n";
			echo "<issued>$w3cdtfa</issued>\n";
			echo "<modified>$w3cdtfa</modified>\n";
			echo "<dc:subject>$foldername</dc:subject>\n";
			echo "<content type=\"text/html\" mode=\"escaped\" xml:lang=\"en\" xml:base=\"".getop('appurl')."\">\n";
			echo encode_xml($phrase['from'].": $messageinfo[2]<br />\n
						  ".$phrase['date'].": $dateline<br />\n
						  ".$phrase['subject'].": $subject<br />\n
						  ".$phrase['link'].": <a href=\"".getop('appurl')."/read.email.php?messageid=$messageinfo[0]\">".getop('appurl')."/read.email.php?messageid=$messageinfo[0]</a><br />\n");
			echo "</content>\n";
			echo "</entry>\n";
		}
	}
	echo "</feed>";
} else {
	echo '<maildata time="'.date('H:i').'" newmsgs="'.$newmsgs['count'].'" minrate="'.$minrate.'" realname="'.htmlchars($hiveuser['realname']).'" domain="'.htmlchars(substr($hiveuser['domain'], 1)).'">'."\n";
	echo '<folders>'."\n";
	foreach ($folders as $folderid => $foldername) {
		echo '<folder id="'.$folderid.'">'."\n";
		echo '<name>'.str_replace(array('<', '>', '&', '\'', '"', '[', ']'), array('«', '»', '-', '_', '_', '«', '»'), $foldername).'</name>'."\n";
		echo '<total>'.intme($msgcounts["$folderid"]).'</total>'."\n";
		echo '<unread>'.intme($unreads["$folderid"]).'</unread>'."\n";
		echo '</folder>'."\n";
	}
	echo '</folders>'."\n";
	echo '</maildata>';
}

?>