<?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();
 
jimport( 'joomla.application.component.model' );
jimport('joomla.filesystem.file');

class rsfilesModelFiles extends JModel
{
	var $_query;
	var $_data;
	var $_total=null;
	var $_total_files=null;
	var $_pagination=null;
	var $_folder=null;
	var $_defaulttheme=null;
	
	function _buildQuery()
	{
		global $mainframe;
		$db =& JFactory::getDBO();
		
		$this->_query="SELECT IdFile , FileName , RealFileName FROM #__rsfiles_files";
	}
	
	function __construct()
	{
		global $mainframe,$option;
		$db = JFactory::getDBO();
		$rsfilesConfig = RsfilesHelper::getConfig();
		parent::__construct();

		$folder = JRequest::getVar('folder');		
		
		if (is_dir($rsfilesConfig['download_folder'].DS.$folder) && !empty($folder))
			$this->_folder = $rsfilesConfig['download_folder'].DS.$folder;
		else
			$this->_folder = $rsfilesConfig['download_folder'];
		
		//statistics for folders
		$this->_addStatistics($this->_folder);
		
		$limit = $rsfilesConfig['nr_per_page'];
		$limitstart = JRequest::getVar('limitstart', 0, 'int');
		
		// In case limit has been changed, adjust it
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);

		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
		
		$db->setQuery("SELECT IdTheme FROM #__rsfiles_themes WHERE `default` = 1 ");
		$this->_defaulttheme = $db->loadResult();
	}
	
	
	function getFolderFiles()
	{
		global $mainframe;
		$db = JFactory::getDBO();
		$rsfilesConfig = RsfilesHelper::getConfig();
		$folders = array();
		$files = array();
		$parent = JRequest::getVar('folder');
		$Itemid = JRequest::getVar('Itemid','','request');
		$itemid = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		$params = &JComponentHelper::getParams( 'com_rsfiles' );
		$all_folders = JFolder::folders($this->_folder);
		$all_files = JFolder::files($this->_folder);
		$layout = JRequest::getWord('layout');
		
		
		if ($layout == 'timeperiod')
		{
			$start = strtotime($params->get('start',date('m/d/Y',time())));
			$end   = strtotime($params->get('end',date('m/d/Y',time()+86400)));
		}
		
		
		foreach ($all_folders as $folder)
		{				
			if (JFile::stripExt($folder) == '') continue;
			
			$db->setQuery("SELECT FileName,FileDescription,FileThumb,DateAdded,hits,published FROM #__rsfiles_files WHERE FilePath ='".$db->getEscaped($this->_folder.DS.$folder)."'");
			$details = $db->loadObject();
			$folderpublished = isset($details->published) ? $details->published : 1;
			
			
			if (!$folderpublished) continue;
			$element = new stdClass();
			$element->name = empty($details->FileName) ? $folder : $details->FileName;
			$element->fullpath = urlencode((empty($parent) ? '' : $parent.DS).$folder);
			if(!$this->getPermissionView(urldecode($element->fullpath))) continue;
			
			$dateadded_folder = empty($details->DateAdded) ? filemtime($this->_folder.DS.$folder) : $details->DateAdded;
			$element->dateadded = date($rsfilesConfig['global_date'],$dateadded_folder);
			if ($layout == 'timeperiod' && ($dateadded_folder < $start || $dateadded_folder > $end)) continue;	
			$element->description = ($rsfilesConfig['show_descriptions'] == 0) ? '' : (empty($details->FileDescription) ? JText::_('RSFL_NO_DESCRIPTION') : $details->FileDescription );
			$element->thumb = empty($details->FileThumb) ? '' : '<img src="'.JURI::root().'components/com_rsfiles/images/thumbs/files/'.$details->FileThumb.'" />' ;
			$element->hits = empty($details->hits) ? 0 : $details->hits;
			$element->time = $dateadded_folder;
			$element->type = 'folder';
			$folders[] = $element;
		}
		
		switch($rsfilesConfig['default_order'])
		{
			case 'name':
				$folders = RsfilesHelper::sort_array_name($folders, $rsfilesConfig['default_order_way']);
			break;
			
			case 'date':
				if ($rsfilesConfig['default_order_way'] == 'ASC')
					usort($folders, array('RsfilesHelper', 'sort_time_asc'));
				else
					usort($folders, array('RsfilesHelper', 'sort_time_desc'));
			break;
			
			case 'hits':
				if ($rsfilesConfig['default_order_way'] == 'ASC')
					usort($folders, array('RsfilesHelper', 'sort_hits_asc'));
				else
					usort($folders, array('RsfilesHelper', 'sort_hits_desc'));
			break;
		}
	
		
		foreach ($all_files as $file)
		{
			
			if(JFile::stripExt($file) == '') continue;
			
			$db->setQuery("SELECT f.IdFile ,f.FileName , f.FilePath, f.FileDescription ,f.FileStatistics , f.hash , f.FileThumb , u.username , f.IdLicense , f.FileVersion ,f.hits , f.published ,f.DateAdded ,l.LicenseName FROM #__rsfiles_files f LEFT JOIN #__users u ON u.id=f.IdUser LEFT JOIN #__rsfiles_licenses l ON l.IdLicense=f.IdLicense WHERE f.FilePath ='".$db->getEscaped($this->_folder.DS.$file)."'");
			$details = $db->loadObject();
			$element = new stdClass();

			$filepublish = isset($details->published) ? $details->published : 1;
			
			if (!$filepublish) continue;
			$element->id = empty($details->IdFile) ? 0 : $details->IdFile;
			$element->name = empty($details->FileName) ? $file : $details->FileName;
			$element->fullpath = urlencode((empty($parent) ? '' : $parent.DS).$file);
			if(!$this->getPermissionView(urldecode($element->fullpath))) continue;
			
			$dateadded_file = empty($details->DateAdded) ? filemtime($this->_folder.DS.$file) : $details->DateAdded;
			$element->dateadded = date($rsfilesConfig['global_date'],$dateadded_file);
			if ($layout == 'timeperiod' && ($dateadded_file < $start || $dateadded_file > $end)) continue;
			
			$element->size = RsfilesHelper::formatBytes(filesize($this->_folder.DS.$file));
			$element->hits = (empty($details->hits) || ($details->hits == 0 && $details->FileStatistics == 0)) ? 0 : $details->hits;
			$element->time = $dateadded_file;
			$element->owner = (empty($details->username) || $details->username == 0) ? JText::_('RSFL_GUEST') : $details->username;
			$element->filetype = JFile::getExt($file).' ('.JText::_('RSFL_MIMETYPE').' '.RsfilesHelper::mimetype(strtolower(JFile::getExt($file))).')';
			$element->filedescription = ($rsfilesConfig['show_descriptions'] == 0) ? '' : (empty($details->FileDescription) ? JText::_('RSFL_NO_DESCRIPTION') : $details->FileDescription );
			$element->fileversion = empty($details->FileVersion) ? '' : $details->FileVersion;
			$element->checksum = empty($details->hash) ? JText::_('RSFL_NO_CHECKSUM') : $details->hash;
			$element->filelicense = (empty($details->IdLicense) || $details->IdLicense == 0) ? '' : '<a href="'.JRoute::_('index.php?option=com_rsfiles&view=files&layout=license&cid='.$details->IdLicense.$itemid,false).'">'.$details->LicenseName.'</a>';
			$element->thumb = empty($details->FileThumb) ? '' : '<img src="'.JURI::root().'components/com_rsfiles/images/thumbs/files/'.$details->FileThumb.'" />' ;
			$element->lastmodified = date($rsfilesConfig['global_date'],filemtime($this->_folder.DS.$file));
			$element->filename = JFile::getName($file);		
			$element->type = 'file';		
			$files[] = $element;
		}
		
		switch($rsfilesConfig['default_order'])
		{
			case 'name':
				$files = RsfilesHelper::sort_array_name($files, $rsfilesConfig['default_order_way']);
			break;
			
			case 'date':
				if ($rsfilesConfig['default_order_way'] == 'ASC')
					usort($files, array('RsfilesHelper', 'sort_time_asc'));
				if ($rsfilesConfig['default_order_way'] == 'DESC')
					usort($files, array('RsfilesHelper', 'sort_time_desc'));
			break;
			
			case 'hits':
				if ($rsfilesConfig['default_order_way'] == 'ASC')
					usort($files, array('RsfilesHelper', 'sort_hits_asc'));
				if ($rsfilesConfig['default_order_way'] == 'DESC')
					usort($files, array('RsfilesHelper', 'sort_hits_desc'));
			break;
		}	
		
		
		$data = array_merge($folders,$files);		
		
		$this->_total = count($data);
		
		//pagination
		$data = array_slice($data,$this->getState('limitstart'),$this->getState('limit'));
		
		return $data;
	}
	
	function getTotal()
	{
		return $this->_total;
	}
	
	function getPagination()
	{
		// Load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit'));
		}
		return $this->_pagination;
	}
	
	function getCurrent()
	{
		return $this->_folder;
	}
	
	function getCurrentFolder()
	{
		$folder = JRequest::getVar('folder',''); 
		if(empty($folder)) 	return '';
		return '&folder='.urlencode(JRequest::getVar('folder'));
	}
	
	function getCurrentPath()
	{
		$path = JRequest::getVar('path',''); 
		if(empty($path)) 	return '';
		return '&path='.urlencode(JRequest::getVar('path'));
	}
	
	function getPrevious()
	{
		$folder = JRequest::getVar('folder');
		$elements = explode(DS, $folder);
		array_pop($elements);
		
		return urlencode(implode(DS, $elements));	
	}
	
	function getPreviousPath()
	{
		$path = JRequest::getVar('path');
		$elements = explode(DS, $path);
		array_pop($elements);
		
		return urlencode(implode(DS, $elements));	
	}	
	
	function getFile()
	{
		global $mainframe;
		$db = JFactory::getDBO();
		$user = JFactory::getUser();
		$rsfilesConfig = RsfilesHelper::getConfig();
		$Itemid = JRequest::getVar('Itemid','','request');
		$itemid = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		$fromemail = JRequest::getVar('email');
		
		$file = JRequest::getVar('path');
		if($fromemail) $file = base64_decode($file);
		
		$fullpath = $rsfilesConfig['download_folder'].DS.$file;
		
		//if the users get outs of the root 
		if (strpos(realpath($fullpath), $rsfilesConfig['download_folder']) !== 0) $mainframe->redirect(JRoute::_('index.php?option=com_rsfiles&view=files'.$itemid,false));
		
		//check first if the user can download the file
		if(!$this->getPermissionDownload())
			$mainframe->redirect(JRoute::_('index.php?option=com_rsfiles&view=files'.$itemid,false));
		
		$ext = end(explode(DS,$fullpath));
		if(JFile::stripExt($ext) == '') $mainframe->redirect(JRoute::_('index.php?option=com_rsfiles&view=files'.$itemid,false));
		
		if(is_file($fullpath))
		{
			$this->_addStatistics($fullpath);
			
			@ob_end_clean();
			$filename = basename($fullpath);
			header("Cache-Control: public, must-revalidate");
			header('Cache-Control: pre-check=0, post-check=0, max-age=0');
			header("Pragma: no-cache");
			header("Expires: 0"); 
			header("Content-Description: File Transfer");
			header("Expires: Sat, 01 Jan 2000 01:00:00 GMT");
			header("Content-Type: application/octet-stream");
			header("Content-Length: ".(string) filesize($fullpath));
			header('Content-Disposition: attachment; filename="'.$filename.'"');
			header("Content-Transfer-Encoding: binary\n");
			$this->readfile_chunked($fullpath);
			
			//send email to admin 
			if($rsfilesConfig['email_admin_enable'] == 1)
			{
				$to = $rsfilesConfig['email_admin_to'];
				$from = $rsfilesConfig['email_from'];
				$fromname = $rsfilesConfig['email_from_name'];
				$reply = $rsfilesConfig['email_reply'];
				$replyname = $rsfilesConfig['email_reply_name'];
				$subject = $rsfilesConfig['email_admin_subject'];
				$mode = $rsfilesConfig['email_admin_mode'];
				$cc = !empty($rsfilesConfig['email_cc']) ? $rsfilesConfig['email_cc'] : null;
				$bcc = !empty($rsfilesConfig['email_bcc']) ? $rsfilesConfig['email_bcc'] : null;
				$message = $rsfilesConfig['email_admin_message'];
				
				$bad = array('{filename}','{ip}','{username}');
				$good = array($fullpath,$_SERVER['REMOTE_ADDR'],empty($user->username) ? JText::_('RSFL_GUEST') : $user->username);
				
				$message = str_replace($bad,$good,$message);
				
				if(!empty($to))
					JUtility::sendMail($from , $fromname , $to , $subject , $message , $mode , $cc , $bcc , null , $reply , $replyname);
			}
			exit();
		}
		
	}
	
	
	function _addStatistics($file)
	{		
		global $mainframe;
		$db = JFactory::getDBO();
		$user = JFactory::getUser();
		$rsfilesConfig = RsfilesHelper::getConfig();
		$row =& JTable::getInstance('Rsfiles_Files','Table');
		
		//check to see if the file is in the DB
		$db->setQuery("SELECT IdFile,FileStatistics FROM #__rsfiles_files WHERE FilePath = '".$db->getEscaped($file)."' ");
		$details = $db->loadObject();
		
		if(!empty($details))
		{
			if(is_file($file))
			if($details->FileStatistics == 1 && !empty($details->IdFile))
			{
				$db->setQuery("UPDATE #__rsfiles_files SET hits = hits + 1 WHERE IdFile = ".$details->IdFile);
				$db->query();
				$db->setQuery("INSERT INTO #__rsfiles_statistics SET Date = ".time()." , Ip = '".$_SERVER['REMOTE_ADDR']."' , UserId = ".$user->id." , IdFile = ".$details->IdFile);
				$db->query();
			}
			
			if(is_dir($file) && !empty($details->IdFile))
			{
				$db->setQuery("UPDATE #__rsfiles_files SET hits = hits + 1 WHERE IdFile = ".$details->IdFile);
				$db->query();
			}
		}
		else
		{
			if (is_dir($file) && $rsfilesConfig['download_folder'] == $this->_folder) return false;
			
			$row->IdFile = null;
			$row->FilePath = $file;
			$row->DateAdded = time();
			$row->ModifiedDate = time();
			$row->DownloadMethod = 0;
			$row->CanDownload = 0; 	 
			$row->CanView = 0;
			if(is_file($file))
				$row->hash = md5_file($file);
			$row->hits = 0;
			$row->store();
		}
	}
	
	//Permission to download
	function getPermissionDownload()
	{
		global $mainframe;
		$db = JFactory::getDBO();
		$user = JFactory::getUser();
		$rsfilesConfig =RsfilesHelper::getConfig();
		$fromemail = JRequest::getVar('email');
		
		$file = JRequest::getVar('path');
		if($fromemail) $file = base64_decode($file);
		$fullpath = $rsfilesConfig['download_folder'].DS.$file;
		
		$gid = $user->gid;
		if($gid == 0) $gid = 29;
		
		$db->setQuery("SELECT CanDownload FROM #__rsfiles_files WHERE FilePath = '".$db->getEscaped($fullpath)."'");
		$candownload = $db->loadResult();
		$groups = explode(',',$candownload);
		
		if($candownload == '' ) return true;
		if (in_array(0,$groups)) return true;
		
		$access = false;
		
		foreach($groups as $group)
		{
			if ($group == 0) continue;
			$db->setQuery("SELECT IdUsers , IdAcls FROM #__rsfiles_group_details WHERE IdGroup = ".$group);
			$details = $db->loadObject();
			
			$uids = explode(',',$details->IdUsers);
			$aids = explode(',',$details->IdAcls);
			
			if (in_array($gid,$aids) || (in_array($user->id,$uids) && !empty($details->IdUsers))) $access = true; 
			
		}
		
		return $access;
	}
	
	//Permission to manage files and folders
	function getPermissionMaintenance()
	{
		global $mainframe;
		$db = JFactory::getDBO();
		$user = JFactory::getUser();
		$rsfilesConfig = RsfilesHelper::getConfig();
		
		$file = JRequest::getVar('path');
		$folder = JRequest::getVar('folder');
		if(isset($file)) $path = $file;
		if(isset($folder)) $path = $folder;
		
		if(!isset($path)) return false;
		
		$fullpath = $rsfilesConfig['download_folder'].DS.urldecode($path);
		
		$gid = $user->gid;
		if($gid == 0) $gid = 29;
		
		$db->setQuery("SELECT CanPerforMaintenance FROM #__rsfiles_files WHERE FilePath = '".$db->getEscaped($fullpath)."'");
		$maintainance = $db->loadResult();
		$groups = explode(',',$maintainance);
		
		if($maintainance == '') return false;
		if (in_array(0,$groups)) return true;
		$access = false;
		
		foreach($groups as $group)
		{
			if ($group == 0) continue;
			$db->setQuery("SELECT IdUsers , IdAcls FROM #__rsfiles_group_details WHERE IdGroup = ".$group);
			$details = $db->loadObject();
			
			$uids = explode(',',$details->IdUsers);
			$aids = explode(',',$details->IdAcls);
			
			if (in_array($gid,$aids) || (in_array($user->id,$uids) && !empty($details->IdUsers))) $access = true; 
			
		}
		
		return $access;
	}
	
	function getPermissionView($fpath = null)
	{
		global $mainframe;
		$db = JFactory::getDBO();
		$user = JFactory::getUser();
		$db->setQuery("SELECT ConfigValue FROM #__rsfiles_config WHERE ConfigName = 'download_folder'");
		$dld_fol = $db->loadResult();
		
		if(empty($fpath))
		{
			$file = JRequest::getVar('path');
			$folder = JRequest::getVar('folder');
			if(isset($file)) $path = $file;
			if(isset($folder)) $path = $folder;
			$path = empty($path) ? '' : DS.$path;
			$fullpath = $dld_fol.$path;			
		} else 
		{
			if(strpos($fpath,$dld_fol) !== false)
				$fullpath = $fpath;
			else
				$fullpath = $dld_fol.DS.$fpath;
		}
		
		if($fullpath == $dld_fol) return true;
		
		$gid = $user->gid;
		if($gid == 0) $gid = 29;
		
		$db->setQuery("SELECT CanView FROM #__rsfiles_files WHERE FilePath = '".$db->getEscaped($fullpath)."'");
		$maintainance = $db->loadResult();
		$groups = explode(',',$maintainance);
		
		
		if ($maintainance == '') return true;
		if (in_array(0,$groups)) return true;
		
		$access = false;
		
		foreach($groups as $group)
		{
			if ($group == 0) continue;
			$db->setQuery("SELECT IdUsers , IdAcls FROM #__rsfiles_group_details WHERE IdGroup = ".$group);
			$details = $db->loadObject();
			
			$uids = explode(',',$details->IdUsers);
			$aids = explode(',',$details->IdAcls);
			
			if (in_array($gid,$aids) || (in_array($user->id,$uids) && !empty($details->IdUsers))) $access = true; 
			
		}
		
		return $access;
	}
	
	function getFileLayout()
	{
		$db = JFactory::getDBO();
		$db->setQuery("SELECT TemplateLayout FROM #__rsfiles_templates WHERE IdTheme = '".$this->_defaulttheme."' AND Type = 1");
		
		return $db->loadResult();
	}
	
	function getDownloadLayout()
	{
		$db = JFactory::getDBO();
		$db->setQuery("SELECT TemplateLayout FROM #__rsfiles_templates WHERE IdTheme = '".$this->_defaulttheme."' AND Type = 2");
		
		return $db->loadResult();
	}
	
	function getDetailsLayout()
	{
		$db = JFactory::getDBO();
		$db->setQuery("SELECT TemplateLayout FROM #__rsfiles_templates WHERE IdTheme = '".$this->_defaulttheme."' AND Type = 3");
		
		return $db->loadResult();
	}
	
	function getFilesHeader()
	{
		$db = JFactory::getDBO();
		$db->setQuery("SELECT TemplateHeader FROM #__rsfiles_templates WHERE IdTheme = '".$this->_defaulttheme."' AND Type = 1");
		
		return $db->loadResult();
	}
	
	function getPreview()
	{
		global $mainframe;
		$db = JFactory::getDBO();
		$rsfilesConfig = RsfilesHelper::getConfig();
		$file = urldecode(JRequest::getVar('path'));
		$fullpath = $this->_folder.DS.$file;
		
		
		$allowed = array('pdf','txt','jpg','jpeg','gif','png');
		$extension = strtolower(JFile::getExt($fullpath));
		$extensions = explode(',',strtolower($rsfilesConfig['preview_files']));
		
		if(!in_array($extension,$allowed))
		{
			echo JText::_('RSFL_NO_PREVIEW');
			exit;
		}
		
		if(in_array($extension,$extensions))
		{
			if($extension == 'pdf')
			{
				header("Content-type:application/pdf");
				header("Content-Disposition:inline;filename='".$file."'");
				readfile($fullpath);
				exit();
			}
			
			if($extension == 'txt')
			{
				$o = fopen($fullpath,'r');
				$c = fread($o,filesize($fullpath));
				fclose($o);
				echo nl2br($c);
			}
			
			
			if($extension == 'jpg' || $extension == 'jpeg' || $extension == 'gif' || $extension == 'png')
			{				
				jimport('joomla.environment.browser');
				$browser = &JBrowser::getInstance();
				
				if ($browser->getBrowser() == 'konqueror' && $extension == 'jpg') $extension = 'jpeg';
				
				if ($browser->getBrowser() != 'msie') 
					header('Content-Type: image/'.$extension);
				
				readfile($fullpath);
				
				die();
			}
		}
	}
	
	function getFileDetails()
	{
		global $mainframe;
		$db = JFactory::getDBO();
		$rsfilesConfig = RsfilesHelper::getConfig();
		
		$path = JRequest::getVar('path','','request');
		$fullpath = $rsfilesConfig['download_folder'].DS.$path;
		
		$db->setQuery("SELECT f.FileName , f.FilePath, f.FileDescription ,f.FileStatistics , f.DateAdded , f.DownloadMethod , f.FileVersion , f.hits , f.hash , f.FileThumb , u.username , f.IdLicense , l.LicenseName FROM #__rsfiles_files f LEFT JOIN #__users u ON u.id=f.IdUser LEFT JOIN #__rsfiles_licenses l ON l.IdLicense=f.IdLicense WHERE FilePath = '".$db->getEscaped($fullpath)."' ");
		
		return $db->loadObject();
		
	}
	
	function getLicense()
	{
		$db = JFactory::getDBO();
		$cid = JRequest::getVar('cid','','request');
		
		$db->setQuery("SELECT LicenseName,LicenseText FROM #__rsfiles_licenses WHERE IdLicense = ".$cid);
		
		return $db->loadObject();
		
	}
	
	function getMirrors()
	{
		global $mainframe;
		$db = JFactory::getDBO();
		$rsfilesConfig = RsfilesHelper::getConfig();
		
		$path = JRequest::getVar('path','','request');
		$fullpath = $rsfilesConfig['download_folder'].DS.$path;
		
		$db->setQuery("SELECT m.MirrorName , m.MirrorURL FROM #__rsfiles_mirrors m LEFT JOIN #__rsfiles_files f ON f.IdFile=m.IdFile WHERE f.FilePath = '".$db->getEscaped($fullpath)."'");
		return $db->loadObjectList();
	}
	
	function getScreenshots()
	{
		global $mainframe;
		$db = JFactory::getDBO();
		$rsfilesConfig = RsfilesHelper::getConfig();
		
		$path = JRequest::getVar('path','','request');
		$fullpath = $rsfilesConfig['download_folder'].DS.$path;
		
		$db->setQuery("SELECT s.Path FROM #__rsfiles_screenshots s LEFT JOIN #__rsfiles_files f ON f.IdFile=s.IdFile WHERE f.FilePath = '".$db->getEscaped($fullpath)."'");
		return $db->loadObjectList();
	}
	
	function getResults()
	{
		global $mainframe;
		$db = JFactory::getDBO();
		$post = JRequest::get('post');
		$rsfilesConfig =RsfilesHelper::getConfig();
		$Itemid = JRequest::getVar('Itemid','','request');
		$itemid = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		$files = array();
		
		$subfolders = JFolder::folders($rsfilesConfig['download_folder'],'.',true,true);
		$subfiles = JFolder::files($rsfilesConfig['download_folder'],'.',true,true);
		$all_files = array_merge($subfolders,$subfiles);
		
		
		foreach($all_files as $file)
		{
			$extension = end(explode(DS,$file));			
			if(JFile::stripExt($extension) == '') continue;
			
			$db->setQuery("SELECT f.IdFile ,f.FileName , f.FilePath, f.FileDescription ,f.FileStatistics , f.hash , f.FileThumb , u.username , f.IdLicense , f.FileVersion ,f.hits, f.published ,f.DateAdded ,l.LicenseName FROM #__rsfiles_files f LEFT JOIN #__users u ON u.id=f.IdUser LEFT JOIN #__rsfiles_licenses l ON l.IdLicense=f.IdLicense WHERE f.FilePath ='".$db->getEscaped($file)."'");
			$details = $db->loadObject();
			$element = new stdClass();
			
			if(!$this->getPermissionView($file)) continue;
			$element->name = empty($details->FileName) ? JFile::getName($file) : $details->FileName;
			$element->description = empty($details->FileDescription) ? '' : $details->FileDescription;
			$element->hits = empty($details->hits) ? 0 : $details->hits;
			$element->time = empty($details->DateAdded) ? filemtime($file) : $details->DateAdded;
			$element->type = is_dir($file) ? 'folder' : 'file';
			$element->size = RsfilesHelper::formatBytes(filesize($file));
			$element->owner = (empty($details->username) || $details->username == 0) ? JText::_('RSFL_GUEST') : $details->username;
			$element->filetype = is_file($file) ? JFile::getExt($file).' ('.JText::_('RSFL_MIMETYPE').' '.RsfilesHelper::mimetype(strtolower(JFile::getExt($file))).')' : '';
			$element->fileversion = empty($details->FileVersion) ? '' : $details->FileVersion;
			$element->checksum = empty($details->hash) ? JText::_('RSFL_NO_CHECKSUM') : $details->hash;
			$element->filelicense = (empty($details->IdLicense) || $details->IdLicense == 0) ? '' : '<a href="'.JRoute::_('index.php?option=com_rsfiles&view=files&layout=license&cid='.$details->IdLicense.$itemid,false).'">'.$details->LicenseName.'</a>';
			$element->dateadded = empty($details->DateAdded) ? date($rsfilesConfig['global_date'],filemtime($file)) : date($rsfilesConfig['global_date'],$details->DateAdded);
			$element->thumb = empty($details->FileThumb) ? '' : '<img src="'.JURI::root().'components/com_rsfiles/images/thumbs/files/'.$details->FileThumb.'" />' ;
			$element->lastmodified = date($rsfilesConfig['global_date'],filemtime($file));
			$element->filename = JFile::getName($file);	
			$element->fullpath = urlencode(str_replace($rsfilesConfig['download_folder'].DS,'',$file));			
			
			if(!empty($post['rsfl_keyword']))
			{
				if(isset($post['rsfl_search']))
				{
					if(isset($post['rsfl_search'][0]) && isset($post['rsfl_search'][1]))
					{	
						if(strpos(strtolower($element->name),strtolower($post['rsfl_keyword'])) === FALSE && strpos(strtolower($element->description),strtolower($post['rsfl_keyword'])) === FALSE) continue;
					}
					elseif($post['rsfl_search'][0] == 'name')
					{
						if(strpos(strtolower($element->name),strtolower($post['rsfl_keyword'])) === FALSE) continue;
					}
					elseif($post['rsfl_search'][0] == 'description')
					{
						if(strpos(strtolower($element->description),strtolower($post['rsfl_keyword'])) === FALSE) continue;
					}
				}
				else
				{
					if(strpos(strtolower($element->name),strtolower($post['rsfl_keyword'])) === FALSE && strpos(strtolower($element->description),strtolower($post['rsfl_keyword'])) === FALSE) continue;
				}
			}
			
			
			//check for publishing permission
			$published = 1;
			$path = str_replace($rsfilesConfig['download_folder'].DS,'',$file);
			$parts = explode(DS,urldecode($path));

			if (!empty($parts))
			foreach ($parts as $i => $part)
			{
				$db->setQuery("SELECT published FROM #__rsfiles_files WHERE FilePath = '".$db->getEscaped($rsfilesConfig['download_folder'].DS.implode(DS,$parts))."' ");
				if ($db->loadResult() == 0) $published = 0;
				array_pop($parts);
			}
			
			if (!$published) continue;
			
			$files[] = $element;
			
		}
		
		//Ordering
		if(isset($post['rsfl_ordering']) && !empty($files))
		switch($post['rsfl_ordering'])
		{
			case 'name':
				$files = RsfilesHelper::sort_array_name($files, $post['rsfl_ordering_direction']);
			break;
			
			case 'date':
				if ($post['rsfl_ordering_direction'] == 'ASC')
					usort($files, array('RsfilesHelper', 'sort_time_asc'));
				if ($post['rsfl_ordering_direction'] == 'DESC')
					usort($files, array('RsfilesHelper', 'sort_time_desc'));
			break;
			
			case 'hits':
				if ($post['rsfl_ordering_direction'] == 'ASC')
					usort($files, array('RsfilesHelper', 'sort_hits_asc'));
				if ($post['rsfl_ordering_direction'] == 'DESC')
					usort($files, array('RsfilesHelper', 'sort_hits_desc'));
			break;
		}
		
		if(!isset($post['rsfl_ordering'])) return;
		return $files;
	}
	
	function readfile_chunked($filename,$retbytes=true)
	{
		$chunksize = 1*(1024*1024); // how many bytes per chunk
		$buffer = '';
		$cnt =0;
		$handle = fopen($filename, 'rb');
		if ($handle === false) {
			return false;
		}
		while (!feof($handle)) {
			$buffer = fread($handle, $chunksize);
			echo $buffer;
			if ($retbytes) {
				$cnt += strlen($buffer);
			}
		}
	   $status = fclose($handle);
	   if ($retbytes && $status) {
			return $cnt; // return num. bytes delivered like readfile() does.
		}
		return $status;
	}
	
	
	function getPaths()
	{
		$folder = JRequest::getVar('folder','','request');		
		if(empty($folder)) return JText::_('RSFL_HOME');
		
		$elements = explode(DS, $folder);
		$navigation_path = '';
		
		if(!empty($elements))
			foreach($elements as $i=>$element)
			{
				$navigation_path .= $element;
				$newelement = new stdClass();
				$newelement->name = $element;
				$newelement->fullpath = urlencode($navigation_path);
				$elements[$i] = $newelement;
				$navigation_path .= DS;
			}
		
		return $elements;
	}
	
	
	function getBookmarks()
	{
		global $mainframe;
		
		$session = JFactory::getSession();
		$db		 = JFactory::getDBO();
		$config  = RsfilesHelper::getConfig();
		$data = $session->get('rsfl_bookmarks');
		if(empty($data)) return;
		
		$data = array_unique($data);
		$files = array();
		
		foreach ($data as $file)
		{
			if(!$this->getPermissionView(urldecode($file))) continue;
			$db->setQuery("SELECT FileName FROM #__rsfiles_files WHERE FilePath = '".$db->getEscaped($file)."' ");
			$filename = $db->loadResult();
			$file = str_replace($config['download_folder'].DS,'',$file);
			$class = new stdClass();
			$class->name = !empty($filename) ? $filename : JFile::getName($file);
			$class->path = $file;
			
			$files[] = $class;
		}
		
		return $files;
	}
	
	function getFileInfo()
	{
		$db		= JFactory::getDBO();
		$config	= RsfilesHelper::getConfig();
		$path	= JRequest::getVar('path');
		
		$fullpath = $config['download_folder'].DS.urldecode($path);
		
		$db->setQuery("SELECT IdFile, FileName, FilePath, FileVersion, FileStatistics,  FileDescription, DateAdded, IdLicense, DownloadMethod, FileThumb, published FROM #__rsfiles_files WHERE FilePath = '".$db->getEscaped($fullpath)."'");
		$details = $db->loadObject();
		
		if (empty($details))
		{
			$details = new stdClass();
			$details->IdFile = 0;
			$details->FileName = '';
			$details->FilePath = $fullpath;
			$details->FileVersion = '';
			$details->FileStatistics = 0;
			$details->FileDescription = '';
			$details->DateAdded = time();
			$details->IdLicense = 0;
			$details->DownloadMethod = 0;
			$details->FileThumb = '';
			$details->published = '1';	
		}
		
		return $details;
	}
	
}