<?php 

// h-source, a web software to build a community of people that want to share their hardware information.
// Copyright (C) 2010  Antonio Gallo (h-source-copyright.txt)
//
// This file is part of h-source
//
// h-source is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// h-source is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with h-source.  If not, see <http://www.gnu.org/licenses/>.

if (!defined('EG')) die('Direct access not allowed!');

class BaseController extends Controller
{
	
	protected $lang;
	protected $islogged = 'no';
	protected $ismoderator = false;
	protected $isadmin = false;
	protected $querySanitized = true;
	protected $token = 'token';
	protected $_updating = 'no';

	protected $_configXml = null;

	protected $_topMenuClasses = array(
		"home"			=>	null,
		"hardware"		=>	null,
		"credits"		=>	null,
		"issues"		=>	null,
		"contact"		=>	null,
		"search"		=>	null,
		"news"			=>	null,
		"download"		=>	null,
		"help"			=>	null,
		"wiki"			=>	null,
		"faq"			=>	null,
		"project"		=>	null,
	);
	
	public function __construct($model, $controller, $queryString) {
		parent::__construct($model, $controller, $queryString);
		
		header("Cache-Control: no-cache");

		$this->model('BoxesModel');
		$this->model('HistoryModel');
		$this->model('ParamsModel');
		$this->model('UsersModel');
				
		$this->load('header');
		$this->load('footer','last');
		
		$this->session('registered');
		$this->s['registered']->checkStatus();
			
		$data['username'] = null;
		$data['user_groups'] = null;
		$data['islogged'] = 'no';
		$data['token'] = 'token';
		$data['ismoderator'] = false;
		$data['isadmin'] = false;
		
		if ($this->s['registered']->status['status'] === 'logged')
		{
			$data['username'] = $this->s['registered']->status['user'];
			$groups = $this->s['registered']->status['groups'];
			$groups[] = 'registered';
			$data['user_groups'] = implode(',',$groups);
			
			$data['islogged'] = 'yes';
			$this->islogged = $data['islogged'];
			
			$data['token'] = $this->s['registered']->status['token'];
			$this->token = $data['token'];
			
			$data['ismoderator'] = in_array('moderator',$this->s['registered']->status['groups']) ? true : false;
			$this->ismoderator = $data['ismoderator'];

			$data['isadmin'] = in_array('admin',$this->s['registered']->status['groups']) ? true : false;
			$this->isadmin = $data['isadmin'];
		}
		
		$data['lang'] = 'en';
		$this->lang = 'en';

		if (isset($this->_queryString[0]))
		{
			$lang = (strcmp($this->_queryString[0],'') !== 0) ? $this->_queryString[0] : 'en';
			$data['lang'] = Lang::sanitize($lang);
			$this->lang = $data['lang'];
			Lang::$current = $data['lang'];
		}

		$data['langIcon'] = Lang::getIcon(Lang::$current);
		$data['langLabel'] = Lang::getLabel(Lang::$current);
		
		//set desktop or mobile version
		Version::set();
		//subfolder of the Views folder where to look for view files
		Params::$viewSubfolder = Version::getViewSubfolder();

		$data['tm'] = $this->_topMenuClasses;
		
		$this->_queryString = $this->sanitizeQueryString($this->_queryString);

		$data['querySanitized']	= $this->querySanitized;
		$data['queryString'] = Url::createUrl($this->_queryString);

		//check ft they are updating the website
		$updating = $this->m['ParamsModel']->select('updating')->where(array('id_par'=>1))->toList('updating')->send();

		$data['updating_flag'] = 'no';
		if (count($updating)>0)
		{
			$data['updating_flag'] = $updating[0];
			$this->_updating = $data['updating_flag'];
		}

		//get the configuration xml
		if (Website::$useXmlConfigFile)
		{
			$xmlConfigFile = rtrim(Website::$xmlConfigFileFolder,'/') . '/config.xml';

			if (@simplexml_load_file($xmlConfigFile))
			{
				$this->_configXml = simplexml_load_file($xmlConfigFile);
			}
		}
		else
		{
			$xmlRes = $this->m['ParamsModel']->select('boxes_xml')->where(array('id_par'=>1))->toList('boxes_xml')->send();
			
			if (count($xmlRes)>0)
			{
				$configXml = htmlspecialchars_decode($xmlRes[0],ENT_QUOTES);
				
				if (@simplexml_load_string($configXml))
				{
					$this->_configXml = simplexml_load_string($configXml);
				}
			}
			
		}

		//elements of the top menu from the config.xml file
		//help link
		$mod = new BoxParser($this->getBox(array("top_menu","help_page_link")));
		$data["topMenuHelpLink"] = $mod->modules[0]->render($this->_topMenuClasses["help"]);
		//faq link
		$mod = new BoxParser($this->getBox(array("top_menu","faq_link")));
		$data["topMenuFaqLink"] = $mod->modules[0]->render($this->_topMenuClasses["faq"]);
		
		//link to the "discover your hardware" wiki page
		$data['discoverYourHardwareLink'] = $this->getModule(array('right_column','discover_your_hardware'));
		
		$this->append($data);
	}

	//get the right box from the configuration xml
	protected function getBox($xmlPath,$xmlString = null)
	{
		if (!isset($xmlString))
		{
			$xmlString = $this->_configXml;
		}

		if (is_array($xmlPath))
		{
			if (isset($xmlString))
			{
				$tempXml = $xmlString->{$xmlPath[0]};
				if (count($xmlPath) === 1)
				{
					if (isset($tempXml->{$this->lang}))
					{
						return $tempXml->{$this->lang}->asXml();
					}
					else if (isset($tempXml->{"en"}))
					{
						return $tempXml->{"en"}->asXml();
					}
					else
					{
						return null;
					}
				}
				else
				{
					array_shift($xmlPath);
					return $this->getBox($xmlPath,$tempXml);
				}
			}
		}
		return null;
	}

// 	get the HTML of a module from the xml configuration string
//	$xmlPath: array conitaining the path
	protected function getModule($xmlPath)
	{
		$tracksHelpLabel = null;
		$xml = $this->getBox($xmlPath);
		if ($xml)
		{
			$box_news = new BoxParser($xml);
			$tracksHelpLabel = $box_news->render();
		}
		return $tracksHelpLabel;
	}
	
	protected function right($lang = 'en')
	{
		$hard = new HardwareModel();
		
		$data['stat'] = $hard->clear()->select('type,count(*) AS numb')->where(array('-deleted'=>'no','cleared'=>'no'))->groupBy('type')->toList('type','aggregate.numb')->send();
		
		$logged = $this->s['registered']->getUsersLogged();
		
		$data['numbLogged'] = count($logged);

		//render the boxes inside the right column
		$data['htmlRightBox'] = $this->getModule(array('right_column'));

		$data['language_links'] = $this->buildLanguageLinks($this->lang);
		
		$data['lastModif'] = $this->m['HistoryModel']
								->clear()->select()
								->inner('hardware')
								->on('hardware.id_hard=history.id')
								->where(array('type'=>'hardware','gr'=>'registered','deleted'=>'no','cleared'=>'no',))
								->orderBy('id_history desc')
								->limit(5)
								->send();

		$this->append($data);
		$this->load('right');
	}
	
	protected function sanitizeQueryString($queryArray)
	{
		$resArray = array();
		foreach ($queryArray as $item)
		{
			if (preg_match('/^[a-zA-Z0-9\-\_\.\+\s]+$/',$item))
			{
				$resArray[] = sanitizeAll($item);
			}
			else
			{
				$this->querySanitized = false;
				return array('en');
			}
		}
		return $resArray;
	}
	
	protected function buildLanguageLinks($lang)
	{
		$status = $this->_queryString;
		$cPage = $this->querySanitized ? $this->currPage : $this->baseUrl."/home/index";
		
		$mobileDataRole = Version::get() === "mobile" ? "data-role='listview'" : null;
		
		$link = "<ul $mobileDataRole class='languages_link_box'>\n";
		foreach (Lang::$complete as $abbr => $fullName)
		{
			$linkClass = (strcmp($abbr,$lang) === 0) ? "class='current_lang'" : null;
			$status[0] = $abbr;
			$href = Url::createUrl($status);
			$fullNameArray = explode(',',$fullName);
			$text = "<img class='ui-li-icon' src='".$this->baseUrl."/Public/Img/Famfamfam/".$fullNameArray[0]."'><span>".$fullNameArray[1]."</span>";

			$mobileRel = Version::get() === "mobile" ? "rel='external'" : null;
			$link .= "\t<li><a $mobileRel $linkClass href='".$cPage.$href."'>$text</a></li>\n";
		}
		$link .= "</ul>\n";
		return $link;
	}
	
	protected function cleverLoad($file)
	{
		$fileInt = $file."_".$this->lang;
		if (file_exists(ROOT . DS . APPLICATION_PATH . DS . 'Views' . DS . Params::$viewSubfolder . DS . ucwords($this->controller) . DS . $fileInt . '.php'))
		{
			$this->load($fileInt);
		}
		else
		{
			$this->load($file);
		}
	}
	
}