<?php
 /**
 * @category   Atmail
 * @package    WebDAV model
 * @author     Ben Duncan
 * @license    Copyrighted by Atmail 2011
 */

class webdav
{

	private $_session;
	private $_account;
	private $_tableNames;
	private $_namespaceName = 'webdav';
		
	public function __construct(Array $args)
	{

		return;
		if( !isset($args['Account']) )
		{
			throw new Atmail_Exception('WebDAV constructor requires Account field in arguments array');
		}
		else
		{
			$this->_account = $args['Account'];               
		}
			
		$email = explode('@', $this->_account);
		
		if(!empty($email['1']))
		{
			$this->_username = $email['0'];
			$this->_domain = $email['1'];		
		}
		else
		{	
			$this->_username = '';		
			$this->_domain = '';	
		}

		$this->view->global = Zend_Registry::get('config')->global;
        	if( isset($args['namespaceName']) )
			$this->_namespaceName = $args['namespaceName'];
		$this->_session = new Zend_Session_Namespace($this->_namespaceName); // session used as seperate persistent store for if caching disabled
		
		$this->dbAdapter = Zend_Registry::get('dbAdapter');
		
		// Fetch the users preferences
		$this->userData = users::getAllUserData($this->_account);
		
		$this->log = Zend_Registry::get('log');
		
		// Store files in the users maildir, otherwise toggle to the users tmp dir (webmail client only)
		if(empty($this->userData['MailDir'])) {
			 $this->storageDir = users::getTmpFolder() . '/webfiles/';
			
			// Check the path exists (webfiles)
			if (!mkdir($this->storageDir, 0755)) {
			    //die('Failed to create folders...');
			}
			
		} else {
			 $this->storageDir = $this->userData['MailDir'] . '/webfiles/';
		}
		
		
	}

	public function listfiles($folder='', $depth=0)
	{
		$arr = array();
		
		if(!empty($folder)) {
			$dirname = $this->storageDir . $folder . '/';
			
		} else {
			$dirname = $this->storageDir;
			
		}
		
		// Open a known directory, and proceed to read its contents
		if (is_dir($dirname)) {

		    if ($dh = opendir($dirname)) {
				$i = 0;
				
		        while (($file = readdir($dh)) !== false) {
					$stat = stat($dirname . $file);
					$type = filetype($dirname . $file);

					// Skip dirs, just files
					if($type == 'dir' || $file == '.' || $file == '..')
						continue;
						
					$arr[$i]['Filename'] = $file;
					$arr[$i]['Filetype'] = $type;
					$arr[$i]['Size'] = round($stat['size'] / 1024, 0) . "KB";
					$arr[$i]['Atime'] = timeago( strtotime($stat['atime']) );
					$arr[$i]['Mtime'] = timeago($stat['mtime']);

					preg_match('/\.(.*)/', $file, $m);
					if($m[1] == "png" || $m[1] == "jpg" || $m[1] == "gif")
					$arr[$i]['Ext'] = "image";
					else
					$arr[$i]['Ext'] = "file";					
					
					$i++;
		
		        }
		        closedir($dh);
		    }
		}
		
		asort($arr);
		
		return $arr;
		
	}
	
	// List folders in the users WebDAV store	
	public function listfolders()
	{
		$arr = array();
		
		$arr = $this->getDirectoryTree($this->storageDir, $arr, 0);
		
		asort($arr);
		
		return $arr;
		
	}
	
	// Stat a file for info
	public function filestat( $filename )
	{
		$stat = stat( $this->storageDir . $filename);
		
		// Cleanup the size and modified time
		$stat['size'] = round($stat['size'] / 1024, 0) . " KB";
		$stat['mtime'] = timeago($stat['mtime']);
		
		return $stat;
	}
	
	private function getDirectoryTree( $outerDir ){
	    $dirs = array_diff( scandir( $outerDir ), Array( ".", ".." ) );
	    $dir_array = Array();
	    foreach( $dirs as $d ){
	        if( is_dir($outerDir."/".$d) ) $dir_array[ $d ] = $this->getDirectoryTree( $outerDir."/".$d );
	        else if(is_array($d)) $dir_array[ $d ] = $d;
	    }
	
	    return $dir_array;
	}
	
	// List a specified folder
	private function listfolder($dirname, $arr, $i)
	{
	
		// Open a known directory, and proceed to read its contents
		if (is_dir($dirname)) {

		    if ($dh = opendir($dirname)) {
				
		        while (($file = readdir($dh)) !== false) {
					$stat = stat($dirname . $file);
					$type = filetype($dirname . $file);

					// Skip dirs, just files
					if($file == '.' || $file == '..')
						continue;
						
					if($type == 'dir') {
						$arr[$i]['Name'] = $file;
						$arr[$i]['Filetype'] = $type;
						$arr[$i]['Size'] = $stat['size'];
						$arr[$i]['Atime'] = $stat['atime'];
						$arr[$i]['Mtime'] = $stat['mtime'];
						
						$arr = $this->listfolder($dirname . '/' . $file, $arr, $i);
					}
											
					$i++;
		
		        }
		        closedir($dh);
		    }
		}
	
	asort($arr);
	return $arr;
		
	}
	
	// *** COMMENTS
	// Get a list of comments on a file (needs a unique reference)	
	public function getComments($fileName)
	{
		
		return $this->dbAdapter->fetchAll("select * from FileComments where FileID=?", md5($fileName));
	
	}	

	// Insert a new comment into the SQL
	public function newComment($comment, $fileName)
	{
		
		return $this->dbAdapter->INSERT("FileComments", array(
		'Comment' => $comment,
		'FileID' => md5($fileName),
		'Account' => $this->_account	
		));
	
	}	
	
	// ** FOLDER FUNCTIONS
	// Create a new folder on disk
	public function foldercreate($folderNameNew, $folderRoot)
	{
		
		if (!mkdir($this->storageDir . $folderNameNew, 0755)) {
			return 1;
		}
		
		return 0;
		
	}
	
	public function folderdelete($folderName, $folderRoot)
	{

	// Build the directory to purge
	$dir = $this->storageDir . '/' . $folderRoot . '/' . $folderName;
	
	// Call function to loop removing the directory
	return $this->rmdir($dir);
		
	}
	
	private function rmdir($dir)
	{
	
	return;
	
	if (is_dir($dir)) {
		$objects = scandir($dir);
		foreach ($objects as $object) {
		  if ($object != "." && $object != "..") {
		    if (filetype($dir."/".$object) == "dir") $this->rrmdir($dir."/".$object); else unlink($dir."/".$object);
		  }
		}
		reset($objects);
		rmdir($dir);
		}
	}
}
