<?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');


class RSFilesHelper
{	
	function createThumb($src, $dest, $thumb_w, $type='jpg')
	{
		jimport('joomla.filesystem.file');
		
		$dest = $dest.'.'.$type;
		
		// load image
		if($type == "jpg" || $type == "jpeg" || $type == "JPG") $img=imagecreatefromjpeg($src);
        if($type == "png") $img=imagecreatefrompng($src);
        if($type == "gif") $img=imagecreatefromgif($src); 
		
		
		if ($img)
		{
			// get image size
			$width = imagesx($img);
			$height = imagesy($img);

			// calculate thumbnail size
			$new_width = $thumb_w;
			$new_height = floor($height*($thumb_w/$width));

			// create a new temporary image
			$tmp_img = imagecreatetruecolor($new_width, $new_height);
			imagealphablending($tmp_img, false);
			// copy and resize old image into new image
			imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

			// save thumbnail into a file
			if($type == "jpg" || $type == "jpeg" || $type == "JPG") imagejpeg($tmp_img, $dest);
			if($type == "png") imagepng($tmp_img, $dest);
			if($type == "gif") imagegif($tmp_img, $dest);
			
			return true;
		}
		else
			return false;
	}

	function formatBytes($bytes, $precision = 2) 
	{
		$units = array('B', 'KB', 'MB', 'GB', 'TB');
	  
		$bytes = max($bytes, 0);
		$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
		$pow = min($pow, count($units) - 1);
	  
		$bytes /= pow(1024, $pow);
	  
		return round($bytes, $precision) . ' ' . $units[$pow];
	}

	//read configuration
	function readConfig()
	{
		$db		 =& JFactory::getDBO();
		$session = JFactory::getSession();
		$rsfiles_config = array();
		
		$db->setQuery("SELECT * FROM `#__rsfiles_config`");
		$config = $db->loadObjectList();
		if (!empty($config))
			foreach ($config as $config_item)
				$rsfiles_config[$config_item->ConfigName] = $config_item->ConfigValue;
		
		$session->set('rsfilesConfig', $rsfiles_config);
	}
	
	//fetch the config
	function getConfig($name = null)
	{
		$session = JFactory::getSession();
		$config = $session->get('rsfilesConfig');
		if ($name != null)
		{
			if (isset($config[$name]))
				return $config[$name];
			else
				return false;
		}
		else
			return $config;
	}

}