<?php
class Api_WebdavController extends Zend_Controller_Action 
{
	
	public function init()
	{
		//TODO: extend authentication to support multiple user levels/roles/groups 
	
		$this->view->baseUrl = $this->_request->getBaseUrl();
		$this->view->appBaseUrl = $this->_request->getBaseUrl() . (strpos($this->_request->getBaseUrl(),'index.php')?'':'/index.php');
		$this->view->siteBaseUrl = Zend_Registry::get('siteBaseUrl');
		$this->view->moduleBaseUrl = $this->view->appBaseUrl . ($this->_request->module == 'default'?'':'/' . $this->_request->module);
		
		$this->_helper->viewRenderer->setNoRender();
		
		$this->restserver = new Zend_Rest_Server();
		$this->restserver->setClass('webdav');

		// Load all the params
		$this->requestParams = $this->getRequest()->getParams();

		// Use Cookie auth
		if( !Atmail_FormAuth::authenticated() )
		{
			
			// we have most probably timed out, so lets kick them to the timeout bootstrap page
			// this will poison json responses, which will fire the php.error ( or ajax.error ) which can detect the special page
			$this->_forward('timeout', 'mail', 'api', $this->requestParams);
			return;

		} else {
			
			// Load the session
			$this->session = new Zend_Session_Namespace(ATMAIL_NAMESPACE);
			$this->userData = Zend_Auth::getInstance()->getStorage()->read();

			// Load the system settings
			$this->_globalConfig = Zend_Registry::get('config')->global;

			// Find the users settings ( used for theme )
			$this->view->UserSettings = Zend_Registry::get('UserSettings');

			$this->log = Zend_Registry::get('log');
			
			// Used to determine the contact in the global addressbook
			$this->view->Account = $this->userData['Account'];

			$this->fileAdapter = Atmail_Files_Factory::instance($this->userData['Account']);

			
		}
		
						
	} 
	
	
	public function indexAction() {
			
	}

	public function listAction() {

		// Connect to the IMAP server
        $this->requestParams['recursive'] = array_key_exists('recursive', $this->requestParams) ? $this->requestParams['recursive'] : false;
		$arr = $this->fileAdapter->getFiles($this->requestParams['folder'], Atmail_Files_FileObject::TYPE_FILE, $this->requestParams['recursive']);
		
		// Build the JSON packet and return
		$this->getResponse()->setHeader('Content-Type','application/x-javascript');//->appendBody($json);
		$this->_helper->viewRenderer->setNoRender();
		
		// If we are a JSONP request, wrap in a function
		if( array_key_exists('jsoncallback', $this->requestParams) && $this->requestParams['jsoncallback'] && !empty($this->_globalConfig['jsonpAPI']) )
			echo $this->requestParams['jsoncallback'] . '(' . Zend_Json::encode($arr) . ')'; 
		else 
		{
			// Otherwise return as a JSON array
			// $json = Zend_Json::encode($arr);
			
			if( array_key_exists('pretty', $this->requestParams) )
				echo Zend_Json::prettyPrint(Zend_Json::encode($arr), array("indent" => "    "));
			else
				echo Zend_Json::encode($arr);
		
		}
		
	}

	public function deletefileAction()
	{
		
		$success = 0;
		
		// Remove a folder
		if(!empty($this->requestParams['FolderDelete'])) {
			if($this->isReservedFolder($this->requestParams['Directory'])) {
				throw new Exception('Cannot delete system reserved folder!'); 
			}
			
			if($this->fileAdapter->delete($this->requestParams['Directory']))
				$success = 1;
			
		} else {
		// Remove a specified file
			if(isset($this->requestParams['id']))
			{
				foreach($this->requestParams['id'] as $id)	{
					if($this->fileAdapter->delete($this->requestParams['Directory'] . '/' . $id))
						$success = 1;
				}
			}
			
		}
		
		// Return the JSON
		if($success == 1)	{
			$status = array('status' => 'OK');
		} else {
			$status = array('status' => 'FAIL');			
		}
		
		$json = Zend_Json::encode($status); 
		
		// Build the JSON packet and return
		$this->getResponse()->setHeader('Content-Type','text/javascript')->appendBody($json);
		$this->_helper->viewRenderer->setNoRender();
		
	}
	
	public function renameAction()
	{

		// Renames a folder
		if(!empty($this->requestParams['FolderDelete'])) {
			
			if($this->isReservedFolder($this->requestParams['Directory'])) {
				throw new Exception('Cannot rename system reserved folder!'); 
			}
			
			if($this->fileAdapter->rename($this->requestParams['Directory'], $this->requestParams['NewDirectory']))
				$success = 1;
				
		} elseif(!is_array($this->requestParams['id'])) {
			
			$newFile_exten = '';
			
			// TODO: UI does not reflect the actual names of files, only what was submitted in the form
			//       so if we choose to preserve the extension, it does not inform the user. and update
			//       the UI correctly.
			// Preserve the old file extension if user wacks it while renaming their file
			// check the old file even has an extension
			if(!strrpos($this->requestParams['OldFileName'], '.') === false)
			{
				// get the old file extension
				$oldFile_exten = substr($this->requestParams['OldFileName'], strrpos($this->requestParams['OldFileName'], '.'));
				
				// check if the new file has an extension
				if(strrpos($this->requestParams['NewFileName'], '.') === false)
				{
					// if the new file does not have an extension, use the old extension
					$newFile_exten = $oldFile_exten;
					
				}
				// check if the new file ends in just a dot
				
				$pos = strrpos($this->requestParams['NewFileName'], '.');
				$len = strlen($this->requestParams['NewFileName']);
				
				if(strrpos($this->requestParams['NewFileName'], '.') == strlen($this->requestParams['NewFileName'])-1)
				{
					throw new Exception('Files need to not end with a dot');
					// if the new file does not have an extension but ends in dot, use the old extension
					$newFile_exten = $oldFile_exten;
						
				}
			
			}

			$oldFile = $this->requestParams['Directory'] . '/' . $this->requestParams['OldFileName'];
			$newFile = $this->requestParams['NewDirectory'] . '/' . $this->requestParams['NewFileName'] . $newFile_exten;
			
			if($this->fileAdapter->rename($oldFile, $newFile))
					$success = 1;
						
		} else {
			
			// Renames a specified file
			foreach($this->requestParams['id'] as $id)	{
				
				$oldFile = $this->requestParams['Directory'] . '/' . $id;
				$newFile = $this->requestParams['NewDirectory'] . '/' . $id;
				
				if($this->fileAdapter->rename($oldFile, $newFile))
					$success = 1;

			}
			
		}
		
		// Return the JSON
		if($success == 1)	{
			$status = array('status' => 'OK');
		} else {
			$status = array('status' => 'FAIL');			
		}
		
		$json = Zend_Json::encode($status); 
		
		// Build the JSON packet and return
		$this->getResponse()->setHeader('Content-Type','text/javascript')->appendBody($json);
		$this->_helper->viewRenderer->setNoRender();		
	}
	
	public function getFolderName($folder)
	{
		$pos = strrpos($folder,'/');
		return ($pos !== FALSE)? substr($folder, $pos+1) : $folder;
	}

	public function isReservedFolder($folder)
	{
		$folder = $this->getFolderName($folder);
		if(empty($folder)) return true;

		$reserved = array(
			'Attachments',
			'Documents',
			'Music',
			'Pictures',
			'/',
		);

		return in_array($folder, $reserved);
	}
	
}