<?php
class Admin_PluginsController extends Atmail_Controller_Action
{

	public function init()
	{

		//$this->log = Zend_Registry::get('log');	
		$this->view->addHelperPath('library/Atmail/View/Helper/', 'Atmail_View_Helper');
		$this->_helper->pluginCall('initAdminController', $this);
		 
		$this->request  = $this->getRequest();
		$this->requestParams = $this->request->getParams();
		
		$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->view->global = Zend_Registry::get('config')->global;
		$this->dbAdapter = Zend_Registry::get('dbAdapter');

		require_once 'application/models/admin.php';
		
		$this->admin = new admin();
		
		// check is an XML request or not only allow index to be rendered normally (i.e. full page load)
		if ($this->request->action == 'index' ) {
			return;
		}
			
		if( !isset($this->view->errors) ) {
			$this->view->errors = array();
		}
		
		if( !isset($this->view->notices) ) {
			$this->view->notices = array();
		}
		
		if( !isset($this->view->jsonIdsToRender) ) {
			$this->view->jsonIdsToRender = array();
		}
		
		require_once 'library/jQuery/jQuery.php';
	}

	public function preDispatch()
	{
		// Check the session is active, otherwise redirect to the login page
		$this->view->userData = $this->admin->getCurrentAdminData();
		
		if( empty($this->view->userData) ) {
			$this->_forward( 'timeout', 'index', 'default' );
			return;		 
		}

		if( $this->view->userData['UMasterAdmin'] != '1') {
			throw new Exception('MasterAdmin rights required.');	
		}
	}

	public function indexAction()
	{
	}
	
	public function addAction()
	{
		$params = $this->getRequest()->getParams();
		if (isset($params['file']) || !empty($params['file'])) {
			$file = base64_decode($params['file']);
			$this->view->installResult = plugins::install($file);
		}
		
		$this->view->availablePluginPackages = plugins::getAvailablePackages();
	}
	
	public function settingsAction()
	{
		$params = $this->getRequest()->getParams();
		if (isset($params['filter']) && isset($params['key'])) {
		   $this->view->plugins = plugins::getInstalledPlugins($params['filter'], $params['key']);
		   $this->view->filter = $params['filter'];
		   $this->view->key = $params['key'];
		} else {
			$this->view->plugins = plugins::getInstalledPlugins();
		}
		
		$this->render("settings");
	}
	
	public function savesettingsAction()
	{
		$params = $this->getRequest()->getParams();
		if( $this->view->global['demo'] == 1 ) {
			throw new Exception('Disabled in online demo');
		}

		try {
			require_once 'application/models/config.php';
			plugins::updateStatus($params['plugins']);
			config::save('global', array('allowPlugins' => $params['allowPlugins']));
			
			// Success!
			jQuery::addMessage( $this->view->translate('The settings have been updated.') );
		} catch( Exception $e ) {
			throw new Exception('Failed saving config: ' . $e->getMessage());
		}
		
		$this->render('global/jsonresponse', null, true);		
	}

	public function infoAction()
	{
		$params = $this->getRequest()->getParams();
		$this->view->plugin = plugins::getInfoFromDb($params['id']);
	}
	
	public function preinstallAction()
	{
         if( $this->view->global['demo'] == 1 ) {
			$this->view->demo = true;
			return;
         }

		$params = $this->getRequest()->getParams();
		$this->view->errorCode = 0;
		if( isset($params['existing']) ) {
			$this->view->plugin = plugins::getInfoFromTgz(APP_ROOT . "/application/modules/admin/pluginPackages/{$params['existing']}", $pluginURL);
			$this->view->plugin['tgzPath'] = $params['existing'];
			$this->view->plugin['compat'] = trim($this->view->plugin['compat']);
			
			//check for compatibility
			if( $this->view->plugin['compat'] == '' || version_compare($this->view->plugin['compat'], Zend_Registry::get('config')->global['version'], '>') ) {
				//bad plugin
				$this->view->errorCode = 16; //uploaded plugin not compatible with this version of Atmail
			}
			
			return;
			
		} elseif( isset($_FILES['newPlugin']) ) {
		
			$uploadedFile = $_FILES['newPlugin'];
		    
			// Check for any errors
			if ($uploadedFile['error'] != 0) {
				$this->view->errorCode = 2; //problem uploading file
				return;
			}   
			
			// Check for correct type
            if(substr($uploadedFile['name'], -4) != '.tgz') {
				$this->view->errorCode = 4; //uploaded file not a valid Plugin package
				return;
			}	
			
			//try get plugin info
			$pluginInfoResult = plugins::getInfoFromTgz( $uploadedFile['tmp_name'] );
			if( !is_array($pluginInfoResult) ) {
				//bad plugin
				$this->view->errorCode = 8; //referred error
				$this->view->error = $pluginInfoResult;
				return;
			}
			
			//check for compatibility
			if( $pluginInfoResult['compat'] == '' || version_compare($pluginInfoResult['compat'], Zend_Registry::get('config')->global['version'], '>') ) {
				//bad plugin
				$this->view->errorCode = 16; //uploaded plugin not compatible with this version of Atmail
			}
			$this->view->plugin = $pluginInfoResult;
			
			//sanity check uploaded file for plugin validity and compatibility
			plugins::savePluginTgz($uploadedFile['tmp_name'], $uploadedFile['name']); 
			$this->view->plugin['tgzPath'] = $uploadedFile['name'];
			$this->view->plugin['compat'] = trim($this->view->plugin['compat']);
		} else {
			$this->view->errorCode = 1; //unknown error (actually a bad/illagal call)
			return;	
		}
	}
	
}

