<?php
class Admin_LicenseController extends Zend_Controller_Action 
{
	
	public function init()
	{
        $this->view->addHelperPath('library/Atmail/View/Helper/', 'Atmail_View_Helper');
		$this->_helper->pluginCall('initAdminController', $this);
		//TODO: extend authentication to support multiple user levels/roles/groups
		 
		$this->request  = $this->getRequest();

		$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');
		$this->dbTables = new dbTables();
		
		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;
			
		}
			
		$this->_helper->viewRenderer->setNoRender();
		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.');
			
		}

		$this->view->reg = Zend_Registry::get('config')->reg;
		$this->view->oldLicense = strlen($this->view->reg['serialKey']) == 32 || strlen($this->view->reg['serialKey']) == 64;

		if( empty($this->view->reg['downloadId']) || empty($this->view->reg['serialKey']) )
			$this->view->notRegistered = 1;
		$expiry = Zend_Registry::get('config')->reg['expiry'];
		if(time() > strtotime($expiry) && !empty($expiry))
			$this->view->licenseExpired = 1;
		Atmail_Locale::setupLocaleAndTranslation( $this->view->userData['Language'] );

	}
	
	public function indexAction() 
	{
		//sanity check for version updates up to date else send user to admin with warning to run updates
		$updater = new Atmail_Update( $this->dbAdapter );
		$this->view->update = $updater->updateAvailable;
	}

	public function detailsAction() 
	{
	
		$this->view->reg = Zend_Registry::get('config')->reg;
		$this->view->global = Zend_Registry::get('config')->global;
		$this->render('details');
	}
	
	public function deleteAction()
	{
		
		$serialKey = $this->request->serialKey;
		$this->_helper->viewRenderer->setNoRender();
		license::remove($serialKey);
		echo Zend_Json::encode(array("response" => array('message' => 'success'), 'status' => 'succeeded', 'success' => true) );
		
	}

	public function registerAction() 
	{
		
		$this->view->reg = Zend_Registry::get('config')->reg;
		$this->view->installType = (Zend_Registry::get('config')->global['install_type'] == 'server')? 's' : 'c';
        $this->render('register');

	}
	
	public function registersaveAction() 
	{
	
		if( $this->view->global['demo'] == 1 )
			throw new Exception('Disabled in online demo');

		license::add($this->request->fields['downloadId'], $this->request->fields['serialKey']);
		
		$message = $this->view->translate("License has been validated.");

		jQuery::evalScript("$('#licence-register').hide();");
		jQuery::evalScript("$('#licence-error').hide();");

		jQuery::addMessage($message);
		require_once("Atmail/General.php");
		$dlid = $this->request->fields['downloadId'];
		$p = base64_encode(serialize(getOperatingSystemInfo()));
		$v = Zend_Registry::get('config')->global['version'];
		//LICENSE UPGRADE: propose adding posting of license key - response will confirm if key has been invalidated, (expiry always calculated from key)
		$url = "http://atmail.com/latestversion.php?dlid=$dlid&reg=1&p=$p&v=$v"; // &lic=$licenseKey 
		$res = @file_get_contents($url);
		/*
		// Check the response
		if ($res) 
		{
		    list($latestVersion, $message, $expiryDate) = explode('|', $res);
			$arr = array('expiry' => $expiryDate);
			require_once 'application/models/config.php';
			config::save('reg', $arr);
		}
		*/		

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

}
