<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Download helper class.
 *
 * $Id: download.php 3238 2008-07-30 15:42:28Z Shadowhand $
 *
 * @package    Core
 * @author     Kohana Team
 * @copyright  (c) 2007-2008 Kohana Team
 * @license    http://kohanaphp.com/license.html
 */
class download_Core {

	/**
	 * Force a download of a file to the user's browser. This function is
	 * binary-safe and will work with any MIME type that Kohana is aware of.
	 *
	 * @param   string  a file path or file name
	 * @param   mixed   data to be sent if the filename does not exist
	 * @param   string  suggested filename to display in the download
	 * @return  void
	 */
	public static function force($filepath = NULL, $filename = NULL, $nicename = NULL)
	{
		if(!$filename) $filename = basename($filepath);
		if(self::is_ie()) $filename = rawurlencode($filename);
		$filetype = self::fileext($filename);
		$filesize = sprintf("%u", filesize($filepath));
		if(ob_get_length() !== false) @ob_end_clean();
		header('Pragma: public');
		header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
		header('Cache-Control: no-store, no-cache, must-revalidate');
		header('Cache-Control: pre-check=0, post-check=0, max-age=0');
		header('Content-Transfer-Encoding: binary');
		header('Content-Encoding: none');
		header('Content-type: '.$filetype);
		header('Content-Disposition: attachment; filename="'.$filename.'"');
		header('Content-length: '.$filesize);
		readfile($filepath);
		exit;
	}

	function is_ie()
	{
		$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
		if((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) return false;
		if(strpos($useragent, 'msie ') !== false) return true;
		return false;
	}
	function fileext($filename)
	{
		return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
	}
} // End download