<?php
class Admin_GraphController 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 

		// Setup the requestParams
		$this->request  = $this->getRequest();
		$this->view->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;
		
		require_once 'application/models/admin.php';
		require_once 'application/models/graph.php';
		$this->admin = new admin();
		$this->graph = new graph();
		$this->dbAdapter = Zend_Registry::get('dbAdapter');

		$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;			

		}
		
		Atmail_Locale::setupLocaleAndTranslation( $this->view->userData['Language'] );
		
	}
	
	// Load the contact creation page, using the existing editcontact for code re-use
	public function jsonAction() 
	{
		
		$fieldFilters = array(
			'account'		=> array('StripTags'),
			'view'			=> array('StripTags'),
			'log'			=> array('StripTags'),
			'type'   		=> array('StripTags', 'Int'),
		);

		$fieldValidators = array (
			'type'			=> array('Int'),
			'log'			=> array(),
			'view'			=> array(), 
			'account'			=> array()
		);

		$filter = new Atmail_Filter_Input($fieldFilters, $fieldValidators, $this->view->requestParams);	
		$request = $filter;
		$logAllowedValues = array('Log_Login', 'Log_SendMail', 'Log_RecvMail', 'Log_Spam', 'Log_Virus');
		
		if( !in_array($request->log, $logAllowedValues) )
			throw new Exception('Illegal log value');

		$viewAllowedValues = array('day','week', 'month','year');

		if( !in_array($request->view, $viewAllowedValues) )
			throw new Exception('Illegal view value');
		
		$this->view->adminDomains = $this->dbAdapter->fetchCol("select Domain from AdminGroup where Username = " . $this->dbAdapter->quote( Zend_Auth::getInstance()->getIdentity() ) );
		$adminInfo = $this->admin->getCurrentAdminData();
		
		if( 
			$adminInfo['UMasterAdmin'] != '1' && 
			(
				count($this->view->adminDomains) == 0 || 
				(
					count($this->view->adminDomains) == 1 &&
					$this->view->adminDomains[0] == ''
				)
			)
		)
		{
			
			$points = array();
			
		}                     
		else
		{
			
			$points = $this->graph->getLog($request->view, $request->log, $request->account, $request->type, $this->view->adminDomains);
			
		}
		$data = Zend_Json::encode( $points );

$template = <<<_EOF
{
    data: $data,
	color: '#0073ca',
	lines: { show: true, fill: true, fillColor: "rgba(229, 242, 250, 0.8)", lineWidth: 3 }
}
_EOF;

		$this->getResponse()->setHeader('Content-Type','application/json');
		$this->getResponse()->appendBody($template);		
		
	}

	public function useripmapAction()
	{

		if(empty($this->view->requestParams['Account']) || empty($this->view->requestParams['range'])) {

			$data = Zend_Json::encode( array('error' => 1, 'msg' => 'Account and range are required') );

			$this->getResponse()->setHeader('Content-Type','application/json');
			$this->getResponse()->appendBody($data);

			return;
		}

		if( !array_key_exists("resolveLogIPsToGeoLocationViaAtmailGeoLocationServer", $this->view->global) || $this->view->global['resolveLogIPsToGeoLocationViaAtmailGeoLocationServer'] != true )
		{

			$data = Zend_Json::encode( array('error' => 1, 'msg' => 'Geo-location lookups currently disabled by admin.') );
			$this->getResponse()->setHeader('Content-Type','application/json');
			$this->getResponse()->appendBody($data);
			return;

		}

		if( $this->admin->checkAdminPrivs($this->view->requestParams['Account']) == 0 )
		{
			$data = Zend_Json::encode( array('error' => 1, 'msg' => 'You do not have permission to view this data') );

			$this->getResponse()->setHeader('Content-Type','application/json');
			$this->getResponse()->appendBody($data);

			return;
		}
		$forceCacheRefresh = false;

		// Cache the user IPs
		$account = preg_replace("/[^A-Za-z0-9]/", '', $this->view->requestParams['Account']);
		$range = preg_replace("/[^A-Za-z0-9]/", '', $this->view->requestParams['range']);
		$logsCount = $this->dbAdapter->fetchAll("select count(LogIP) from Log_Login where Account=? and LogIP != '127.0.0.1'", array($this->view->requestParams['Account']));
		if(($userIps = Atmail_Cache::fetch(Atmail_Cache::TYPE_GRAPH, $account . $range . $logsCount)) === false || $forceCacheRefresh)
		{
			// maximum response of 100 items
			$userIps = $this->dbAdapter->fetchAll("select LogType, LogDate, LogIP from Log_Login where Account=? and LogIP != '127.0.0.1' and LogDate > DATE_SUB(NOW(), INTERVAL ? DAY) group by LogIP order by LogDate desc limit 100", array($this->view->requestParams['Account'], $this->view->requestParams['range']));
			Atmail_Cache::store(Atmail_Cache::TYPE_GRAPH, $account . $range . $logsCount , $userIps);
		}

		if(file_exists(".dev")) {
			$serverUrl = "http://reboot.local.atmail.com";

		} else {
			$serverUrl = "http://api.atmail.com";

		}

		// use curl if it exists

		$useCurl = function_exists('curl_init');
		if( $useCurl )
		{
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,10);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		}
		foreach($userIps as $key => $value)
		{

			// Cache the IP
			if( ($userIps[$key]['data'] = $graphIPCache = Atmail_Cache::fetch(Atmail_Cache::TYPE_GRAPH, $account . $userIps[$key]['LogDate'] . $userIps[$key]['LogIP'] . $range)) === false || $forceCacheRefresh )
			{

				$url = $serverUrl . "/api/ip/?ip=" . $userIps[$key]['LogIP'] . '&ClientID=' . Zend_Registry::get("config")->reg['downloadId'];
				if( $useCurl )
				{

					curl_setopt($ch, CURLOPT_URL,$url);
					$jsonData = curl_exec($ch);

				}
				else
					$jsonData = file_get_contents($url);

				$jsonArray = Zend_Json::decode($jsonData);

				// do A CHECK if clientid not found, return json error
				$userIps[$key]['data'] = array('country_code' => $jsonArray['data']['country_code'], 'city' => $jsonArray['data']['city'], 'lat' => $jsonArray['data']['lat'], 'long' => $jsonArray['data']['long']);

				Atmail_Cache::store(Atmail_Cache::TYPE_GRAPH, $account . $userIps[$key]['LogDate'] . $userIps[$key]['LogIP'] . $range, $userIps[$key]['data']);

            }

		}
		if( $useCurl )
			curl_close($ch);

		if( $this->view->requestParams['type'] == 'json')
		{

			$data = Zend_Json::encode( $userIps );

		}
		else
		{

			$jsJson = array('type' => 'FeatureCollection');

			$jsJson['features'] = array();
			$id = 0;
			foreach($userIps as $ip) {

				if( !empty($ip['data']['lat']) && !empty($ip['data']['long']) ) {

					$jsJson['features'][] = array(
						'type' => 'Feature',
						'id' => $id,
						'geometry' => array('type' => 'Point', 'coordinates' => array($ip['data']['long'], $ip['data']['lat']) ),
						'properties' => array(
                            'popupContent' => $ip,
                		)
					 );			
					$id++;

				}

			}

			$data = Zend_Json::encode( $jsJson );

		}

		$this->getResponse()->setHeader('Content-Type','application/json');
		$this->getResponse()->appendBody($data);

	}
	
}
