<?php
class Mail_WebdavController extends Atmail_Controller_Action
{
	
	private $_settings;

	public function init()
	{
	
	}

	public function preDispatch()
	{
		// Setup filters
		$this->filter = Atmail_Filter_Input_Controller::filterInput($this->_request);

		require_once 'library/jQuery/jQuery.php';
		
		if( $this->getRequest()->isXmlHttpRequest() || $this->getRequest()->isAjax )
		{
			$this->view->jsonIdsToRender = array();
			Zend_Registry::get('log')->info(__METHOD__ . ' isAJAX request');//show a hidden dialog box and include desired content
			$this->isAjax = true;
		}
		else
		{
			Zend_Registry::get('log')->info(__METHOD__ . ' normal HTML request');//show a hidden dialog box and include desired content
			$this->isAjax = false;
		}

		// check if we have been authenticated... and redirect if not
		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', 'index', 'default');
			return;
		}
		else
		{
			$this->view->UserSettings = Zend_Registry::get('UserSettings');
			$this->view->requestParams = $this->_request->getParams();
			$this->view->setEncoding('UTF-8');
			$this->view->siteBaseUrl = Zend_Registry::get('siteBaseUrl');
			$this->view->appBaseUrl = $this->_request->getBaseUrl() . (strpos($this->_request->getBaseUrl(),'index.php')?'':'/index.php');
			$this->view->moduleBaseUrl = $this->view->appBaseUrl . ($this->view->requestParams['module']=='default'?'':'/' . $this->view->requestParams['module']);
			$this->view->thisActionURL = $this->view->moduleBaseUrl . '/' . $this->view->requestParams['controller'] . '/' . $this->view->requestParams['action'];
			$this->view->notices = array();
			$this->view->errors = array();
			$this->session = new Zend_Session_Namespace('defaultNamespace');
			$this->userData = Zend_Auth::getInstance()->getStorage()->read();
			$this->_globalConfig = Zend_Registry::get('config')->global;
			$this->_currentConfig = array();			
		}
			
		list($junk, $domain) = explode('@', $this->userData['Account']);	
		
		$this->view->localDomain = (in_array($domain, domains::getList()) ? true : false); 
		$this->view->group = groups::get($this->view->UserSettings['Ugroup']);
		
		$this->fileAdapter = Atmail_Files_Factory::instance($this->userData['Account']);
		$this->view->fileAdapter = $this->fileAdapter;
		$this->dbAdapter = Zend_Registry::get('dbAdapter');
		
	}

    public function recursiveDirTranslate($dirs)
    {
        foreach($dirs as &$dir)
        {
            $dir->displayname = $this->view->translate($dir->fileName);
            if($dir->children && count($dir->children) > 0)
            {
                $dir->children = $this->recursiveDirTranslate($dir->children);
            }
        }
        return $dirs;
    }

	public function indexAction()
	{

		$directoryList = $this->recursiveDirTranslate($this->fileAdapter->getFiles('', Atmail_Files_FileObject::TYPE_DIR, $recursive = true));
    	$this->view->directoryList = $directoryList;


	}

	public function listAction()
	{

	} 

	public function listfilesAction()
	{
		
	}
	
	public function viewAction()
	{		
		$this->view->Filename = $this->view->requestParams['Filename'];
		$this->view->Directory = $this->view->requestParams['Directory'];
		
		$fileInfo = $this->fileAdapter->getFileInfo($this->view->Directory . '/' . $this->view->Filename);
		$this->view->fileInfo = $fileInfo;
		
		// Do we have a match for SharedFiles? If so, we need the MD5!
		$this->view->fileMD5 = $this->dbAdapter->fetchOne("select FileMD5 from SharedFiles where FileName=? and FilePath=? and Account=? ", array(
			$this->view->Filename, $this->view->Directory, $this->userData['Account']
		));
		
		//$this->view->iconName = $this->fileAdapter->getIconName($fileInfo);

		// Push the comments
		$this->view->fileComments = $this->fileAdapter->getComments( $this->fileAdapter->getFullPath($this->view->Directory . '/' . $this->view->Filename) );

        foreach($this->view->fileComments as $k => $value)
        {
            foreach($value as $ak => $avalue)
            {
                $this->view->fileComments[$k][$ak] = htmlentities($avalue);
            }
        }
		$this->view->jsonIdsToRender['file_info'] = 'webdav/view.phtml';	
		
		$this->render('global/jsonresponse', null, true);
	}
	
	public function openAction()
	{
		$this->_helper->viewRenderer->setNoRender();

		$this->view->Filename = $this->view->requestParams['Filename'];
		$this->view->Directory = $this->view->requestParams['Directory'];
		
		$fileName = $this->view->Directory . '/' . $this->view->Filename;
		
		$this->view->extension = strtolower(substr($filenameOriginal, (strrpos($filenameOriginal,'.')+1) ));
		
		$fileInfo = $this->fileAdapter->getFileInfo($fileName);
		// Zend_Registry::get('log')->debug( "\n" . print_r($fileInfo, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$fileInfo \n");
		$absFilename = $this->fileAdapter->getFullPath($fileName);
		//Zend_Registry::get('log')->debug( "\n" . print_r($absFilename, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$basePath \n");
		
		// Set headers
		if( !empty($this->view->requestParams['Download']) ) 
		{
		
		    header("Cache-Control: public");
		    header("Content-Description: File Transfer");
		    header("Content-Disposition: attachment; filename=" . urlencode($this->view->Filename));
		
		    header("Content-Type: " . $fileInfo->contentType);
			//header("Content-Length: " . $fileInfo->size);
		    header("Content-Transfer-Encoding: binary");	
		
			fpassthru($this->fileAdapter->getFile($fileName));

		} 
		elseif( !empty($this->view->requestParams['Thumbnail']) ) 
		{

			//$graphCache = Atmail_Cache::fetch(Atmail_Cache::TYPE_DAV, $timeframe . $log . $account . $type . md5(implode($domains)) . $domains);
			//Atmail_Cache::store(Atmail_Cache::TYPE_DAV, $timeframe . $log . $account . $type . md5(implode($domains)) . $domains, $points);
			//Zend_Registry::get('log')->debug( __METHOD__ . ' #' . __LINE__ . ": getting thumbnail");
			
			if( strtolower(substr($this->view->Filename,-4)) == ".pdf" )
			{
				
				header("Content-Type: image/gif");
				//header("Content-Length: " . strlen($contentThumbnail));
				header("Cache-Control: private, max-age=10800, pre-check=10800");
				header("Pragma: private");
				echo thumbnailGifPreviewCachedFromPDFABSFilename($absFilename);

			}
			else
			{

				header("Content-Type: image/png");
				//header("Content-Type: text/plain");
				header("Cache-Control: private, max-age=10800, pre-check=10800");
				header("Pragma: private");
				echo thumbnailPngContentCachedFromAbsFilename($absFilename);

			}

		} 
		else 
		{
			
			if($this->view->requestParams['mimeType'] == "text/html")
				$fileInfo->contentType = "text/html";
			header("Content-Type: " . $fileInfo->contentType);
			fpassthru($this->fileAdapter->getFile($fileName));

		}
		

	}

	public function shareAction()
	{
	
		$this->_helper->viewRenderer->setNoRender();

		$this->view->Filename = $this->view->requestParams['Filename'];
		$this->view->Directory = $this->view->requestParams['Directory'];
		
		$fileName = $this->view->Directory . '/' . $this->view->Filename;
		
		$this->view->extension = strtolower(substr($filenameOriginal, (strrpos($filenameOriginal,'.')+1) ));
		
		$fileInfo = $this->fileAdapter->getFileInfo($fileName);
		
		$fileMD5 = md5($fileName . ":" . $this->userData['Account']);
		
		if( !empty($this->view->requestParams['Delete']) ) {
			$this->dbAdapter->delete("SharedFiles", array(
				$this->dbAdapter->quoteInto('Account = ?', $this->userData['Account']),
				$this->dbAdapter->quoteInto('FileName = ?', $this->view->Filename),
				$this->dbAdapter->quoteInto('FilePath = ?', $this->view->Directory)
			));
		}
		// If it already exists, update
		else if( $this->dbAdapter->fetchOne("select FileMD5 from SharedFiles where FileMD5=? and Account=?", array($fileMD5, $this->userData['Account']) ) ) {
			
		// Otherwise add the new record
		} else {
			
			$this->dbAdapter->insert("SharedFiles", array(
				'Account' => $this->userData['Account'],
				'FileName' => $this->view->Filename,
				'FilePath' => $this->view->Directory,
				'FileMD5' => $fileMD5,
				'Creation' => new Zend_Db_Expr('NOW()')				
			));

		echo $fileMD5;

	}
		
}
	
	public function uploaddndAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		// Get the file uplaod via the DND
		$fileName = $_SERVER['HTTP_X_FILE_NAME'];
		$path = $this->view->requestParams['Directory'] . "/" . basename($fileName);

		try{
			$this->fileAdapter->createFile($path, fopen("php://input", "r"));
		}
		catch(Atmail_Exception $e)
		{
			//$message = $e->getMessage();
			//jQuery::addMessage("The settings have been updated");
			jQuery::evalScript("alert('yo');");
			$this->render('global/jsonresponse', null, true);
		}

	}

	public function checkquotaAction()
	{
        $this->_helper->viewRenderer->setNoRender();
        $requestParams = $this->_request->getParams();

        if($this->_globalConfig['install_type'] != 'server')
        {
            echo json_encode(array(
                'result' => 0,
                'message' => 'success'
            ));
            return;
        }


		if(!array_key_exists('uploadsize', $requestParams)) {
			$result = -1;
			$message = 'param=>uploadsize not found';
		}

		$uploadSize = round( intval( $requestParams['uploadsize'] )/1024, 0);

		list($current, $total) = Atmail_Quota::getTotalQuota(array(Atmail_Quota::TYPE => Atmail_Quota::TYPE_IMAP));

		$result = (($current == 0 && $total == 0) || $uploadSize+$current <= $total)? 0 : -2;
		$message = ($result == 0)? 'success' : 'upload exceeds quota';

		echo json_encode(array(
			'result' => $result,
			'message' => $message
		));
	}
	
	public function uploadAction()
	{
		$this->_helper->viewRenderer->setNoRender();

		$fileNameOriginal = basename($_FILES['newAttachment']['name']);

		if (is_uploaded_file($_FILES['newAttachment']['tmp_name'])) {
			try{
				$this->fileAdapter->createFile(
					$this->view->requestParams['folder'] . '/' . $fileNameOriginal,
					fopen($_FILES['newAttachment']['tmp_name'],'r')
				);
			}
			catch(Atmail_Exception $e)
			{
				echo "Error: " . $e->getMessage();
				exit;
			}			

		}
		else
		{

			$errorMessages = array();
			$errorMessages[0] = $this->view->translate('Attachment upload successful.');
			$errorMessages[1] = $this->view->translate('Attachment is too large.');
			$errorMessages[2] = $this->view->translate('Attachment is too large.');
			$errorMessages[3] = $this->view->translate('The attachment was only partially uploaded.');
			$errorMessages[4] = $this->view->translate('No attachment file was uploaded.');
			$errorMessages[5] = $this->view->translate('Unable to upload the attachment.');
			$errorMessages[6] = $this->view->translate('Unable to store the attachment on the server.');
			$errorMessages[7] = $this->view->translate('Unable to store the attachment on the server.');
			$errorMessages[8] = $this->view->translate('Attachment upload stopped due to security restrictions.');

			/*

			UPLOAD_ERR_OK
			Value: 0; There is no error, the file uploaded with success.
			UPLOAD_ERR_INI_SIZE
			Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
			UPLOAD_ERR_FORM_SIZE
			Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
			UPLOAD_ERR_PARTIAL
			Value: 3; The uploaded file was only partially uploaded.
			UPLOAD_ERR_NO_FILE
			Value: 4; No file was uploaded.
			UPLOAD_ERR_NO_TMP_DIR
			Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.
			UPLOAD_ERR_CANT_WRITE
			Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
			UPLOAD_ERR_EXTENSION
			Value: 8; File upload stopped by extension. Introduced in PHP 5.2.0.

			*/
			echo $errorMessages[$_FILES["newAttachment"]["error"]];
			exit;

		}
				
		// Successful copy
		echo $fileNameOriginal;
		
		//$json = Zend_Json::encode(array('status' => 'OK', 'filename' => $filenameFS)); 
		
		// Build the JSON packet and return
		//$this->getResponse()->setHeader('Content-Type','text/javascript')->appendBody($json);
		//$this->_helper->viewRenderer->setNoRender();
		
	}

	public function commentAction()
	{
				
		//$this->webdav->newComment( $this->view->requestParams['Comment'], $this->view->requestParams['Filename'] );
		
		$fileComment = new Atmail_Files_Comment();
		$fileComment->comment = $this->view->requestParams['Comment'];

		$commentid = $this->fileAdapter->createComment( $this->view->requestParams['Directory'] . '/' . $this->view->requestParams['Filename'], $fileComment );

		jQuery('.message-bubble[commentid=xxxx]')->attr('commentid', $commentid);

		$this->render('global/jsonresponse', null, true);
	}

	public function deletecommentAction()
	{
				
		//$this->webdav->newComment( $this->view->requestParams['Comment'], $this->view->requestParams['Filename'] );
		$requestParams = $this->_request->getParams();
		$commentId = $requestParams['commentid'];

		$fileComment = new Atmail_Files_Comment();
		$fileComment->comment = $this->view->requestParams['Comment'];

		$this->fileAdapter->deleteCommentById( $this->view->requestParams['Directory'] . '/' . $this->view->requestParams['Filename'], $commentId );
		
		$this->render('global/jsonresponse', null, true);
	}

	public function foldercreateAction()
	{

		$this->fileAdapter->createDirectory($this->view->requestParams['folderRoot'] . '/' . $this->view->requestParams['folderNameNew']);
		
		// Create the specified folder into the storage/webdav		
		$this->render('global/jsonresponse', null, true);
		
	}
	
	public function folderdeleteAction()
	{

		$this->fileAdapter->delete($this->view->requestParams['folderRoot'] . '/' . $this->view->requestParams['folderNameNew']);
		
		// Create the specified folder into the storage/webdav		
		$this->render('global/jsonresponse', null, true);
		
	}
	
}
