Location: PHPKode > projects > Bugdar > upload/framework/functions.php
<?php
/*=====================================================================*\
|| ###################################################################
|| # Blue Static ISSO Framework
|| # Copyright ©2002-[#]year[#] Blue Static
|| #
|| # This program is free software; you can redistribute it and/or modify
|| # it under the terms of the GNU General Public License as published by
|| # the Free Software Foundation; version [#]gpl[#] of the License.
|| #
|| # This program is distributed in the hope that it will be useful, but
|| # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
|| # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|| # more details.
|| #
|| # You should have received a copy of the GNU General Public License along
|| # with this program; if not, write to the Free Software Foundation, Inc.,
|| # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
|| ###################################################################
\*=====================================================================*/

/**
* Globalized Functions
* functions.php
*
* @package	ISSO
*/

/**
* Globalized Functions
*
* This framework is a set of functions that are commonly used in most
* applications.
*
* @author		Blue Static
* @copyright	Copyright ©2002 - [#]year[#], Blue Static
* @version		$Revision$
* @package		ISSO
*
*/
class Functions
{
	/**
	* Framework registry object
	* @var	object
	* @access	private
	*/
	var $registry = null;
	
	/**
	* The path that is used to set cookies
	* @var	string
	* @access	private
	*/
	var $cookiepath = '/';
	
	/**
	* The domain used for cookie setting
	* @var	string
	* @access	private
	*/
	var $cookiedom = '';
	
	/**
	* The time it takes for a cookie to expire
	* @var	integer
	* @access	private
	*/
	var $cookieexp = 900;
	
	/**
	* State of the current background colour during alternation
	* @var	string
	* @access	public
	*/
	var $bgcolour = '';
	
	// ###################################################################
	/**
	* Constructor
	*/
	function __construct(&$registry)
	{
		$this->registry =& $registry;
	}
	
	// ###################################################################
	/**
	* (PHP 4) Constructor
	*/
	function Functions(&$registry)
	{
		$this->__construct($registry);
	}
	
	// ###################################################################
	/**
	* Sets the cookie path
	*
	* @access	public
	*
	* @param	string	Cookie path
	*/
	function setCookiePath($path)
	{
		$this->cookiepath = $path;
	}
	
	// ###################################################################
	/**
	* Gets the cookie path
	*
	* @access	public
	*
	* @return	string	The cookie path
	*/
	function getCookiePath()
	{
		return $this->cookiepath;
	}
	
	// ###################################################################
	/**
	* Sets the cookie domain
	*
	* @access	public
	*
	* @param	string	Cookie domain
	*/
	function setCookieDomain($domain)
	{
		$this->cookiedom = $domain;
	}
	
	// ###################################################################
	/**
	* Gets the cookie domain
	*
	* @access	public
	*
	* @return	string	The cookie domain
	*/
	function getCookieDomain()
	{
		return $this->cookiedom;
	}
	
	// ###################################################################
	/**
	* Sets the cookie expiration time
	*
	* @access	public
	*
	* @param	integer	Cookie expiration time
	*/
	function setCookieExpiration($exp)
	{
		$this->cookieexp = $exp;
	}
	
	// ###################################################################
	/**
	* Gets the cookie expiration time
	*
	* @access	public
	*
	* @return	integer	The cookie expiration time
	*/
	function getCookieExpiration()
	{
		return $this->cookieexp;
	}
	
	// ###################################################################
	/**
	* Sets a cookie with a friendly interface
	*
	* @access	public
	*
	* @param	string	The name of the cookie
	* @param	string	Value of the cookie
	* @param	bool	Is the cookie permanent?
	*/
	function cookie($name, $value = '', $sticky = true)
	{
		// expire the cookie
		if (!$value)
		{
			setcookie($name, $value, time() - (2 * $this->cookieexp), $this->cookiepath, $this->cookiedom);
		}
		// set the cookie
		else
		{
			if ($sticky)
			{
				$expire = time() + 60 * 60 * 24 * 365;
			}
			else
			{
				$expire = time() + $this->cookieexp;
			}
			
			setcookie($name, $value, $expire, $this->cookiepath, $this->cookiedom);
		}
	}
	
	// ###################################################################
	/**
	* Alternate between two background colours
	*
	* @access	public
	*
	* @param	string	First CSS class name
	* @param	string	Second CSS class name
	*/
	function exec_swap_bg($class1 = 'alt1', $class2 = 'alt2')
	{
		static $count;
		
		$this->bgcolour = ($count % 2) ? $class1 : $class2;
		$count++;
	}
	
	// ###################################################################
	/**
	* Force-download a file by sending application/octetstream
	*
	* @access	public
	*
	* @param	string	The text of the file to be streamed
	* @param	string	File name of the new file
	* @param	bool	Whether or not to die after stringeaming the file
	*/
	function download_file($file, $name, $exit = true)
	{
		if ($this->is_browser('ie') OR $this->is_browser('opera') OR $this->is_browser('safari'))
		{
			$mime = 'application/octetstream';
		}
		else
		{
			$mime = 'application/octet-stream';
		}
		
		header("Content-Type: $mime");
		header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
		header('Content-Disposition: attachment; filename="' . $name . '"');
		header('Content-length: ' . strlen($file));
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Pragma: public');
		
		print($file);
		
		if ($exit)
		{
			exit;
		}
	}
	
	// ###################################################################
	/**
	* Verify that an email address is valid via regex
	*
	* @access	public
	*
	* @param	string	An email address
	*
	* @return	bool	Validity of the email address
	*/
	function is_valid_email($email)
	{
		if (preg_match('#^[a-z0-9\.\-\+_]+?@(.*?\.)*?[a-z0-9\-_]+?\.[a-z]{2,4}$#i', $email))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	// ###################################################################
	/**
	* Check a browser's user agent against a pre-determined list
	*
	* @access	public
	*
	* @param	string	Browser name
	* @param	string	The browser's version
	*
	* @param	mixed	False if there is no match, the version if there is
	*/
	function is_browser($check, $version = '')
	{
		$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
		$browser = array();
		$matches = array();
		
		// -------------------------------------------------------------------
		// -- Opera
		// -------------------------------------------------------------------
		# Opera/6.05 (Windows 98; U) [en]
		# Mozilla/4.0 (compatible; MSIE 5.0; Windows 98) Opera 6.0 [en]
		# Mozilla/5.0 (Windows 98; U) Opera 6.0 [en]
		# Mozilla/4.0 (compatible; MSIE, 6.0; Windows 98) Opera 7.0 [en]
		if (preg_match('#opera ([0-9\.]+)#', $useragent, $matches) !== false)
		{
			if (isset($matches[1]))
			{
				$browser['opera'] = $matches[1];
			}
		}
		
		// -------------------------------------------------------------------
		// -- Mac browser
		// -------------------------------------------------------------------
		if (strpos($useragent, 'mac') !== false)
		{
			$browser['mac'] = true;
		}
		
		// -------------------------------------------------------------------
		// -- Internet explorer
		// -------------------------------------------------------------------
		# Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.1; .NET CLR 1.0.2914)
		# Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)
		if (preg_match('#msie ([0-9\.]+)#', $useragent, $matches) !== false AND !isset($browser['opera']))
		{
			if (isset($matches[1]))
			{
				$browser['ie'] = $matches[1];
			}
		}
		
		// -------------------------------------------------------------------
		// -- Safari
		// -------------------------------------------------------------------
		# Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/125.4 (KHTML, like Gecko) Safari/125.9
		if (preg_match('#safari/([0-9\.]+)#', $useragent, $matches) !== false)
		{
			if (isset($matches[1]))
			{
				$browser['safari'] = $matches[1];
			}
		}
		
		// -------------------------------------------------------------------
		// -- Konqueror
		// -------------------------------------------------------------------
		# Mozilla/5.0 (compatible; Konqueror/3)
		# Mozilla/5.0 (compatible; Konqueror/3.1; i686 Linux; 20020628)
		if (preg_match('#konqueror/([0-9\.]+)#', $useragent, $matches) !== false)
		{
			if (isset($matches[1]))
			{
				$browser['konqueror'] = $matches[1];
			}
		}
		
		// -------------------------------------------------------------------
		// -- Mozilla
		// -------------------------------------------------------------------
		# Mozilla/5.001 (windows; U; NT4.0; en-us) Gecko/25250101
		# Mozilla/5.001 (Macintosh; N; PPC; ja) Gecko/25250101 MegaCorpBrowser/1.0 (MegaCorp, Inc.)
		if (preg_match('#gecko/([0-9]+)#', $useragent, $matches) !== false AND !isset($browser['safari']))
		{
			if (isset($matches[1]))
			{
				$browser['mozilla'] = $matches[1];
			}
			
			// -------------------------------------------------------------------
			// -- Firefox
			// -------------------------------------------------------------------
			# Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.7) Gecko/20040628 Firefox/0.9.1
			# Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4a) Gecko/20030423 Firebird Browser/0.6
			if (preg_match('#(firebird|firefox)( browser)?/([0-9\.]+)#', $useragent, $matches) !== false)
			{
				if (isset($matches[3]))
				{
					$browser['firefox'] = $matches[3];
				}
			}
			
			// -------------------------------------------------------------------
			// -- Netscape
			// -------------------------------------------------------------------
			# Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:0.9.4.1) Gecko/20020318 Netscape6/6.2.2
			if (preg_match('#netscape([0-9].*?)?/([0-9\.]+)#', $useragent, $matches) !== false)
			{
				if (isset($matches[2]))
				{
					$browser['netscape'] = $matches[2];
				}
			}
			
			// -------------------------------------------------------------------
			// -- Camino
			// -------------------------------------------------------------------
			# Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.7) Gecko/20040623 Camino/0.8
			if (preg_match('#camino/([0-9\.]+)#', $useragent, $matches) !== false)
			{
				if (isset($matches[1]))
				{
					$browser['camino'] = $matches[1];
				}
			}
		}
		
		if (isset($browser["$check"]))
		{
			if ($version)
			{
				if ($browser["$check"] >= $version)
				{
					return $browser["$check"];
				}
				else
				{
					return false;
				}
			}
			else
			{
				return $browser["$check"];
			}
		}
		else
		{
			return false;
		}
	}
	
	// ###################################################################
	/**
	* Generates a random string of random length (unless otherwise
	* specified)
	*
	* @access	public
	*
	* @param	integer	Optional length
	*
	* @return	string	A random string
	*/
	function rand($length = 0)
	{
		// custom high and lows
		if (is_array($length))
		{
			$length = rand($length[0], $length[1]);
		}
		else if (!$length)
		{
			// Gimme a length!
			$length = rand(20, 65);
		}
		
		// Number of ints in our salt
		$intcount = rand(1, intval($length / 2));
		
		// Number of chars
		$charcount = $length - $intcount;
		
		// Upper-case chars
		$upperchars = rand(1, intval($charcount / 2));
		
		// Lower-case chars
		$lowerchars = $charcount - $upperchars;
		
		// Generate ints
		for ($i = 0; $i < $intcount; $i++)
		{
			$string[ mt_rand() ] = rand(0, 9);
		}
		
		// Generate upper chars
		for ($i = 0; $i < $upperchars; $i++)
		{
			$string[ mt_rand() ] = chr(rand(65, 90));
		}
		
		// Generate lower chars
		for ($i = 0; $i < $lowerchars; $i++)
		{
			$string[ mt_rand() ] = chr(rand(97, 122));
		}
		
		// Sort the chars by thier random assignment
		ksort($string);
		
		// Flatten the array
		$return = '';
		foreach ($string AS $char)
		{
			$return .= $char;
		}
		
		return $return;
	}
	
	// ###################################################################
	/**
	* Sets the current array position to be the specified key. This
	* function should be avoided on large arrays.
	*
	* @access	public
	*
	* @param	array	The array whose counter is to be updated
	* @param	mixed	The key of the element of the array that the counter is to be set to
	*
	* @return	mixed	Return the elelment of the array that we just put the counter to
	*/
	function array_set_current(&$array, $key)
	{
		reset($array);
		while (current($array) !== false)
		{
			if (key($array) == $key)
			{
				break;
			}
			next($array);
		}
		return current($array);
	}
	
	// ###################################################################
	/**
	* Calculates the microtime difference by taking a given microtime and
	* subtracting it from the current one
	*
	* @access	public
	*
	* @param	string	The start microtime
	*
	* @return	float	Microtime difference
	*/
	function fetch_microtime_diff($mtstart)
	{
		$mtend = microtime();
		list ($starttime['micro'], $starttime['sec']) = explode(' ', $mtstart);
		list ($endtime['micro'], $endtime['sec']) = explode(' ', $mtend);
		return ($endtime['micro'] + $endtime['sec']) - ($starttime['micro'] + $starttime['sec']);
	}
	
	// ###################################################################
	/**
	* Fetches the extension of a file by extracting everything after the
	* last period
	*
	* @access	public
	*
	* @param	string	Filename
	*
	* @return	string	The extension for the specifid file name
	*/
	function fetch_extension($filename)
	{
		return strval(end(explode('.', $filename)));
	}
	
	// ###################################################################
	/**
	* Gets the maximum file size for attachment uploading, as specified by
	* PHP. If no value is present, 10 MB (represented in bytes) is
	* returned.
	*
	* @access	public
	*
	* @return	integer	The maximum file upload size in bytes
	*/
	function fetch_max_attachment_size()
	{
		if ($size = @ini_get('upload_max_filesize'))
		{
			if (preg_match('#[^0-9].#', $size))
			{
				return $size;
			}
			else
			{
				return intval($size) * 1048576;
			}
		}
		else
		{
			return 10 * 1048576;
		}
	}
	
	// ###################################################################
	/**
	* Scans a specified directory path and returns an array of all the
	* items in that directory. Directories found by this are end in a "/"
	*
	* @access	public
	*
	* @param	string	Path to scan
	* @param	bool	Whether or not to recursively scan the directories encountered
	* @param	bool	Ignore files beginning with a dot
	* @param	bool	Ignore 'CVS' dirctories
	*
	* @return	array	A list of all the files in the specified path
	*/
	function scandir($path, $recurse = true, $ignoredot = true, $ignorecvs = true, $basepath = '', $unset = 1)
	{
		static $filelist;
		
		if ($unset)
		{
			$filelist = array();
		}
		
		if (substr($path, (strlen($path) - 1), 1) != '/')
		{
			$path .= '/';
		}
		
		if ($handle = opendir($path))
		{
			while (($file = readdir($handle)) !== false)
			{
				$isdot = ((substr($file, 0, 1) == '.') ? true : false);
				$isdot = (($ignoredot) ? $isdot : true);
				$iscvs = (($file == 'CVS') ? true : false);
				$iscvs = (($ignorecvs) ? $iscvs : true);
				if (!$isdot AND !$iscvs)
				{
					if (is_dir($path . $file))
					{
						$filelist["$basepath"][] = "$file/";
						if ($recurse)
						{
							$this->scandir("$path$file", true, $ignoredot, $ignorecvs, "$basepath$file/", 0);
						}
					}
					else
					{
						$filelist["$basepath"][] = $file;
					}
				}
			}
			closedir($handle);
		}
		return $filelist;
	}
	
	// ###################################################################
	/**
	* Changes line breaks into one format
	*
	* @access	public
	*
	* @param	string	Text
	* @param	string	New line break (default is UNIX format)
	*
	* @return	string	Text with one type of line break
	*/
	function convert_line_breaks($text, $convert_to = "\n")
	{
		$text = trim($text);
		$text = str_replace(array("\r\n", "\r", "\n"), "\n", $text);
		$text = str_replace("\n", $convert_to, $text);
		return $text;
	}
	
	// ###################################################################
	/**
	* Removes all empty() [by PHP's standards] elements in an array. This
	* can be used in place of using PREG_SPLIT_NO_EMPTY.
	*
	* @access	public
	*
	* @param	array	An array to strip empties from
	*
	* @return	array	Full-valued array
	*/
	function array_strip_empty($array)
	{
		foreach ($array AS $key => $value)
		{
			if (is_array($array["$key"]))
			{
				$array["$key"] = $this->array_strip_empty($array["$key"]);
			}
			else if (empty($value) OR is_null($value))
			{
				unset($array["$key"]);
			}
		}
		return $array;
	}
}

/*=====================================================================*\
|| ###################################################################
|| # $HeadURL$
|| # $Id$
|| ###################################################################
\*=====================================================================*/
?>
Return current item: Bugdar