Your IP : 216.73.216.41


Current Path : /home/purehotels/public_html/components/com_easyfolderlistingpro/helpers/
Upload File :
Current File : /home/purehotels/public_html/components/com_easyfolderlistingpro/helpers/ValorUtilities.Class.php

<?php
/**
 * @description   This is an abstract class that provides access to static utility 
 *                functions needed for the ValorApps Listing components.
 * @author        Michael Gilkes (Valor Apps)
 * @created       Friday, May 7, 2013
 * @modified      Thursday, February 11, 2016
 * @version       1.6
 * @copyright     Copyright (C) 2013-2016 Michael Albert Gilkes. All rights reserved.
 * @license       GNU General Public License version 3 or later; see LICENSE
 */

defined('JPATH_PLATFORM') or die;


abstract class ValorUtilities
{
	const PATHINFO_ALL = 15; //PATHINFO_DIRNAME(1) + PATHINFO_BASENAME(2) + PATHINFO_EXTENSION(4) + PATHINFO_FILENAME(8)
	
	protected static $kb = 1024;
	protected static $mb = 1048576; //1024*1024
	protected static $gb = 1073741824; //1024*1024*1024
	protected static $tb = 1099511627776; //1024*1024*1024*1024
	
	
	/**
	 * Converts the bytes to the JEDEC representation of the memory, where 1 kilobyte = 1024 bytes.
	 * Uses upper-case B and KB. Use this instead of JHtmlNumber.bytes
	 *
	 * Note: Only goes to Terabyte (TB)
	 */
	public static function sizeToText($size, $precision = 2)
	{
		//make sure the size in an integer type
		$size = (int)$size;
		//holds human readable size
		$text = '';
		
		if ($size >= self::$tb)
		{
			$size = round($size / self::$tb, $precision);
			$text = $size." TB";
		}
		elseif ($size >= self::$gb)
		{
			$size = round($size / self::$gb, $precision);
			$text = $size." GB";
		}
		elseif ($size >= self::$mb)
		{
			$size = round($size / self::$mb, $precision);
			$text = $size." MB";
		}
		elseif ($size >= self::$kb)
		{
			$size = round($size / self::$kb, $precision);
			$text = $size." KB";
		}
		else
		{
			$text = $size." B";
		}
		return $text;
	}
	
	public static function getUserIP()
	{
		$ip = "";
		
		if (isset($_SERVER))
		{
			if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
			{
				$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
			}
			elseif (isset($_SERVER["HTTP_CLIENT_IP"]))
			{
				$ip = $_SERVER["HTTP_CLIENT_IP"];
			}
			else
			{
				$ip = $_SERVER["REMOTE_ADDR"];
			}
		}
		else
		{
			if (getenv('HTTP_X_FORWARDED_FOR'))
			{
				$ip = getenv('HTTP_X_FORWARDED_FOR');
			}
			elseif (getenv('HTTP_CLIENT_IP'))
			{
				$ip = getenv('HTTP_CLIENT_IP');
			}
			else
			{
				$ip = getenv('REMOTE_ADDR');
			}
		}
		return $ip;
	}
	
	/**
	 * Test the users permission to access the listing profile
	 */
	public static function isUserAllowed($access)
	{
		$user = JFactory::getUser();
		$userAccess = $user->getAuthorisedViewLevels();
		
		return in_array($access, $userAccess);
	}
	
	/**
	 * @param	mixed		$data		string, array or object (any data type) to be obfuscated
	 * @param	boolean		$urisafe	Apply reversible uri safe processing. See: http://www.w3.org/Addressing/URL/5_URI_BNF.html
	 * @param	boolean		$compress	Choose the level of compression to apply ZLIB compression to the serialized data before encoding it
	 */
	public static function obfuscate($data, $urisafe = true, $compress = 9)
	{
		//serialize the data
		$serialized = serialize($data);
		
		//compress the data
		$compress = (int)$compress;
		if ($compress < 0 || $compress > 9) { $compress = 9; }
		$compressed = gzcompress($serialized, 9);
		
		//base64 encode the comparessed, serialized data. addslashes first.
		$obfuscated = base64_encode(addslashes($compressed));
		
		//ensure uri safety
		if ($urisafe)
		{
			$obfuscated = strtr($obfuscated, '+/=', '-_,');
		}
		
		return $obfuscated;
	}
	
	/**
	 * Deobfuscates a data string that has been obfuscated.
	 */
	public static function elucidate($obfuscated, $urisafe = true)
	{
		//compensate for uri safe obfuscation
		if ($urisafe)
		{
			$obfuscated = strtr($obfuscated, '-_,', '+/=');
		}
		
		//stripslashes, then base64 decode the serialized data
		$compressed = stripslashes(base64_decode($obfuscated));
		
		//uncompress the serialized data
		$serialized = gzuncompress($compressed);
		
		//unserialize the data
		$data = unserialize($serialized);
		
		return $data;
	}
	
	/**
	 * Better version of readfile() that allows you to read/downlaod files larger than 2MB.
	 */
	public static function readfile_chunked($filename, $retbytes = true)
	{ 
		$chunksize = 1*(1024*1024); // how many bytes per chunk
		$buffer = '';
		$count = 0;
	
		$handle = fopen($filename, 'rb');
		if ($handle === false)
		{
			return false; 
		}
	
		while (!feof($handle))
		{
			$buffer = fread($handle, $chunksize); 
			echo $buffer;
			ob_flush();
			flush();
			if ($retbytes)
			{
				$count += strlen($buffer);
			}
		}
		$status = fclose($handle); 
	
		if ($retbytes && $status)
		{
			return $count; // return num. bytes delivered like readfile() does.
		}
		return $status;
	}
	
	public static function isInJoomlaRoot($path)
	{
		$isInJoomlaRoot = true;
		
		//trim path, just in case
		$path = trim($path);
		
		//trim forward slashes and backslashes from only the end of the path
		$path = rtrim($path, "/\\");
		
		$abspath = JPATH_ROOT;
		//Note: Have to deal with abolsute paths. In windows it starts with drive letter.
		//      In linux/mac, it starts with a forward slash.
		//So, forcibly add the Joomla Root and check if it exists. if it does, it is a relative
		//path.
		if (stripos($path, '/') === 0 || stripos($path, '\\') === 0)
		{
			$abspath.= $path;
		}
		else
		{
			$abspath.= '/'.$path;
		}
		
		//change all slashes to DIRECTORY_SEPARATOR
		$abspath = ValorUtilities::changeSlashes($abspath);
		
		if (!is_dir($abspath))
		{
			//path is absolute AND not in Joomla root
			$isInJoomlaRoot = false;
		}
		
		return $isInJoomlaRoot;
	}
	
	/**
	 * Checks to see if the path given is an absolute path or relative path. If it is a 
	 * relative path it changes the relative path to an absolute path and cleans it. 
	 * Note that is cleans with DIRECTORY_SEPARATOR.
	 */
	public static function compilePath($path, $userfolders, $guestfolder, $username = false)
	{
		//trim path, just in case
		$path = trim($path);
		
		//trim forward slashes and backslashes from only the end of the path
		$path = rtrim($path, "/\\");
		
		//add userfolder if required. leave as-is if userfolders disabled.
		$path = ValorUtilities::userbasedPath($path, $userfolders, $guestfolder, $username);
		
		$abspath = JPATH_ROOT;
		//Note: Have to deal with abolsute paths. In windows it starts with drive letter.
		//      In linux/mac, it starts with a forward slash.
		//So, forcibly add the Joomla Root and check if it exists. if it does, it is a relative
		//path.
		if (stripos($path, '/') === 0 || stripos($path, '\\') === 0)
		{
			$abspath.= $path;
		}
		else
		{
			$abspath.= '/'.$path;
		}
		
		//change all slashes to DIRECTORY_SEPARATOR
		$abspath = ValorUtilities::changeSlashes($abspath);
		
		if (!is_dir($abspath))
		{
			//path is absolute
			$abspath = $path;
			
			//change all slashes to DIRECTORY_SEPARATOR
			$abspath = ValorUtilities::changeSlashes($abspath);
		}
		
		return $abspath;
	}
	
	/**
	 * Similar to JPATH::clean(), but does not return the Joomla Root if $path is empty.
	 */
	public static function changeSlashes($path, $ds = DIRECTORY_SEPARATOR)
	{
		$path = trim($path);

		// Remove double slashes and backslashes and convert all slashes and backslashes to DIRECTORY_SEPARATOR
		// If dealing with a UNC path don't forget to prepend the path with a backslash.
		if (($ds == '\\') && ($path[0] == '\\' ) && ( $path[1] == '\\' ))
		{
			$path = "\\" . preg_replace('#[/\\\\]+#', $ds, $path);
		}
		else
		{
			$path = preg_replace('#[/\\\\]+#', $ds, $path);
		}

		return $path;
	}
	
	/**
	 * Processes the path to include username-based subfolder, if that option was enabled.
	 */
	public static function userbasedPath($path, $userfolders, $guestfolder, $username = false)
	{
		if ($userfolders)
		{
			//get the user data is the user name is false bool value
			if ($username === false)
			{
				$user = JFactory::getUser();
				if ($user->guest)
				{
					$username = $guestfolder;
				}
				else
				{
					$username = $user->username;
				}
			}
			elseif (empty($username))
			{
				//use guest folder if username is an empty string
				$username = $guestfolder;
			}
			
			return $path.'/'.$username;
		}
		else
		{
			//no changes. return as-is
			return $path;
		}
	}
	
	/**
	 * A generic method to do a straight insert of values into a mysql database table
	 */
	public static function insertValuesIntoMysql($table, $values)
	{
		$db = JFactory::getDbo();
		
		//start the query
		$query = 'INSERT INTO '.$table.' ';
		
		//open keys
		$keys_txt = '(';
		
		//open the values
		$values_txt = 'VALUES ';
		
		$rows = count($values);
		for ($i = 0; $i < $rows; $i++)
		{
			if ($i > 0)
			{
				$values_txt.= ', ';
			}
			
			$values_txt.= '(';
			$index = 0;
			foreach ($values[$i] as $key => $value)
			{
				//handle the keys only for the first row; since they are all the same, and
				//we only need to do this once.
				if ($i == 0)
				{
					//place comma between keys
					if ($index > 0)
					{
						$keys_txt.= ', ';
					}
					
					//add key and surround with `
					$keys_txt.= '`'.$key.'`';
				}
				
				//place comma between values
				if ($index > 0)
				{
					$values_txt.= ', ';
				}
				
				//add values
				$values_txt.= $db->quote($value);
				
				//increment counter
				$index++;
			}
			$values_txt.= ')';
		}
		
		//close keys
		$keys_txt.= ') ';
		
		//compile the query
		$query.= $keys_txt;
		$query.= $values_txt;
		
		//set the query
		$db->setQuery($query);
		
		//execute the query
		$resource = false;
		$resource = $db->execute();
		
		//return the result
		if (!$resource)
		{
			return $db->getErrorMsg();
		}
		
		return true;
	}
	
	/**
	 * This method returns the actual MIME of a file
	 */
	public static function actualMIME($file)
	{
		if (!file_exists($file))
		{
			return false;
		}
	
		$mime = false;
		// try to use recommended functions
		if (defined('FILEINFO_MIME_TYPE') &&
			function_exists('finfo_open') && is_callable('finfo_open') && 
			function_exists('finfo_file') && is_callable('finfo_file') && 
			function_exists('finfo_close') && is_callable('finfo_close'))
		{
			$finfo = finfo_open(FILEINFO_MIME_TYPE);
			$mime = finfo_file($finfo, $file);
			if ($mime === '')
			{
				$mime = false;
			}
			finfo_close($finfo);
		}
		else if (strtoupper(substr(PHP_OS,0,3)) !== 'WIN')
		{
			$f = escapeshellarg($file);
			if (function_exists('exec') && is_callable('exec'))
			{
				//didn't like how 'system' flushes output to browser. replaced with 'exec'
				//note: You can change this to: shell_exec("file -b --mime-type $f"); if you get
				//      "regular file" as the mime type
				$mime = exec("file -bi $f");
				//this removes the charset value if it was returned with the mime type. mime is first.
				$mime = strtok($mime, '; ');
				$mime = trim($mime); //remove any remaining whitespace
			}
			else if (function_exists('shell_exec') && is_callable('shell_exec'))
			{
				//note: You can change this to: shell_exec("file -b --mime-type $f"); if you get
				//      "regular file" as the mime type
				$mime = shell_exec("file -bi $f");
				//this removes the charset value if it was returned with the mime type. mime is first.
				$mime = strtok($mime, '; ');
				$mime = trim($mime); //remove any remaining whitespace
			}
		}
		else if (function_exists('mime_content_type') && is_callable('mime_content_type'))
		{
			//test using mime_content_type last, since it sometimes detects the mime incorrectly
			$mime = mime_content_type($file);
		}
	
		return $mime;
	}
	
	/**
	 * This method is my custom made function to replace the PHP's faulty  builtin pathinfo()
	 * function. It works almost the same, in most use cases, and handles UTF-8 characters 
	 * better.
	 */
	public static function fixed_pathinfo($path, $options = ValorUtilities::PATHINFO_ALL)
	{
		//if nothing was entered as a path, return NULL
		if (!$path || !is_string($path)) { return null; }
	
		//define the return array
		$info = array();
	
		if (!empty($path))
		{
			$parts = $path;
			if (strpos($path, '/') !== false)
			{
				$parts = explode('/', $path);
			}
			elseif (strpos($path, '\\') !== false)
			{
				$parts = explode('\\', $path);
			}
		
			//if $parts is a string, it means neither slash nor backslash was found
			$basename = $parts;
		
			//if parts is an array, then basename is at the end
			if (is_array($parts))
			{
				$basename = end($parts);
			}
		
			//assign the dirname
			if ($options & PATHINFO_DIRNAME)
			{
				if (!empty($basename) && (strlen($path) > strlen($basename)))
				{
					$info['dirname'] = substr($path, 0, strlen($path) - strlen($basename) - 1);
				}
				else
				{
					if ($path == '/')
					{
						$info['dirname'] = '/';
					}
					else
					{
						$info['dirname'] = '.';
					}
				}
			}
		
			if ($options & PATHINFO_BASENAME)
			{
				$info['basename'] = $basename;
			}
		
			//assign the filename and extension
			if (strpos($basename, '.') !== false) 
			{
				$split = explode('.', $basename);
				$extension = end($split);
				if ($options & PATHINFO_EXTENSION)
				{
					$info['extension'] = $extension;
				}
				if ($options & PATHINFO_FILENAME)
				{
					$info['filename'] = substr($basename, 0, strlen($basename) - strlen($extension) - 1);
				}
			} 
			else 
			{ 
				if ($options & PATHINFO_EXTENSION)
				{
					$info['extension'] = '';
				}
				if ($options & PATHINFO_FILENAME)
				{
					$info['filename'] = $basename;
				}
			} 
		}
		else
		{
			//check for basename option and initialize to empty string
			if ($options & PATHINFO_BASENAME) { $info['basename'] = ''; }
	
			//check for filename option and initialize to empty string
			if ($options & PATHINFO_FILENAME) { $info['filename'] = ''; }
		}
	
		return $info;
	}
	
	public static function fixed_basename($path)
	{
		$info = ValorUtilities::fixed_pathinfo($path, PATHINFO_BASENAME);
		
		return $info['basename'];
	}

}