<?php
/**
* @version 1.0.0
* @package RSFiles! 1.0.0
* @copyright (C) 2009 www.rsjoomla.com
* @license GPL, http://www.gnu.org/copyleft/gpl.html
*/

// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
jimport('joomla.filesystem.path');


class RsfilesControllerRsfiles extends rsfilesController
{
	/**
	 * constructor (registers additional tasks to methods)
	 * @return void
	 */
	function __construct()
	{
		parent::__construct();

		// Register Extra tasks
		$this->registerTask('apply' ,  'save');
	}
	
	/**
	 * save a record (and redirect to main page)
	 * @return void
	 */
	function save()
	{
		global $mainframe;
		$db = & JFactory::getDBO();
		$post = JRequest::get('post',JREQUEST_ALLOWRAW);
		$rsflConfigPost = $post['rsfilesConfig'];
		$tabposition = JRequest::getInt('tabposition', 0);
		
		$db->setQuery("SELECT * FROM `#__rsfiles_config`");
		$rsflConfigDb = $db->loadObjectList();
		foreach ($rsflConfigDb as $objConfig)
		{  
			if(isset($rsflConfigPost[$objConfig->ConfigName]))
			{
				
				$db->setQuery("UPDATE #__rsfiles_config SET ConfigValue='".$db->getEscaped($rsflConfigPost[$objConfig->ConfigName])."' WHERE ConfigName='".$objConfig->ConfigName."'");
				$db->query();
				$rsfilesConfig[$objConfig->ConfigName] = $rsflConfigPost[$objConfig->ConfigName];
			}
		} 
		$mainframe->setUserState('rsfilesConfig',$rsfilesConfig);
		$msg = JText::_('RSFL_SETTINGS_SAVED');
		
		if(isset($post['rsfl_htaccess']) && $post['rsfl_htaccess'] == 1)
		{
			$db->setQuery("SELECT ConfigValue FROM #__rsfiles_config WHERE ConfigName = 'download_folder'");
			$download_folder = $db->loadResult();
			
			if(!is_file($download_folder.DS.'.htaccess'))
				JFile::write($download_folder.DS.'.htaccess','deny from all');
		}

		$task = JRequest::getCmd('task');
		switch($task)
		{
			case 'apply':
				$link = 'index.php?option=com_rsfiles&task=settings&tabposition='.$tabposition;
			break;
		
			case 'save':
				$link = 'index.php?option=com_rsfiles';
			break;
		}	
		$this->setRedirect($link, $msg);
	}
	
	function savefolder()
	{
		$db = JFactory::getDBO();
		$post = JRequest::get('post');
		$defaultfolder = urldecode($post['default_folder']);
		
		
		$db->setQuery("UPDATE `#__rsfiles_config` SET ConfigValue = '".$db->getEscaped($defaultfolder)."' WHERE ConfigName = 'download_folder'");
		$db->query();
		
		$files = JFolder::files($defaultfolder,'.',true,true);
		
		foreach($files as $file)
		{
			$db->setQuery("UPDATE #__rsfiles_files SET FilePath = '".$db->getEscaped($file)."' WHERE hash = '".md5_file($file)."'");
			$db->query();
		}
		
		$db->setQuery("DELETE FROM #__rsfiles_files WHERE FilePath NOT LIKE '%".$db->getEscaped($db->getEscaped($defaultfolder))."%' ");
		$db->query();
	}
	
	
	/**
	 * cancel editing a record
	 * @return void
	 */
	function cancel()
	{
		$this->setRedirect( 'index.php?option=com_rsfiles', JText::_('RSFL_CANCEL' ) );
	}


	
}