<?php

/**
 * Provides a global endpoint for access to Zend_Cache
 *
 * @package Atmail
 * @subpackage Quota
 * @copyright Copyright (C) 2011 Atmail. All rights reserved.
 * @author Atmail
 */
class Atmail_Quota_Maildir extends Atmail_Quota
{
	const MAILDIR = 'maildir';
	const ROUND = 'round';
	public function __construct($configuration = array())
	{
		if(!array_key_exists(self::MAILDIR, $configuration))
		{
			throw new Exception('No maildir specified');
		}
		if(!array_key_exists(self::ROUND, $configuration))
		{
			$configuration[self::ROUND] = true;
		}

		parent::__construct($configuration);
	}

	public function _getUsedQuota()
	{
		$maildir = $this->configuration[self::MAILDIR];

		if( $maildir == null || strlen($maildir) == 0)
			return -1;

		$round  = $this->configuration[self::ROUND];
		$folders = api::listfolder_file($maildir);
		$msgsize = 0;
		
		
		// var_dump($folders);
		
		foreach($folders as $folder)
		{

			$pathname = "$maildir/$folder";

			if (!$dh = @opendir("$pathname"))
				continue;

			// We don't include any of the root
			// files in the calculation as all email files
			// are stored under cur/ and new/
			// we don't read tmp as this is where dovecot writes
			// the emails initially, before moving into new/

			// Loop through each message in the folder, find the size.
			foreach(array('new', 'cur', 'webfiles') as $sub)
			{
				if (!$dh = @opendir("$pathname/$sub")) {
					continue;
				}

				while (false !== $f = readdir($dh))
				{
					if($f == "." || $f == "..") continue;
					$filename = "$pathname/$sub/$f";
					$size = @filesize($filename);
					$msgsize += $size;
				}
			}
		}

		if($round)
		{
			return round($msgsize / 1024 / 1024, 1);
		}

		self::log(__METHOD__ . ": Quota = " . $msgsize);

		return $msgsize;
	}

	public function _getTotalQuota()
	{
		throw new Exception(__METHOD__ . ": NOT IMPLEMENTED");
		return false;
		// this code uses maildirsize, which isn't very accurate
		/*if(!file_exists("$maildir/maildirsize"))
		return 0;

		$quota = file_get_contents("$maildir/maildirsize");
		if(preg_match('/(\d+) \d+/', $quota, $m))
		{
		return round($m[1] / 1024 / 1024, 1);
		}*/
	}
}
