<?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
*/

defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.controller');
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
jimport('joomla.filesystem.path');

class rsfilesControllerFiles extends rsfilesController
{
	function __construct()
	{
		parent::__construct();
		$this->registerTask('apply', 'save');
		$this->registerTask('unpublish', 'publish');
	}
	
	function publish()
	{
		$db = JFactory::getDBO();
		$cids = JRequest::getVar('cid');
		$task = JRequest::getCmd('task');
		$path = JRequest::getVar('path');
		$model = $this->getModel('files');
		$row =& JTable::getInstance('Rsfiles_Files','Table');
		
		$publish = $task == 'publish' ? 1 : 0;
		
		foreach ($cids as $cid)
		{
			$cid = urldecode($cid);
			$db->setQuery("SELECT IdFile FROM #__rsfiles_files WHERE FilePath = '".$db->getEscaped($cid)."' ");
			$id = $db->loadResult();
			
			if (empty($id))
			{
				$row->IdFile = null;
				$row->FilePath = $cid;
				$row->DateAdded = time();
				$row->ModifiedDate = time();
				$row->DownloadMethod = 0;
				$row->CanDownload = 0; 	 
				$row->CanView = 0;
				$row->IdUser = $user->id;
				if(is_file($cid))
					$row->hash = md5_file($cid);
				$row->hits = 0;
				$row->published = $publish;
				$row->store();
			}
			
			$db->setQuery("UPDATE #__rsfiles_files SET published = '".$publish."' WHERE IdFile = '".$id."' ");
			$db->query();
		}
		
		$path = isset($path) ? '&folder='.urlencode($path) : '';
		$this->setRedirect('index.php?option=com_rsfiles&task=files'.$path);
	}
	
	
	function upload()
	{
		$db = JFactory::getDBO();
		$user = JFactory::getUser();
		$files = JRequest::get('files');
		$post = JRequest::get('post');
		$path = $post['path'];
		$upload = $files['upload'];
		$model = $this->getModel('files');
		$row =& JTable::getInstance('Rsfiles_Files','Table');
		
		$result = JFile::upload($upload['tmp_name'], $path.DS.JFile::getName($upload['name']));
		
		if($result == true)
		{
			$db->setQuery("SELECT CanPerforMaintenance,CanDownload,CanView FROM #__rsfiles_files WHERE FilePath = '".$db->getEscaped(urldecode($post['path']))."' ");
			$permissions = $db->loadObject();
			if (empty($permissions))
			{
				$permissions = new stdClass();
				$permissions->CanPerforMaintenance = 0;
				$permissions->CanDownload = 0;
				$permissions->CanView = 0;
			}
			
			
			$row->IdFile = null;
			$row->FilePath = $path.DS.JFile::getName($upload['name']);
			$row->DateAdded = time();
			$row->ModifiedDate = time();
			$row->DownloadMethod = 0;
			$row->CanPerforMaintenance = $permissions->CanPerforMaintenance; 	 
			$row->CanDownload = $permissions->CanDownload; 	 
			$row->CanView = $permissions->CanView;
			$row->IdUser = $user->id;
			if(is_file($path.DS.JFile::getName($upload['name'])))
				$row->hash = md5_file($path.DS.JFile::getName($upload['name']));
			$row->hits = 0;
			$row->published = 1;
			$row->store();
			$msg = JText::_('RSFL_UPLOAD_OK');
		}
		else
			$msg = JText::_('RSFL_UPLOAD_FAILED');
		
		$this->setRedirect('index.php?option=com_rsfiles&task=files&folder='.urlencode($path),$msg);
	}
	
	function newdir()
	{
		$post = JRequest::get('post');
		$path = $post['path'];
		$dirname = $post['newfolder'];
		$model = $this->getModel('files');
		$row =& JTable::getInstance('Rsfiles_Files','Table');
		
		if(strlen($dirname) > 1)
			$result = JFolder::create($path.DS.$dirname);
		if($result == true)
		{
			$row->IdFile = null;
			$row->FilePath = $path.DS.$dirname;
			$row->DateAdded = time();
			$row->ModifiedDate = time();
			$row->DownloadMethod = 0;
			$row->CanDownload = 0; 	 
			$row->CanView = 0;
			$row->hits = 0;
			$row->published = 1;
			$row->store();
			$msg = JText::_('RSFL_FOLDER_CREATE_OK');
		}
		else
			$msg = JText::_('RSFL_FOLDER_CREATE_FAILED');
		
		$this->setRedirect('index.php?option=com_rsfiles&task=files&folder='.urlencode($path),$msg);
	}
	
	function remove()
	{
		$db = JFactory::getDBO();
		$post = JRequest::get('post');
		$cids = JRequest::getVar('cid');
		$path = $post['path'];
		$folders = 0;
		$files = 0;
		
		foreach($cids as $cid)
		{
			$cid = urldecode($cid);
			if(is_dir($cid))
			{
				$folders++;
				$subfolders = JFolder::folders($cid,'.',true,true);
				$subfiles = JFolder::files($cid,'.',true,true);
				$subs = array_merge($subfolders,$subfiles);
				foreach($subs as $sub)
				{
					$db->setQuery("DELETE FROM #__rsfiles_files WHERE FilePath = '".$db->getEscaped($sub)."'");
					$db->query();
				}
				JFolder::delete($cid);
			}
			
			if(is_file($cid))
			{				
				$files++;
				JFile::delete($cid);
			}
			
			$db->setQuery("DELETE FROM #__rsfiles_files WHERE FilePath = '".$db->getEscaped($cid)."'");
			$db->query();
		}
		
		if($folders == 0 && $files > 0)
			$msg = JText::sprintf('RSFL_DELETED_FILES',$files);
		elseif($folders > 0 && $files == 0)
			$msg = JText::sprintf('RSFL_DELETED_FOLDERS',$folders);
		elseif($folders > 0 && $files > 0)
			$msg = JText::sprintf('RSFL_DELETED_FOLDERS_FILES',$files,$folders);
		else 
			$msg = JText::_('RSFL_FILE_DELETE_ERROR');

		$this->setRedirect('index.php?option=com_rsfiles&task=files&folder='.urlencode($path),$msg);
	}
	
	function cancel()
	{
		$this->setRedirect('index.php?option=com_rsfiles&task=files');
	}
	
	function save()
	{
		global $mainframe;
		$db = JFactory::getDBO();
		$model = $this->getModel('files');
		$post = JRequest::get('post',JREQUEST_ALLOWHTML);
		$files = JRequest::get('files');
		$thumb = $files['thumb'];
		$screenshots = @$files['screenshots'];
		$target = JPATH_SITE.DS.'components'.DS.'com_rsfiles'.DS.'images'.DS.'screenshots'.DS;
		$rsfilesConfig = rsfilesHelper::getConfig();
		$row =& JTable::getInstance('Rsfiles_Files','Table');
		
		$post['CanDownload'] = (isset($post['CanDownload'])) ? implode(',',$post['CanDownload']) : '';
		$post['CanPerforMaintenance'] = (isset($post['CanPerforMaintenance'])) ? implode(',',$post['CanPerforMaintenance']) : '';
		$post['CanView'] = (isset($post['CanView'])) ? implode(',',$post['CanView']) : '';
		$post['ExtendMaintnance'] = (isset($post['ExtendMaintnance'])) ? $post['ExtendMaintnance'] : 0;
		$post['ExtendView'] = (isset($post['ExtendView'])) ? $post['ExtendView'] : 0;
		$post['ExtendDownload'] = (isset($post['ExtendDownload'])) ? $post['ExtendDownload'] : 0;
		
		
		if(!$row->bind($post)) {
			return JError::raiseWarning(500, $row->getError());
		}
		
		if(is_file($row->FilePath))
			$row->hash = md5_file($row->FilePath);
		$row->FileSize = RsfilesHelper::formatBytes(filesize($row->FilePath));
		$row->DateAdded = strtotime($row->DateAdded);
		$row->ModifiedDate = time();
		
		
		if(is_dir($row->FilePath))
		{
			
			$subfolders = JFolder::folders($row->FilePath,'.',true,true);
			$subfiles = JFolder::files($row->FilePath,'.',true,true);
			$subs = array_merge($subfolders,$subfiles);
			
			foreach($subs as $sub)
			{
				$newrow = clone($row);
				$newrow->IdFile = null;
				$newrow->FilePath = $sub;
				if($newrow->IdFile == 0) $newrow->DateAdded = time();
				if(is_file($sub)) $newrow->hash = md5_file($sub);
				
				$newrow->store();
				
				if($post['ExtendView'] == 1)
				{
					$db->setQuery("UPDATE #__rsfiles_files SET CanView = '".$row->CanView."' WHERE FilePath = '".$db->getEscaped($sub)."'");
					$db->query();
				}
				
				if($post['ExtendDownload'] == 1)
				{
					$db->setQuery("UPDATE #__rsfiles_files SET CanDownload = '".$row->CanDownload."' WHERE FilePath = '".$db->getEscaped($sub)."'");
					$db->query();
				}
				
				if($post['ExtendMaintnance'] == 1)
				{
					$db->setQuery("UPDATE #__rsfiles_files SET CanPerforMaintenance = '".$row->CanPerforMaintenance."' WHERE FilePath = '".$db->getEscaped($sub)."'");
					$db->query();
				}
			}
		}
		
		if($row->store()) 
		{
			$msg = JText::_('RSFL_FILE_SAVED');
			$extension = @JFile::getExt($thumb['name']);
			$thumb['name'] = JPATH_ROOT.DS.'components'.DS.'com_rsfiles'.DS.'images'.DS.'thumbs'.DS.'files'.DS.$row->IdFile;
			if(!$thumb['error'] && !empty($thumb['tmp_name']))
			{
				//create the thumbnail
				$uploaded = RsfilesHelper::createThumb($thumb['tmp_name'], $thumb['name'], $rsfilesConfig['thumb_width'],$extension);
				
				if($uploaded)
				{
					$db->setQuery("UPDATE #__rsfiles_files SET FileThumb = '".JFile::getName($thumb['name'].'.'.$extension)."' WHERE IdFile ='".$row->IdFile."'");
					$db->query();
				}
			}
			
			for($i=0;$i<10;$i++)
			{
				if(!empty($screenshots['tmp_name'][$i]))
				{
					$extension = end(explode('.', $screenshots['name'][$i]));

						if(strtolower($extension) != '' && in_array(strtolower($extension),array('jpg','png')) !== false)
						{
							if($screenshots['tmp_name'][$i]!='')
							{
								$fileLocation = uniqid('',FALSE)."_". basename( $screenshots['name'][$i]);
								$uplfile = $target . $fileLocation;
								move_uploaded_file($screenshots['tmp_name'][$i] ,$uplfile);
								$db->setQuery("INSERT INTO #__rsfiles_screenshots (IdFile,Path) VALUES ('".$row->IdFile."','".$fileLocation."')"); 
								$db->query();
							}
						} else $mainframe->redirect('index.php?option=com_rsfiles&task=editfile&cid='.$row->FilePath , JText::_('RSFL_ONLY_JPG_PNG'));
				}
			}
		}
		else $msg = JText::_('RSFL_FILE_SAVE_ERROR');
		
		$task = JRequest::getCmd('task');
		switch($task)
		{
			case 'apply':
				$link = 'index.php?option=com_rsfiles&task=editfile&cid='.urlencode($row->FilePath);
			break;
		
			case 'save':
				$path = explode(DS,$row->FilePath);
				$count = count($path);
				unset($path[$count-1]);
				$path = implode(DS,$path);
				if(!empty($path)) $pathToReturn = '&folder='.urlencode($path);
				$link = 'index.php?option=com_rsfiles&task=files'.$pathToReturn;
			break;
		}
		$this->setRedirect($link,$msg);
	}
	
	function deletethumb()
	{
		$db = JFactory::getDBO();
		$cid = JRequest::getInt('cid');
		
		//see if the file has a thumb
		$db->setQuery("SELECT FilePath,FileThumb FROM #__rsfiles_files WHERE IdFile= ".$cid);
		$thumb = $db->loadObject();
		
		if(!empty($thumb))
		{
			$db->setQuery("UPDATE #__rsfiles_files SET FileThumb = '' WHERE IdFile=".$cid);
			$db->query();
			JFile::delete(JPATH_SITE.DS.'components'.DS.'com_rsfiles'.DS.'images'.DS.'thumbs'.DS.'files'.DS.$thumb->FileThumb);
		}
		
		$this->setRedirect('index.php?option=com_rsfiles&task=editfile&cid='.urlencode($thumb->FilePath),JText::_('RSFL_THUMB_DELETED'));
	}
	
	
	function savemirror()
	{
		global $mainframe;
		$db = JFactory::getDBO();
		$post = JRequest::get('post');
		$model = $this->getModel('files');
		$row =& JTable::getInstance('Rsfiles_Mirrors','Table');
		$row->bind($post);
		
		$row->store();
		
		$db->setQuery("SELECT FilePath FROM #__rsfiles_files WHERE IdFile = ".$row->IdFile);
		$path = $db->loadResult();
		
		$mainframe->redirect('index.php?option=com_rsfiles&task=editfile&cid='.urlencode($path),JText::_('RSFL_MIRROR_SAVED'));
	}

	
	function deletemirror()
	{
		$db = JFactory::getDBO();
		$cid = JRequest::getVar('cid');
		$path = JRequest::getVar('IdFile');
		
		$db->setQuery("DELETE FROM #__rsfiles_mirrors WHERE IdMirror =".$cid);
		$db->query();
		
		$this->setRedirect('index.php?option=com_rsfiles&task=editfile&cid='.urlencode($path),JText::_('RSFL_MIRROR_DELETED'));
	}
	
	
	function deletescreenshot()
	{
		$db = JFactory::getDBO();
		$cid = JRequest::getVar('cid');
		$path = JRequest::getVar('IdFile');
		
		$db->setQuery("SELECT Path FROM #__rsfiles_screenshots WHERE IdScreenshot = ".$cid);
		$spath = $db->loadResult();
		
		JFile::delete(JPATH_SITE.DS.'components'.DS.'com_rsfiles'.DS.'images'.DS.'screenshots'.DS.$spath);
		$db->setQuery("DELETE FROM #__rsfiles_screenshots WHERE IdScreenshot =".$cid);
		$db->query();
		
		$this->setRedirect('index.php?option=com_rsfiles&task=editfile&cid='.urlencode($path),JText::_('RSFL_SCREENSHOT_DELETED'));
	}
	
	function purge()
	{
		global $mainframe;
		$db = JFactory::getDBO();
		$rsfilesConfig = rsfilesHelper::getConfig();
		$path = $rsfilesConfig['download_folder'];
		$thumb_path = JPATH_ROOT.DS.'components'.DS.'com_rsfiles'.DS.'images'.DS.'thumbs'.DS.'files';
		
		$subfolders = JFolder::folders($path,'.',true,true);
		$subfiles = JFolder::files($path,'.',true,true);
		$subs = array_merge($subfolders,$subfiles);
		
		$array = array();
		foreach($subs as $sub)
			$array[] = "'".$db->getEscaped($sub)."'";
		
		$subs = implode(',',$array);
		
		$db->setQuery("DELETE FROM #__rsfiles_files WHERE FilePath NOT IN (".$subs.") ");
		$db->query();
		$affectedRows   = $db->getAffectedRows();
		
		$tfiles = JFolder::files($thumb_path);
		foreach ($tfiles as $file)
		{
			if($file == 'index.html') continue;
			$db->setQuery("SELECT IdFile FROM #__rsfiles_files WHERE FileThumb = '".$file."' ");
			$result = $db->loadResult();
			if(empty($result))
				JFile::delete($thumb_path.DS.$file);
		}
		
		$msg = JText::sprintf('RSFL_PURGE_OK',$affectedRows);
		
		if($affectedRows == 0) $msg = JText::_('RSFL_PURGE_NONE');
		
		$this->setRedirect('index.php?option=com_rsfiles&task=files',$msg);
	}
	
	function enablestatistics()
	{
		$db = JFactory::getDBO();
		$cids = JRequest::getVar('cid');
		
		foreach($cids as $cid)
		{
			$cid = urldecode($cid);
			if (is_dir($cid)) continue;
			$db->setQuery("UPDATE #__rsfiles_files SET FileStatistics = 1 WHERE FilePath = '".$db->getEscaped($cid)."' ");
			$db->query();
		}
		
		$this->setRedirect('index.php?option=com_rsfiles&task=files',JText::_('RSFL_ENABLE_STATISTICS_MESSAGE'));
	}
	
}
?>