/**
  * Creates a new stream object with appropriate prefix
  * @param boolean Prefix the connections for writing
  * @param boolean Use network if available for writing; use false to disable (e.g. FTP, SCP)
  * @param string UA User agent to use
  * @param boolean User agent masking (prefix Mozilla)
  */
 function &getStream($use_prefix = true, $use_network = true, $ua = null, $uamask = false)
 {
     juimport('joomla.filesystem.stream');
     juimport('pasamio.pversion');
     jimport('joomla.client.helper');
     // Setup the context; Joomla! UA and overwrite
     $context = array();
     $version = new PVersion();
     // set the UA for HTTP and overwrite for FTP
     $context['http']['user_agent'] = $version->getUserAgent($ua, $uamask);
     $context['ftp']['overwrite'] = true;
     if ($use_prefix) {
         juimport('joomla.client.helper');
         $FTPOptions = JClientHelper::getCredentials('ftp');
         $SCPOptions = JClientHelper::getCredentials('scp');
         if ($FTPOptions['enabled'] == 1 && $use_network) {
             $prefix = 'ftp://' . $FTPOptions['user'] . ':' . $FTPOptions['pass'] . '@' . $FTPOptions['host'];
             $prefix .= $FTPOptions['port'] ? ':' . $FTPOptions['port'] : '';
             $prefix .= $FTPOptions['root'];
         } else {
             if ($SCPOptions['enabled'] == 1 && $use_network) {
                 $prefix = 'ssh2.sftp://' . $SCPOptions['user'] . ':' . $SCPOptions['pass'] . '@' . $SCPOptions['host'];
                 $prefix .= $SCPOptions['port'] ? ':' . $SCPOptions['port'] : '';
                 $prefix .= $SCPOptions['root'];
             } else {
                 $prefix = JPATH_ROOT . DS;
             }
         }
         $retval = new JStream($prefix, JPATH_ROOT, $context);
     } else {
         $retval = new JStream('', '', $context);
     }
     return $retval;
 }
function downloadFile($url, $target)
{
    juimport('pasamio.downloader.downloader');
    $downloader =& Downloader::getInstance();
    $error_object = new stdClass();
    $params = JComponentHelper::getParams('com_jupdateman');
    $adapter = null;
    switch ($params->get('download_method', 0)) {
        case JUPDATEMAN_DLMETHOD_FOPEN:
        default:
            $adapter = $downloader->getAdapter('fopen');
            break;
        case JUPDATEMAN_DLMETHOD_CURL:
            $adapter = $downloader->getAdapter('curl');
            break;
    }
    return $adapter->downloadFile($url, $target, $params);
}
    $app->redirect('index.php?option=com_jupdateman&task=step1');
    // back to step one if invalid session
}
$params = JComponentHelper::getParams('com_jupdateman');
$extractor = $params->get('extractor', 0);
define('JUPDATEMAN_EXTRACTOR_16', 0);
define('JUPDATEMAN_EXTRACTOR_15', 1);
define('JUPDATEMAN_EXTRACTOR_PEAR', 2);
@set_time_limit(0);
// try to set this just in case - doesn't hurt either
$config =& JFactory::getConfig();
$tmp_path = $config->getValue('config.tmp_path');
$filename = $tmp_path . DS . $file;
switch ($extractor) {
    case JUPDATEMAN_EXTRACTOR_16:
        juimport('joomla.filesystem.archive');
        if (!JArchive::extract($filename, JPATH_SITE)) {
            HTML_jupgrader::showError('Failed to extract archive!');
            return false;
        }
        break;
    case JUPDATEMAN_EXTRACTOR_15:
        jimport('joomla.filesystem.archive');
        if (!JArchive::extract($filename, JPATH_SITE)) {
            HTML_jupgrader::showError('Failed to extract archive!');
            return false;
        }
        break;
    case JUPDATEMAN_EXTRACTOR_PEAR:
        jimport('pear.archive_tar.Archive_Tar');
        $extractor = new Archive_Tar($filename);
<?php

/**
 * @version		$Id:bzip2.php 6961 2007-03-15 16:06:53Z tcp $
 * @package		Joomla.Framework
 * @subpackage	FileSystem
 * @copyright	Copyright (C) 2005 - 2009 Open Source Matters, Inc. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */
// No direct access
defined('JPATH_BASE') or die;
juimport('joomla.filesystem.stream');
/**
 * Bzip2 format adapter for the JArchive class
 *
 * @package 	Joomla.Framework
 * @subpackage	FileSystem
 * @since		1.5
 */
class JArchiveBzip2 extends JObject
{
    /**
     * Bzip2 file data buffer
     * @var string
     */
    var $_data = null;
    /**
     * Constructor tries to load the bz2 extension of not loaded
     *
     * @access	protected
     * @return	void
<?php

/**
 * Downloader Function
 */
juimport('joomla.base.adapter');
class Downloader extends JAdapter
{
    /**
     * PHP style constructor!
     */
    function __construct()
    {
        // base directory is here (so here/adapters)
        // and the prefix is 'downloader'
        parent::__construct(dirname(__FILE__), 'Downloader');
    }
    /**
     * Returns a reference to the global Downloader object, only creating it
     * if it doesn't already exist.
     *
     * @static
     * @return      object  An downloader object
     * @since 1.5
     */
    public static function &getInstance()
    {
        static $instance;
        if (!isset($instance)) {
            $instance = new Downloader();
        }
 function downloadFile($url, $target = false, &$params = null)
 {
     if (!function_exists('curl_init')) {
         $error_object = new stdClass();
         $error_object->number = 40;
         $error_object->message = 'cURL support not available on this host. Use fopen instead.';
         return $error_object;
     }
     $config =& JFactory::getConfig();
     if (is_null($params)) {
         $params = new JParameter();
     }
     $php_errormsg = '';
     // Set the error message
     $track_errors = ini_set('track_errors', true);
     // Set track errors
     // create a new cURL resource
     $ch = curl_init();
     // set URL and other appropriate options
     curl_setopt($ch, CURLOPT_URL, $url);
     // Set the download URL
     curl_setopt($ch, CURLOPT_HEADER, false);
     // Don't include the header in the output
     curl_setopt($ch, CURLOPT_USERAGENT, generateUAString());
     // set the user agent
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
     // follow redirects (required for Joomla!)
     curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
     // 10 maximum redirects
     //		curl_setopt($ch, CURLOPT_HEADERFUNCTION, 					// set a custom header callback
     //				array($this, 'header_callback'));					// use this object and function 'header_callback'
     if (!$target) {
         $target = $config->getValue('config.tmp_path') . DS . Downloader::getFilenameFromURL($url);
     }
     juimport('pasamio.pfactory');
     $output_stream = PFactory::getStream(true, true, 'JUpdateMan/' . getComponentVersion(), true);
     $relative_target = str_replace(JPATH_ROOT, '', $target);
     $output_handle = $output_stream->open($relative_target, 'wb');
     //$output_handle = @fopen($target, "wb"); 								// Open a location
     if (!$output_handle) {
         $error_object->number = 43;
         $error_object->message = 'Local output opening failed: ' . $output_stream->getError();
         ini_set('track_errors', $track_errors);
         return $error_object;
     }
     // since we're using streams we should be able to get everything up and running fine here
     curl_setopt($ch, CURLOPT_FILE, $output_stream->getFileHandle());
     if ($params->get('use_proxy', 0) && strlen($params->get('proxy_host', '')) && strlen($params->get('proxy_port', ''))) {
         curl_setopt($ch, CURLOPT_PROXY, $params->get('proxy_host') . ':' . $params->get('proxy_port'));
         if (strlen($params->get('proxy_user', ''))) {
             curl_setopt($ch, CURLOPT_PROXYUSERPWD, $params->get('proxy_user') . ':' . $params->get('proxy_pass', ''));
         }
     }
     // grab URL and pass it to the browser
     if (curl_exec($ch) === false) {
         $error_object->number = 46;
         $error_object->message = 'cURL transfer failed(' . curl_errno($ch) . '): ' . curl_error($ch);
         ini_set('track_errors', $track_errors);
         return $error_object;
     }
     // close cURL resource, and free up system resources
     curl_close($ch);
     $output_stream->close();
     return basename($target);
 }
<?php

juimport('joomla.version');
class PVersion extends JVersion
{
    /**
     * Returns the user agent.
     * 
     * @param	string	Name of the component.
     * @param	bool	Mask as Mozilla/5.0 or not.
     * @param	bool	Add version afterwards to component.
     * @return	string	User Agent.
     */
    public function getUserAgent($component = null, $mask = false, $add_version = true)
    {
        if ($component === null) {
            $component = 'Framework';
        }
        if ($add_version) {
            $component .= '/' . $this->RELEASE;
        }
        // If masked pretend to look like Mozilla 5.0 but still identify ourselves.
        if ($mask) {
            return 'Mozilla/5.0 ' . $this->PRODUCT . '/' . $this->RELEASE . '.' . $this->DEV_LEVEL . ($component ? ' ' . $component : '');
        } else {
            return $this->PRODUCT . '/' . $this->RELEASE . '.' . $this->DEV_LEVEL . ($component ? ' ' . $component : '');
        }
    }
}
 /**
  * @param	string	The name of the archive file
  * @param	string	Directory to unpack into
  * @return	boolean	True for success
  */
 function extract($archivename, $extractdir)
 {
     juimport('joomla.filesystem.file');
     juimport('joomla.filesystem.folder');
     $untar = false;
     $result = false;
     $ext = JFile::getExt(strtolower($archivename));
     // check if a tar is embedded...gzip/bzip2 can just be plain files!
     if (JFile::getExt(JFile::stripExt(strtolower($archivename))) == 'tar') {
         $untar = true;
     }
     switch ($ext) {
         case 'zip':
             $adapter =& JArchive::getAdapter('zip');
             if ($adapter) {
                 $result = $adapter->extract($archivename, $extractdir);
             }
             break;
         case 'tar':
             $adapter =& JArchive::getAdapter('tar');
             if ($adapter) {
                 $result = $adapter->extract($archivename, $extractdir);
             }
             break;
         case 'tgz':
             $untar = true;
             // This format is a tarball gzip'd
         // This format is a tarball gzip'd
         case 'gz':
             // This may just be an individual file (e.g. sql script)
         // This may just be an individual file (e.g. sql script)
         case 'gzip':
             $adapter =& JArchive::getAdapter('gzip');
             if ($adapter) {
                 $config =& JFactory::getConfig();
                 $tmpfname = $config->getValue('config.tmp_path') . DS . uniqid('gzip');
                 $gzresult = $adapter->extract($archivename, $tmpfname);
                 if (JError::isError($gzresult)) {
                     @unlink($tmpfname);
                     return false;
                 }
                 if ($untar) {
                     // Try to untar the file
                     $tadapter =& JArchive::getAdapter('tar');
                     if ($tadapter) {
                         $result = $tadapter->extract($tmpfname, $extractdir);
                     }
                 } else {
                     $path = JPath::clean($extractdir);
                     JFolder::create($path);
                     $result = JFile::copy($tmpfname, $path . DS . JFile::stripExt(JFile::getName(strtolower($archivename))), null, 1);
                 }
                 @unlink($tmpfname);
             }
             break;
         case 'tbz2':
             $untar = true;
             // This format is a tarball bzip2'd
         // This format is a tarball bzip2'd
         case 'bz2':
             // This may just be an individual file (e.g. sql script)
         // This may just be an individual file (e.g. sql script)
         case 'bzip2':
             $adapter =& JArchive::getAdapter('bzip2');
             if ($adapter) {
                 $config =& JFactory::getConfig();
                 $tmpfname = $config->getValue('config.tmp_path') . DS . uniqid('bzip2');
                 $bzresult = $adapter->extract($archivename, $tmpfname);
                 if (JError::isError($bzresult)) {
                     @unlink($tmpfname);
                     return false;
                 }
                 if ($untar) {
                     // Try to untar the file
                     $tadapter =& JArchive::getAdapter('tar');
                     if ($tadapter) {
                         $result = $tadapter->extract($tmpfname, $extractdir);
                     }
                 } else {
                     $path = JPath::clean($extractdir);
                     JFolder::create($path);
                     $result = JFile::copy($tmpfname, $path . DS . JFile::stripExt(JFile::getName(strtolower($archivename))), null, 1);
                 }
                 @unlink($tmpfname);
             }
             break;
         default:
             JError::raiseWarning(10, JText::_('UNKNOWNARCHIVETYPE'));
             return false;
             break;
     }
     if (!$result || JError::isError($result)) {
         return false;
     }
     return true;
 }
 function downloadFile($url, $target = false, &$params = null)
 {
     // this isn't intelligent some times
     $error_object = new stdClass();
     $proxy = false;
     $php_errormsg = '';
     // Set the error message
     $track_errors = ini_set('track_errors', true);
     // Set track errors
     $config =& JFactory::getConfig();
     if (is_null($params)) {
         $params = new JParameter();
     }
     $input_handle = null;
     // Are we on a version of PHP that supports streams?
     if (version_compare(PHP_VERSION, '5.0.0', '>')) {
         // set the ua; we could use ini_set but it might not work
         $http_opts = array('user_agent' => generateUAString());
         // If:
         // - the proxy is enabled,
         // - the host is set and the port are set
         // Set the proxy settings and create a stream context
         if ($params->get('use_proxy', 0) && strlen($params->get('proxy_host', '')) && strlen($params->get('proxy_port', ''))) {
             $proxy = true;
             // I hate eclipse sometimes
             // If the user has a proxy username set fill this in as well
             $http_opts['proxy'] = 'tcp://' . $params->get('proxy_host') . ':' . $params->get('proxy_port');
             $http_opts['request_fulluri'] = 'true';
             // play nicely with squid
             if (strlen($params->get('proxy_user', ''))) {
                 $credentials = base64_encode($params->get('proxy_user', '') . ':' . $params->get('proxy_pass', ''));
                 $http_opts['header'] = "Proxy-Authorization: Basic {$credentials}\r\n";
             }
         }
         $context = stream_context_create(array('http' => $http_opts));
         $input_handle = @fopen($url, 'r', false, $context);
     } else {
         // Open remote server
         ini_set('user_agent', generateUAString());
         // set the ua
         $input_handle = @fopen($url, "r");
         // or die("Remote server connection failed");
     }
     if (!$input_handle) {
         $error_object->number = 42;
         $error_object->message = 'Remote Server connection failed: ' . $php_errormsg . '; Using Proxy: ' . ($proxy ? 'Yes' : 'No');
         ini_set('track_errors', $track_errors);
         return $error_object;
     }
     $meta_data = stream_get_meta_data($input_handle);
     foreach ($meta_data['wrapper_data'] as $wrapper_data) {
         if (substr($wrapper_data, 0, strlen("Content-Disposition")) == "Content-Disposition") {
             $contentfilename = explode("\"", $wrapper_data);
             $target = $contentfilename[1];
         }
     }
     // Set the target path if not given
     if (!$target) {
         $target = $config->getValue('config.tmp_path') . DS . Downloader::getFilenameFromURL($url);
     } else {
         $target = $config->getValue('config.tmp_path') . DS . basename($target);
     }
     juimport('pasamio.pfactory');
     $stream = PFactory::getStream(true, true, 'JUpdateMan/' . getComponentVersion(), true);
     $relative_target = str_replace(JPATH_ROOT, '', $target);
     $output_handle = $stream->open($relative_target, 'wb');
     //$output_handle = fopen($target, "wb"); // or die("Local output opening failed");
     if (!$output_handle) {
         $error_object->number = 43;
         $error_object->message = 'Local output opening failed: ' . $stream->getError();
         ini_set('track_errors', $track_errors);
         return $error_object;
     }
     $contents = '';
     $downloaded = 0;
     while (!feof($input_handle)) {
         $contents = fread($input_handle, 4096);
         if ($contents === false) {
             $error_object->number = 44;
             $error_object->message = 'Failed reading network resource at ' . $downloaded . ' bytes: ' . $php_errormsg;
             ini_set('track_errors', $track_errors);
             return $error_object;
         } else {
             if (strlen($contents)) {
                 $write_res = $stream->write($contents);
                 if ($write_res == false) {
                     $error_object->number = 45;
                     $error_object->message = 'Cannot write to local target: ' . $stream->getError();
                     ini_set('track_errors', $track_errors);
                     return $error_object;
                 }
                 $downloaded += 1024;
             }
         }
     }
     $stream->close();
     fclose($input_handle);
     ini_set('track_errors', $track_errors);
     return basename($target);
 }
 * This class adheres to the stream wrapper operations:
 * http://www.php.net/manual/en/function.stream-get-wrappers.php
 *
 * PHP5
 *
 * Created on Sep 17, 2008
 *
 * @package Joomla!
 * @license GNU General Public License version 2 or later; see LICENSE.txt
 * @copyright 2008 OpenSourceMatters.org
 * @version SVN: $Id: stream.php 12276 2009-06-22 01:54:01Z pasamio $
 */
// Check to ensure this file is within the rest of the framework
defined('JPATH_BASE') or die;
juimport('joomla.filesystem.helper');
juimport('joomla.utilities.utility');
/**
 * Joomla! Stream Class
 * @see http://au.php.net/manual/en/intro.stream.php PHP Stream Manual
 * @see http://au.php.net/manual/en/wrappers.php Stream Wrappers
 * @see http://au.php.net/manual/en/filters.php Stream Filters
 * @see http://au.php.net/manual/en/transports.php Socket Transports (used by some options, particularly HTTP proxy)
 */
class JStream extends JObject
{
    // Publicly settable vars (protected to let our parent read them)
    /** @var File Mode */
    protected $filemode = 0644;
    /** @var Directory Mode */
    protected $dirmode = 0755;
    /** @var Default Chunk Size */