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

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );

/**
 * RSForm! Pro system plugin
 */
class plgSystemRSFiles extends JPlugin
{
	/**
	 * Constructor
	 *
	 * For php4 compatibility we must not use the __constructor as a constructor for plugins
	 * because func_get_args ( void ) returns a copy of all passed arguments NOT references.
	 * This causes problems with cross-referencing necessary for the observer design pattern.
	 *
	 * @access	protected
	 * @param	object	$subject The object to observe
	 * @param 	array   $config  An array that holds the plugin configuration
	 * @since	1.0
	 */
	
	function plgSystemRSFiles( &$subject, $config )
	{
		parent::__construct( $subject, $config );
		$this->loadLanguage('com_rsfiles',JPATH_SITE);
		JHTML::_('behavior.modal');
	}
	
	function onAfterRender()
	{
		global $mainframe,$option;
		$task = JRequest::getVar('task');
		
		if ($option == 'com_content' && $task == 'edit') return;
		if ($mainframe->isAdmin()) return;
		
		$pattern = '#{rsfiles path="(.*?)" template="(.*?)"}#is';
		
		$content =& JResponse::getBody();
		preg_match_all($pattern, $content, $matches);
		
		
		if(!empty($matches[1]))
		{
			foreach ($matches[1] as $i => $path)
			{
				$find[] = $matches[0][$i];
				$replace[] = $this->listFiles($path,@$matches[2][$i]);
			}
			
			$content = str_replace($find,$replace,$content);			
			JResponse::setBody($content);
		}
	}
	
	function listFiles($path,$template)
	{
		$db =& JFactory::getDBO();
		
		if(!file_exists(JPATH_SITE.DS.'components'.DS.'com_rsfiles'.DS.'models'.DS.'files.php') && !file_exists(JPATH_SITE.DS.'components'.DS.'com_rsfiles'.DS.'helper.php')) return 'Install RSFiles!';
		
		//get the itemid
		$Itemid = JRequest::getVar('Itemid','','request');
		$xmlitemid = $this->params->get('itemid','');
		if(!empty($xmlitemid)) $Itemid = $xmlitemid;
		
		$itemid = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		//load the model
		require_once(JPATH_SITE.DS.'components'.DS.'com_rsfiles'.DS.'models'.DS.'files.php');
		//load the helper
		require_once(JPATH_SITE.DS.'components'.DS.'com_rsfiles'.DS.'helper.php');
		
		//get the download directory
		$db->setQuery("SELECT ConfigValue FROM #__rsfiles_config WHERE ConfigName = 'download_folder' ");
		$dfolder = $db->loadResult();
		
		if(empty($dfolder) || !is_dir($dfolder)) return 'Please set a correct download folder';
		
		//check to see if the template exists
		$db->setQuery("SELECT COUNT(IdTheme) FROM #__rsfiles_themes WHERE ThemeName = '".$template."' LIMIT 1");
		$is_template = $db->loadResult();
		
		
		//get the file header
		if ($is_template == 0)
			$db->setQuery("SELECT t.TemplateHeader FROM #__rsfiles_templates t  LEFT JOIN #__rsfiles_themes th ON th.IdTheme = t.IdTheme WHERE th.default = 1 AND t.Type = 1");
		else 
			$db->setQuery("SELECT t.TemplateHeader FROM #__rsfiles_templates t  LEFT JOIN #__rsfiles_themes th ON th.IdTheme = t.IdTheme WHERE th.ThemeName = '".$template."' AND t.Type = 1");
		$theader = $db->loadResult();
		
		//get the layout
		if ($is_template == 0)
			$db->setQuery("SELECT t.TemplateLayout FROM #__rsfiles_templates t  LEFT JOIN #__rsfiles_themes th ON th.IdTheme = t.IdTheme WHERE th.default = 1 AND t.Type = 1");
		else
			$db->setQuery("SELECT t.TemplateLayout FROM #__rsfiles_templates t  LEFT JOIN #__rsfiles_themes th ON th.IdTheme = t.IdTheme WHERE th.ThemeName = '".$template."' AND t.Type = 1");
		$tlayout = $db->loadResult();
		
		//get the config
		$db->setQuery("SELECT * FROM `#__rsfiles_config`");
		$configs = $db->loadObjectList();
		$rsfilesConfig = array();
		foreach ($configs as $config)
			$rsfilesConfig[$config->ConfigName] = $config->ConfigValue;
		
		//approved extensions for previewing 
		$extensions = explode(',',$rsfilesConfig['preview_files']);
		
		if(empty($path)) $npath = $dfolder; else $npath = $dfolder.DS.$path;
		$all_folders = JFolder::folders($npath,'.',false,true);
		$all_files = JFolder::files($npath,'.',false,true);
		$data = array();
		$layouts = array();
		
		if(is_dir($npath))
		{
			$folders = array();
			$files = array();
			
			foreach($all_folders as $folder)
			{
				$db->setQuery("SELECT FileName,FileDescription,FileThumb,DateAdded,hits,published FROM #__rsfiles_files WHERE FilePath ='".$db->getEscaped($folder)."'");
				$details = $db->loadObject();
				$folderpublished = ($details->published != '') ? $details->published : 1;
				
				if (!$folderpublished) continue;
				$element = new stdClass();
				$element->name = empty($details->FileName) ? JFile::getName($folder) : $details->FileName;
				$element->fullpath = urlencode(str_replace($dfolder.DS,'',$folder));
				if(!rsfilesModelFiles::getPermissionView(urldecode($element->fullpath))) 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 = filemtime($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,f.published , u.username , f.IdLicense , f.FileVersion ,f.hits ,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();
				$filepublish = $details->published != '' ? $details->published : 1;

				if (!$filepublish) continue;
				$element = new stdClass();
				$element->name = empty($details->FileName) ? JFile::getName($file) : $details->FileName;
				$element->fullpath = urlencode(str_replace($dfolder.DS,'',$file));
				if(!rsfilesModelFiles::getPermissionView(urldecode($element->fullpath))) continue;
				$element->size = RsfilesHelper::formatBytes(filesize($file));
				$element->hits = (empty($details->hits) || ($details->hits == 0 && $details->FileStatistics == 0)) ? 0 : $details->hits;
				$element->time = filemtime($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->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->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);
		}
		
		if(is_file($npath))
		{
			$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.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($npath)."'");
			$details = $db->loadObject();
			$element = new stdClass();

			$element->name = empty($details->FileName) ? JFile::getName($npath) : $details->FileName;
			$element->fullpath = urlencode(str_replace($dfolder.DS,'',$npath));
			$element->size = RsfilesHelper::formatBytes(filesize($npath));
			$element->hits = (empty($details->hits) || ($details->hits == 0 && $details->FileStatistics == 0)) ? 0 : $details->hits;
			$element->time = filemtime($npath);
			$element->owner = (empty($details->username) || $details->username == 0) ? JText::_('RSFL_GUEST') : $details->username;
			$element->filetype = JFile::getExt($npath).' ('.JText::_('RSFL_MIMETYPE').' '.RsfilesHelper::mimetype(strtolower(JFile::getExt($npath))).')';
			$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->dateadded = empty($details->DateAdded) ? date($rsfilesConfig['global_date'],filemtime($npath)) : 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($npath));
			$element->filename = JFile::getName($npath);		
			$element->type = 'file';
			if(rsfilesModelFiles::getPermissionView(urldecode($element->fullpath))) $data[] = $element;
		}
		
		foreach($data as $obj)
		{
			$name = ($obj->type == 'folder') ? '<a href="'.JRoute::_('index.php?option=com_rsfiles&view=files&folder='.$obj->fullpath.$itemid,false).'">'.$obj->name.'</a>' : '<a href="'.JRoute::_('index.php?option=com_rsfiles&view=files&layout=download&path='.$obj->fullpath.$itemid,false).'">'.$obj->name.'</a>';
			
			if($obj->type == 'folder')
			{
				$bad = array('{FileName}','{FileDescription}','{FileHits}','{FileThumb}','{FileLicense}','{RealFileName}','{FileVersion}','{FileSize}','{FileType}','{FileUploader}','{DateAdded}','{FileModified}','{FileChecksum}','{Download}','{View}','{Details}');
				$good	= array($name,$obj->description,$obj->hits.' '.JText::_('RSFL_HITS'),$obj->thumb,''); 
			}
			
			if($obj->type == 'file')
			{
				//set the download view link
				$download = '<a class="button" href="'.JRoute::_('index.php?option=com_rsfiles&view=files&layout=download&path='.$obj->fullpath.$itemid,false).'">'.JText::_('RSFL_DOWNLOAD').'</a>&nbsp;';
				
				//set the preview link if the file extension is in the $rsfilesConfig['preview_files']
				if(in_array(JFile::getExt($obj->fullpath),$extensions))
				$view = '<a class="button modal" rel="{handler: \'iframe\', size: {x: 660, y: 475}}" href="'.JRoute::_('index.php?option=com_rsfiles&view=files&layout=view&tmpl=component&path='.$obj->fullpath.$itemid,false).'">'.JText::_('RSFL_VIEW').'</a>&nbsp;';
				else $view = '';
				
				//set the details view
				$details = '<a class="button" href="'.JRoute::_('index.php?option=com_rsfiles&view=files&layout=details&path='.$obj->fullpath.$itemid,false).'">'.JText::_('RSFL_DETAILS').'</a>&nbsp;';
				
				$bad = array('{FileName}','{FileDescription}','{FileLicense}','{RealFileName}','{FileVersion}','{FileSize}','{FileType}','{FileUploader}','{DateAdded}','{FileHits}','{FileModified}','{FileChecksum}','{FileThumb}','{Download}','{View}','{Details}');
				
				$good	= array($name,$obj->filedescription,$obj->filelicense,$obj->filename,$obj->fileversion,$obj->size,$obj->filetype,$obj->owner,$obj->dateadded,($obj->hits == 0) ? JText::_('RSFL_NO_HITS') : $obj->hits.' '.JText::_('RSFL_HITS'),$obj->lastmodified,$obj->checksum,$obj->thumb,$download,$view,$details); 
			}
			
			$layouts[] = str_replace($bad,$good,$tlayout);
		}
		
		$sheader = $this->params->get('fheader', 0);
		
		if($sheader == 1) $return = $theader ; else $return = '';
		$return .= implode("\n",$layouts);
		
		return $return;
	}
	
}