<?php
/**
 * ThunderSnarf
 *
 * @author Ricardo H.F. Sette P. <ricardohfsp@gmail.com>
 * @link http://www.freebsdbrasil.com.br/
 * @copyright Copyright &copy; 2010 - FreeBSD Brasil LTDA
 * @license licença GNU/GPL v2.0 http://www.gnu.org/licenses/gpl-2.0.html
 */
?>
<?php

class SiteController extends Controller {
	/**
	 * Declares class-based actions.
	 */
	public function actions() {
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex() {
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		//$model=new Extension();
		//$data = $model->findBySql("SELECT SUM(traffic_static) AS traffic_static, SUM(traffic_dynamic) AS traffic_dynamic, SUM(cache_static) AS cache_static, SUM(cache_dynamic) AS cache_dynamic FROM thunder_extension;");

		$this->render('pages/sobre');
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError() {
		if($error=Yii::app()->errorHandler->error) {
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	/**
	 * Displays the contact page
	 */
	/*public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}*/

	/**
	 * Displays the login page
	 */
	public function actionLogin() {
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm'])) {
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($this->validarSoftware($model) && $model->validate() && $model->login())
				$this->redirect(array('estatisticas/'));
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout() {
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}

	private function objectXML2array($object) {
		$return = NULL;
		if(is_array($object)) {
			foreach($object as $key => $value)
				$return[$key] = $this->objectXML2array($value);
		}
		else {
			$var = @get_object_vars($object);
			if($var) {
				foreach($var as $key => $value)
					$return[$key] = ($key && !$value) ? NULL : $this->objectXML2array($value);
			}
			else return $object;
		}
		return $return;
	}

	private function validarSoftware(&$model) {
		$thunderconf = file(Yii::app()->params['thunderconf']);
		$plugins = array();
		$cache_dir_array = array();
		foreach ($thunderconf as $line_num => $line) {
			if(strpos($line,"LOGIN ")!==false AND strpos($line,"LOGIN ")==0) {
				Yii::app()->user->setState('login_thunder', trim(substr($line,5)));
				$login_thunder = trim(substr($line,5));
			}
			if(strpos($line,"PASSWORD ")!==false AND strpos($line,"PASSWORD ")==0) {
				Yii::app()->user->setState('senha_thunder', md5(trim(substr($line,8))));
				$password_thunder = trim(substr($line,8));
			}
		}
		try {
			$objDomXML = new DomDocument();
			if(!$objDomXML->load("http://www.bmsoftware.org/webservice/ativador/snarf.php?login=".$login_thunder."&h=".md5($login_thunder)."&password=".md5($password_thunder))){
				throw new Exception('Falha ao buscar informações no site da BMSoftware.');
			}
			$objXML = simplexml_load_string($objDomXML->saveXML());
			$arrayXML = $this->objectXML2array($objXML);
                Yii::app()->user->setState('xml_thunder', $arrayXML);
		}catch(DOMException $e) {
			$model->addError('FalhaAutenticacao',$e->getMessage());
			return false;
		}catch(Exception $e){
			$model->addError('FalhaAutenticacao',$e->getMessage());
			return false;
		}

		if(isset($arrayXML["THUNDERCONF_SITE"])) {//verificar se a pessoa está cadastrada, pois se nao estiver o retorno é um array contendo THUNDERCONF_SITE
			$model->addError('FalhaAutenticacao',$arrayXML["THUNDERCONF_SITE"]);
			return false;
		}

		if(!isset($arrayXML["THUNDER_BASE"])) {//verificar se a pessoa está cadastrada, pois se nao estiver o retorno é um array contendo THUNDERCONF_SITE
			$model->addError('FalhaAutenticacao','Dados não cadastrados na <a  href="http://www.bmsoftware.org/" target="_blank">BMSoftware</a>. Você deve efetuar a configuração do seu ThunderCache no site da <a  href="http://www.bmsoftware.org/" target="_blank">BMSoftware</a>.');
			return false;
		}

                if(!isset($arrayXML["THUNDER_CACHEDIRS"])) {//verificar se a pessoa está cadastrada, pois se nao estiver o retorno é um array contendo THUNDERCONF_SITE
			$model->addError('FalhaAutenticacao','Não existe uma Configuração de Disco cadastrada na <a  href="http://www.bmsoftware.org/" target="_blank">BMSoftware</a>. Você deve efetuar a Configuração de Disco do seu ThunderCache no site da <a  href="http://www.bmsoftware.org/" target="_blank">BMSoftware</a>.');
			return false;
		}

		if((int)$arrayXML["THUNDER_PLUGINS_CLIENTE"]["@attributes"]["quantidade"]>0) {
			foreach ($arrayXML["THUNDER_PLUGINS_CLIENTE"]["PLUGIN_DOMAIN"] as $num => $plugin) {
				$plugin_array = explode("_", $plugin);
				$plugins[] = $plugin_array[0];
				unset($plugin_array[0]);
				foreach($plugin_array as $key => $value) {
					if(strpos($value, ".")!==false)
						$plugins[] = $value;
				}
			}
			Yii::app()->user->setState('thunderplugin', $plugins);
		}
                Yii::app()->user->setState('xml_thunder', $arrayXML);
		return true;
	}
}