Source for file Downloader.php
Documentation is available at Downloader.php
* PEAR_Downloader, the PEAR Installer's download utility class
* @author Greg Beaver <cellog@php.net>
* @author Stig Bakken <ssb@php.net>
* @author Tomas V. V. Cox <cox@idecnet.com>
* @author Martin Jansen <mj@php.net>
* @copyright 1997-2009 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version CVS: $Id: Downloader.php 313024 2011-07-06 19:51:24Z dufuz $
* @link http://pear.php.net/package/PEAR
* @since File available since Release 1.3.0
* Needed for constants, extending
require_once 'PEAR/Common.php';
define('PEAR_INSTALLER_OK', 1 );
define('PEAR_INSTALLER_FAILED', 0 );
define('PEAR_INSTALLER_SKIPPED', -1 );
define('PEAR_INSTALLER_ERROR_NO_PREF_STATE', 2 );
* Administration class used to download anything from the internet (PEAR Packages,
* static URLs, xml files)
* @author Greg Beaver <cellog@php.net>
* @author Stig Bakken <ssb@php.net>
* @author Tomas V. V. Cox <cox@idecnet.com>
* @author Martin Jansen <mj@php.net>
* @copyright 1997-2009 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version Release: 1.9.4
* @link http://pear.php.net/package/PEAR
* @since Class available since Release 1.3.0
* Preferred Installation State (snapshot, devel, alpha, beta, stable)
* Options from command-line passed to Install.
* Recognized options:<br />
* - onlyreqdeps : install all required dependencies as well
* - alldeps : install all dependencies, including optional
* - installroot : base relative path to install files in
* - force : force a download even if warnings would prevent it
* - nocompress : download uncompressed tarballs
* @see PEAR_Command_Install
* Downloaded Packages after a call to download().
* array('pkg' => 'package_name', 'file' => '/path/to/local/file',
* 'info' => array() // parsed package.xml
var $_downloadedPackages = array ();
* Packages slated for download.
* This is used to prevent downloading a package more than once should it be a dependency
* for two packages to be installed.
* array('package_name1' => parsed package.xml, 'package_name2' => parsed package.xml,
var $_toDownload = array ();
* Array of every package installed, with names lower-cased.
* array('package1' => 0, 'package2' => 1, );
var $_installed = array ();
var $_errorStack = array ();
var $_internalDownload = false;
* Temporary variable used in sorting packages by dependency in {@link sortPkgDeps()}
* Temporary directory, or configuration value where downloads will occur
$this->_options = $options;
$this->_preferredState = $this->config->get ('preferred_state');
if (!$this->_preferredState) {
// don't inadvertantly use a non-set preferred_state
$this->_preferredState = null;
if (isset ($this->_options['installroot'])) {
$this->config->setInstallRoot ($this->_options['installroot']);
$this->_registry = &$config->getRegistry ();
if (isset ($this->_options['alldeps']) || isset ($this->_options['onlyreqdeps'])) {
foreach ($this->_installed as $key => $unused) {
* Attempt to discover a channel's remote capabilities from
$this->log(1 , 'Attempting to discover channel "' . $channel . '"...');
$callback = $this->ui ? array (&$this, '_downloadCallback') : null;
require_once 'System.php';
$tmpdir = $this->config->get ('temp_dir');
$a = $this->downloadHttp('http://' . $channel . '/channel.xml', $this->ui, $tmp, $callback, false );
// Attempt to fallback to https automatically.
$this->log(1 , 'Attempting fallback to https instead of http on channel "' . $channel . '"...');
$a = $this->downloadHttp('https://' . $channel . '/channel.xml', $this->ui, $tmp, $callback, false );
list ($a, $lastmodified) = $a;
require_once 'PEAR/ChannelFile.php';
if ($b->fromXmlFile ($a)) {
if ($this->config->get ('auto_discover')) {
if ($b->getName () == $this->_registry->channelName($b->getAlias ())) {
$this->log(1 , 'Auto-discovered channel "' . $channel .
'", alias "' . $alias . '", adding to registry');
* For simpler unit-testing
* @return PEAR_Downloader_Package
require_once 'PEAR/Downloader/Package.php';
* For simpler unit-testing
require_once 'PEAR/Dependency2.php';
if (!isset ($this->_registry)) {
$this->_registry = &$this->config->getRegistry ();
$channelschecked = array ();
// convert all parameters into PEAR_Downloader_Package objects
foreach ($params as $i => $param) {
$err = $params[$i]->initialize ($param);
// skip parameters that were missed by preferred_state
if (!isset ($this->_options['soft']) && $err->getMessage () !== '') {
$this->log(0 , $err->getMessage ());
$param = $param->getChannel () . '/' . $param->getPackage ();
if (!isset ($this->_options['soft'])) {
$this->log(2 , 'Package "' . $param . '" is not valid');
// Message logged above in a specific verbose mode, passing null to not show up on CLI
if ($params[$i] && $params[$i]->getType () == 'local') {
// bug #7090 skip channel.xml check for local packages
if ($params[$i] && !isset ($channelschecked[$params[$i]->getChannel ()]) &&
!isset ($this->_options['offline'])
$channelschecked[$params[$i]->getChannel ()] = true;
require_once 'System.php';
$curchannel = &$this->_registry->getChannel($params[$i]->getChannel ());
$mirror = $this->config->get ('preferred_mirror', null , $params[$i]->getChannel ());
$url = 'http://' . $mirror . '/channel.xml';
$a = $this->downloadHttp($url, $this->ui, $dir, null , $curchannel->lastModified ());
// Attempt fallback to https automatically
'/channel.xml', $this->ui, $dir, null , $curchannel->lastModified ());
$this->log(0 , 'WARNING: channel "' . $params[$i]->getChannel () . '" has ' .
'updated its protocols, use "' . PEAR_RUNTYPE . ' channel-update ' . $params[$i]->getChannel () .
if ($params[$i] && !isset ($this->_options['downloadonly'])) {
if (isset ($this->_options['packagingroot'])) {
$checkdir = $this->_prependPath (
$this->config->get ('php_dir', null , $params[$i]->getChannel ()),
$this->_options['packagingroot']);
$checkdir = $this->config->get ('php_dir',
null , $params[$i]->getChannel ());
while ($checkdir && $checkdir != '/' && !file_exists($checkdir)) {
$params[$i]->getChannel () . '" is not writeable by the current user');
if (!isset ($this->_options['nodeps']) && !isset ($this->_options['offline'])) {
foreach ($params as $i => $param) {
//PHP Bug 40768 / PEAR Bug #10944
//Nested foreaches fail in PHP 5.2.1
$ret = $params[$i]->detectDependencies ($params);
if (!isset ($this->_options['soft'])) {
$this->log(0 , $ret->getMessage ());
if (isset ($this->_options['offline'])) {
$this->log(3 , 'Skipping dependency download check, --offline specified');
if (count($errorparams)) {
foreach ($errorparams as $param) {
if (isset ($this->_options['pretend'])) {
foreach ($params as $i => $package) {
$pf = &$params[$i]->download ();
if (!isset ($this->_options['soft'])) {
$this->log(1 , $pf->getMessage ());
$this->log(0 , 'Error: cannot download "' .
$newparams[] = &$params[$i];
'file' => $pf->getArchiveFile (),
'pkg' => $pf->getPackage ()
// remove params that did not download successfully
if (!count($newparams)) {
$this->_downloadedPackages = $ret;
* @param array all packages to be installed
if (isset ($this->_options['downloadonly'])) {
$reset = $hasfailed = $failed = false;
foreach ($params as $i => $param) {
$deps = $param->getDeps ();
$send = $param->getPackageFile ();
$installcheck = $depchecker->validatePackage ($send, $this, $params);
if (!isset ($this->_options['soft'])) {
$this->log(0 , $installcheck->getMessage ());
if (!$reset && $param->alreadyValidated () && !$force) {
$send = $param->getPackageFile ();
$send = $param->getDownloadURL ();
$installcheck = $depchecker->validatePackage ($send, $this, $params);
if (!isset ($this->_options['soft'])) {
$this->log(0 , $installcheck->getMessage ());
if (isset ($deps['required']) && is_array($deps['required'])) {
foreach ($deps['required'] as $type => $dep) {
// note: Dependency2 will never return a PEAR_Error if ignore-errors
// is specified, so soft is needed to turn off logging
if (PEAR::isError($e = $depchecker->{" validate{$type}Dependency" }($dep,
if (!isset ($this->_options['soft'])) {
$this->log(0 , $e->getMessage ());
} elseif (is_array($e) && !$param->alreadyValidated ()) {
if (!isset ($this->_options['soft'])) {
$depchecker->{" validate{$type}Dependency" }($d,
if (!isset ($this->_options['soft'])) {
$this->log(0 , $e->getMessage ());
} elseif (is_array($e) && !$param->alreadyValidated ()) {
if (!isset ($this->_options['soft'])) {
if (isset ($deps['optional']) && is_array($deps['optional'])) {
foreach ($deps['optional'] as $type => $dep) {
$depchecker->{" validate{$type}Dependency" }($dep,
if (!isset ($this->_options['soft'])) {
$this->log(0 , $e->getMessage ());
} elseif (is_array($e) && !$param->alreadyValidated ()) {
if (!isset ($this->_options['soft'])) {
$depchecker->{" validate{$type}Dependency" }($d,
if (!isset ($this->_options['soft'])) {
$this->log(0 , $e->getMessage ());
} elseif (is_array($e) && !$param->alreadyValidated ()) {
if (!isset ($this->_options['soft'])) {
$groupname = $param->getGroup ();
if (isset ($deps['group']) && $groupname) {
if (!isset ($deps['group'][0 ])) {
$deps['group'] = array ($deps['group']);
foreach ($deps['group'] as $group) {
if ($group['attribs']['name'] == $groupname) {
unset ($group['attribs']);
foreach ($group as $type => $dep) {
$depchecker->{" validate{$type}Dependency" }($dep,
if (!isset ($this->_options['soft'])) {
$this->log(0 , $e->getMessage ());
} elseif (is_array($e) && !$param->alreadyValidated ()) {
if (!isset ($this->_options['soft'])) {
$depchecker->{" validate{$type}Dependency" }($d,
if (!isset ($this->_options['soft'])) {
$this->log(0 , $e->getMessage ());
} elseif (is_array($e) && !$param->alreadyValidated ()) {
if (!isset ($this->_options['soft'])) {
foreach ($deps as $dep) {
if (PEAR::isError($e = $depchecker->validateDependency1 ($dep, $params))) {
if (!isset ($this->_options ['soft'])) {
$this->log(0 , $e->getMessage ());
} elseif (is_array($e) && !$param->alreadyValidated ()) {
if (!isset ($this->_options ['soft'])) {
$params[$i]->setValidated ();
if ($hasfailed && (isset ($this->_options ['ignore-errors']) ||
isset ($this->_options ['nodeps']))) {
// this is probably not needed, but just in case
if (!isset ($this->_options ['soft'])) {
$this->log(0 , 'WARNING: dependencies failed');
* Retrieve the directory that downloads will happen in
function getDownloadDir ()
if (isset ($this->_downloadDir )) {
return $this->_downloadDir;
$downloaddir = $this->config->get ('download_dir');
$this->log(0 , 'WARNING: configuration download directory "' . $downloaddir .
'" is not writeable. Change download_dir config variable to ' .
'a writeable dir to avoid this warning');
require_once 'System.php';
$this->log(3 , '+ tmp dir created at ' . $downloaddir);
'" is not writeable. Change download_dir config variable to ' .
return $this->_downloadDir = $downloaddir;
'" is not writeable. Change download_dir config variable to ' .
$this->_downloadDir = $dir;
function configSet($key, $value, $layer = 'user', $channel = false )
$this->config->set ($key, $value, $layer, $channel);
$this->_preferredState = $this->config->get ('preferred_state', null , $channel);
if (!$this->_preferredState ) {
// don't inadvertantly use a non-set preferred_state
$this->_preferredState = null;
$this->_options = $options;
* @param array output of {@link parsePackageName()}
function _getPackageDownloadUrl ($parr)
$curchannel = $this->config->get ('default_channel');
$this->configSet('default_channel', $parr['channel']);
// getDownloadURL returns an array. On error, it only contains information
// on the latest release as array(version, info). On success it contains
// array(version, info, download url string)
$state = isset ($parr['state']) ? $parr['state'] : $this->config->get ('preferred_state');
if (!$this->_registry ->channelExists ($parr['channel'])) {
if ($this->config->get ('auto_discover') && $this->discover($parr['channel'])) {
$this->configSet('default_channel', $curchannel);
return PEAR::raiseError('Unknown remote channel: ' . $parr['channel']);
$chan = &$this->_registry ->getChannel ($parr['channel']);
$version = $this->_registry ->packageInfo ($parr['package'], 'version', $parr['channel']);
$stability = $this->_registry ->packageInfo ($parr['package'], 'stability', $parr['channel']);
// package is installed - use the installed release stability level
if (!isset ($parr['state']) && $stability !== null ) {
$state = $stability['release'];
$preferred_mirror = $this->config->get ('preferred_mirror');
if (!$chan->supportsREST ($preferred_mirror) ||
!($base2 = $chan->getBaseURL ('REST1.3', $preferred_mirror))
!($base = $chan->getBaseURL ('REST1.0', $preferred_mirror))
return $this->raiseError($parr['channel'] . ' is using a unsupported protocol - This should never happen.');
$rest = &$this->config->getREST ('1.3', $this->_options );
$rest = &$this->config->getREST ('1.0', $this->_options );
$downloadVersion = false;
if (!isset ($parr['version']) && !isset ($parr['state']) && $version
&& !isset ($this->_options ['downloadonly'])
$downloadVersion = $version;
$url = $rest->getDownloadURL ($base, $parr, $state, $downloadVersion, $chan->getName ());
$this->configSet('default_channel', $curchannel);
if ($parr['channel'] != $curchannel) {
$this->configSet('default_channel', $curchannel);
$url['raw'] = false; // no checking is necessary for REST
return PEAR::raiseError('Invalid remote dependencies retrieved from REST - ' .
'this should never happen');
if (!isset ($this->_options ['force']) &&
!isset ($this->_options ['downloadonly']) &&
$parr, true ) . ' is already installed and is the same as the ' .
'released version ' . $url['version'], -976 );
$parr, true ) . ' is already installed and is newer than detected ' .
'released version ' . $url['version'], -976 );
if (isset ($url['info']['required']) || $url['compatible']) {
require_once 'PEAR/PackageFile/v2.php';
$pf->setRawChannel ($parr['channel']);
if ($url['compatible']) {
$pf->setRawCompatible ($url['compatible']);
require_once 'PEAR/PackageFile/v1.php';
$pf->setRawPackage ($url['package']);
$pf->setDeps ($url['info']);
if ($url['compatible']) {
$pf->setCompatible ($url['compatible']);
$pf->setRawState ($url['stability']);
if (is_array($url) && isset ($url['url'])) {
* @param array dependency array
function _getDepPackageDownloadUrl ($dep, $parr)
$xsdversion = isset ($dep['rel']) ? '1.0' : '2.0';
$curchannel = $this->config->get ('default_channel');
if (isset ($dep['uri'])) {
$chan = &$this->_registry ->getChannel ('__uri');
$version = $this->_registry ->packageInfo ($dep['name'], 'version', '__uri');
$this->configSet('default_channel', '__uri');
if (isset ($dep['channel'])) {
$remotechannel = $dep['channel'];
$remotechannel = 'pear.php.net';
if (!$this->_registry ->channelExists ($remotechannel)) {
if ($this->config->get ('auto_discover')) {
$chan = &$this->_registry ->getChannel ($remotechannel);
$version = $this->_registry ->packageInfo ($dep['name'], 'version', $remotechannel);
$this->configSet('default_channel', $remotechannel);
$state = isset ($parr['state']) ? $parr['state'] : $this->config->get ('preferred_state');
if (isset ($parr['state']) && isset ($parr['version'])) {
if (isset ($dep['uri'])) {
$err = $info->initialize ($dep);
// skip parameters that were missed by preferred_state
if (!isset ($this->_options ['soft'])) {
$this->log(0 , $err->getMessage ());
$param = $info->getChannel () . '/' . $info->getPackage ();
} elseif ($chan->supportsREST ($this->config->get ('preferred_mirror'))
($base2 = $chan->getBaseURL ('REST1.3', $this->config->get ('preferred_mirror')))
($base = $chan->getBaseURL ('REST1.0', $this->config->get ('preferred_mirror')))
$rest = &$this->config->getREST ('1.3', $this->_options );
$rest = &$this->config->getREST ('1.0', $this->_options );
$url = $rest->getDepDownloadURL ($base, $xsdversion, $dep, $parr,
$state, $version, $chan->getName ());
if ($parr['channel'] != $curchannel) {
$this->configSet('default_channel', $curchannel);
$url['raw'] = false; // no checking is necessary for REST
return PEAR::raiseError('Invalid remote dependencies retrieved from REST - ' .
'this should never happen');
if (isset ($url['info']['required'])) {
require_once 'PEAR/PackageFile/v2.php';
$pf->setRawChannel ($remotechannel);
require_once 'PEAR/PackageFile/v1.php';
$pf->setRawPackage ($url['package']);
$pf->setDeps ($url['info']);
if ($url['compatible']) {
$pf->setCompatible ($url['compatible']);
$pf->setRawState ($url['stability']);
if (is_array($url) && isset ($url['url'])) {
return $this->raiseError($parr['channel'] . ' is using a unsupported protocol - This should never happen.');
* @deprecated in favor of _getPackageDownloadUrl
if ($this === null || $this->_registry === null ) {
$package = " http://pear.php.net/get/$package";
$chan = $this->_registry ->getChannel ($channel);
$package = "http://" . $chan->getServer () . " /get/$package";
$package .= '?uncompress=yes';
* Retrieve a list of downloaded packages after a call to {@link download()}.
* Also resets the list of downloaded packages.
$ret = $this->_downloadedPackages;
$this->_downloadedPackages = array ();
$this->_toDownload = array ();
function _downloadCallback ($msg, $params = null )
$this->log(1 , " downloading $params ..." );
$this->log(1 , '.', false );
$length = "Unknown size";
$this->log(1 , " Starting to download {$params[0]} ($length)" );
$this->ui->_downloadCallback ($msg, $params);
function _prependPath ($path, $prepend)
$prepend = substr($prepend, 2 );
} elseif ($prepend{0 } != '\\') {
$path = $prepend . $path;
array_push($this->_errorStack , array ($errmsg, $code));
$errs = $this->_errorStack;
foreach ($errs as $err) {
$this->_errorStack = array ();
$this->sortPackagesForUninstall ($packages) :
* Sort a list of arrays of array(downloaded packagefilename) by dependency.
* This uses the topological sort method from graph theory, and the
* Structures_Graph package to properly sort dependencies for installation.
* @param array an array of downloaded PEAR_Downloader_Packages
* @return array array of array(packagefilename, package.xml contents)
require_once 'Structures/Graph.php';
require_once 'Structures/Graph/Node.php';
require_once 'Structures/Graph/Manipulator/TopologicalSorter.php';
$depgraph = new Structures_Graph (true );
$reg = &$this->config->getRegistry ();
foreach ($packages as $i => $package) {
$pname = $reg->parsedPackageNameToString (
'channel' => $package->getChannel (),
$nodes[$pname] = new Structures_Graph_Node;
$nodes[$pname]->setData ($packages[$i]);
$depgraph->addNode ($nodes[$pname]);
foreach ($nodes as $package => $node) {
$pdeps = $pf->getDeps (true );
if ($pf->getPackagexmlVersion () == '1.0') {
foreach ($pdeps as $dep) {
if ($dep['type'] != 'pkg' ||
(isset ($dep['optional']) && $dep['optional'] == 'yes')) {
$dname = $reg->parsedPackageNameToString (
'channel' => 'pear.php.net',
if (isset ($nodes[$dname])) {
if (!isset ($deplinks[$dname])) {
$deplinks[$dname] = array ();
$deplinks[$dname][$package] = 1;
// dependency is in installed packages
$dname = $reg->parsedPackageNameToString (
'channel' => 'pecl.php.net',
if (isset ($nodes[$dname])) {
if (!isset ($deplinks[$dname])) {
$deplinks[$dname] = array ();
$deplinks[$dname][$package] = 1;
// dependency is in installed packages
// the only ordering we care about is:
// 1) subpackages must be installed before packages that depend on them
// 2) required deps must be installed before packages that depend on them
if (isset ($pdeps['required']['subpackage'])) {
$t = $pdeps['required']['subpackage'];
$this->_setupGraph ($t, $reg, $deplinks, $nodes, $package);
if (isset ($pdeps['group'])) {
if (!isset ($pdeps['group'][0 ])) {
$pdeps['group'] = array ($pdeps['group']);
foreach ($pdeps['group'] as $group) {
if (isset ($group['subpackage'])) {
$t = $group['subpackage'];
$this->_setupGraph ($t, $reg, $deplinks, $nodes, $package);
if (isset ($pdeps['optional']['subpackage'])) {
$t = $pdeps['optional']['subpackage'];
$this->_setupGraph ($t, $reg, $deplinks, $nodes, $package);
if (isset ($pdeps['required']['package'])) {
$t = $pdeps['required']['package'];
$this->_setupGraph ($t, $reg, $deplinks, $nodes, $package);
if (isset ($pdeps['group'])) {
if (!isset ($pdeps['group'][0 ])) {
$pdeps['group'] = array ($pdeps['group']);
foreach ($pdeps['group'] as $group) {
if (isset ($group['package'])) {
$this->_setupGraph ($t, $reg, $deplinks, $nodes, $package);
$this->_detectDepCycle ($deplinks);
foreach ($deplinks as $dependent => $parents) {
foreach ($parents as $parent => $unused) {
$nodes[$dependent]->connectTo ($nodes[$parent]);
$installOrder = Structures_Graph_Manipulator_TopologicalSorter ::sort ($depgraph);
for ($i = 0 , $count = count($installOrder); $i < $count; $i++ ) {
foreach ($installOrder[$i] as $index => $sortedpackage) {
$data = &$installOrder[$i][$index]->getData ();
$ret[] = &$nodes[$reg->parsedPackageNameToString (
'channel' => $data->getChannel (),
* Detect recursive links between dependencies and break the cycles
function _detectDepCycle (&$deplinks)
foreach ($deplinks as $dep => $parents) {
foreach ($parents as $parent => $unused) {
// reset the parent cycle detector
$this->_testCycle (null , null , null );
if ($this->_testCycle ($dep, $deplinks, $parent)) {
unset ($deplinks[$dep][$parent]);
if (count($deplinks[$dep]) == 0 ) {
function _testCycle ($test, $deplinks, $dep)
static $visited = array ();
// this happens when a parent has a dep cycle on another dependency
// but the child is not part of the cycle
if (isset ($visited[$dep])) {
if (isset ($deplinks[$dep])) {
foreach ($deplinks[$dep] as $parent => $unused) {
if ($this->_testCycle ($test, $deplinks, $parent)) {
* Set up the dependency for installation parsing
* @param array $t dependency information
* @param PEAR_Registry $reg
* @param array $deplinks list of dependency links already established
* @param array $nodes all existing package nodes
* @param string $package parent package name
function _setupGraph ($t, $reg, &$deplinks, &$nodes, $package)
$depchannel = !isset ($dep['channel']) ? '__uri': $dep['channel'];
$dname = $reg->parsedPackageNameToString (
'channel' => $depchannel,
if (isset ($nodes[$dname])) {
if (!isset ($deplinks[$dname])) {
$deplinks[$dname] = array ();
$deplinks[$dname][$package] = 1;
function _dependsOn ($a, $b)
function _checkDepTree ($channel, $package, $b, $checked = array ())
$checked[$channel][$package] = true;
if (!isset ($this->_depTree [$channel][$package])) {
if (isset ($this->_depTree [$channel][$package][strtolower($b->getChannel ())]
foreach ($this->_depTree [$channel][$package] as $ch => $packages) {
foreach ($packages as $pa => $true) {
if ($this->_checkDepTree ($ch, $pa, $b, $checked)) {
function _sortInstall ($a, $b)
if (!$a->getDeps () && !$b->getDeps ()) {
return 0; // neither package has dependencies, order is insignificant
if ($a->getDeps () && !$b->getDeps ()) {
return 1; // $a must be installed after $b because $a has dependencies
if (!$a->getDeps () && $b->getDeps ()) {
return -1; // $b must be installed after $a because $b has dependencies
// both packages have dependencies
if ($this->_dependsOn ($a, $b)) {
if ($this->_dependsOn ($b, $a)) {
* Download a file through HTTP. Considers suggested file name in
* Content-disposition: header and can run a callback function for
* different events. The callback will be called with two
* parameters: the callback type, and parameters. The implemented
* 'setup' called at the very beginning, parameter is a UI object
* that should be used for all output
* 'message' the parameter is a string with an informational message
* 'saveas' may be used to save with a different file name, the
* parameter is the filename that is about to be used.
* If a 'saveas' callback returns a non-empty string,
* that file name will be used as the filename instead.
* Note that $save_dir will not be affected by this, only
* the basename of the file.
* 'start' download is starting, parameter is number of bytes
* that are expected, or -1 if unknown
* 'bytesread' parameter is the number of bytes read so far
* 'done' download is complete, parameter is the total number
* 'connfailed' if the TCP/SSL connection fails, this callback is called
* with array(host,port,errno,errmsg)
* 'writefailed' if writing to disk fails, this callback is called
* with array(destfile,errmsg)
* If an HTTP proxy has been configured (http_proxy PEAR_Config
* setting), the proxy will be used.
* @param string $url the URL to download
* @param object $ui PEAR_Frontend_* instance
* @param object $config PEAR_Config instance
* @param string $save_dir directory to save file in
* @param mixed $callback function/method to call for status
* @param false|string|array$lastmodified header values to check against for caching
* use false to return the header values from this download
* @param false|array$accept Accept headers to send
* @param false|string$channel Channel to use for retrieving authentication
* @return string|array Returns the full path of the downloaded file or a PEAR
* error on failure. If the error is caused by
* socket-related errors, the error object will
* have the fsockopen error code available through
* getCode(). If caching is requested, then return the header
function downloadHttp($url, &$ui, $save_dir = '.', $callback = null , $lastmodified = null ,
$accept = false , $channel = false )
// always reset , so we are clean case of error
$wasredirect = $redirect;
call_user_func ($callback, 'setup', array (&$ui));
if (!isset ($info['scheme']) || !in_array($info['scheme'], array ('http', 'https'))) {
return PEAR::raiseError('Cannot download non-http URL "' . $url . '"');
if (!isset ($info['host'])) {
return PEAR::raiseError('Cannot download from non-URL "' . $url . '"');
$host = isset ($info['host']) ? $info['host'] : null;
$port = isset ($info['port']) ? $info['port'] : null;
$path = isset ($info['path']) ? $info['path'] : null;
$proxy_host = $proxy_port = $proxy_user = $proxy_pass = '';
if ($config->get ('http_proxy') &&
$proxy = parse_url($config->get ('http_proxy'))) {
$proxy_host = isset ($proxy['host']) ? $proxy['host'] : null;
if (isset ($proxy['scheme']) && $proxy['scheme'] == 'https') {
$proxy_host = 'ssl://' . $proxy_host;
$proxy_port = isset ($proxy['port']) ? $proxy['port'] : 8080;
$proxy_user = isset ($proxy['user']) ? urldecode($proxy['user']) : null;
$proxy_pass = isset ($proxy['pass']) ? urldecode($proxy['pass']) : null;
$port = (isset ($info['scheme']) && $info['scheme'] == 'https') ? 443 : 80;
$scheme = (isset ($info['scheme']) && $info['scheme'] == 'https') ? 'https' : 'http';
$fp = @fsockopen($proxy_host, $proxy_port, $errno, $errstr);
call_user_func($callback, 'connfailed', array ($proxy_host, $proxy_port,
return PEAR::raiseError(" Connection to `$proxy_host:$proxy_port' failed: $errstr" , $errno);
if ($lastmodified === false || $lastmodified) {
$request = " GET $url HTTP/1.1\r\n";
$request .= " Host: $host\r\n";
$request = " GET $url HTTP/1.0\r\n";
$request .= " Host: $host\r\n";
if (isset ($info['scheme']) && $info['scheme'] == 'https') {
$network_host = 'ssl://' . $host;
$fp = @fsockopen($network_host, $port, $errno, $errstr);
return PEAR::raiseError(" Connection to `$host:$port' failed: $errstr" , $errno);
if ($lastmodified === false || $lastmodified) {
$request = " GET $path HTTP/1.1\r\n";
$request .= " Host: $host\r\n";
$request = " GET $path HTTP/1.0\r\n";
$request .= " Host: $host\r\n";
if (isset ($lastmodified['Last-Modified'])) {
$ifmodifiedsince = 'If-Modified-Since: ' . $lastmodified['Last-Modified'] . "\r\n";
if (isset ($lastmodified['ETag'])) {
$ifmodifiedsince .= " If-None-Match: $lastmodified[ETag]\r\n";
$ifmodifiedsince = ($lastmodified ? " If-Modified-Since: $lastmodified\r\n" : '');
$request .= $ifmodifiedsince .
"User-Agent: PEAR/1.9.4/PHP/" . PHP_VERSION . "\r\n";
if (isset ($this)) { // only pass in authentication for non-static calls
$username = $config->get ('username', null , $channel);
$password = $config->get ('password', null , $channel);
if ($username && $password) {
$request .= " Authorization: Basic $tmp\r\n";
if ($proxy_host != '' && $proxy_user != '') {
$request .= 'Proxy-Authorization: Basic ' .
$request .= 'Accept: ' . implode(', ', $accept) . "\r\n";
$request .= "Connection: close\r\n";
if (preg_match('/^([^:]+):\s+(.*)\s*\\z/', $line, $matches)) {
} elseif (preg_match('|^HTTP/1.[01] ([0-9]{3}) |', $line, $matches)) {
$reply = (int) $matches[1 ];
if ($reply == 304 && ($lastmodified || ($lastmodified === false ))) {
if (!in_array($reply, array (200 , 301 , 302 , 303 , 305 , 307 ))) {
return PEAR::raiseError(" File $scheme://$host:$port$path not valid (received: $line)" );
if (!isset ($headers['location'])) {
return PEAR::raiseError(" File $scheme://$host:$port$path not valid (redirected but no location)" );
return PEAR::raiseError(" File $scheme://$host:$port$path not valid (redirection looped more than 5 times)" );
$redirect = $wasredirect + 1;
$ui, $save_dir, $callback, $lastmodified, $accept);
if (isset ($headers['content-disposition']) &&
preg_match('/\sfilename=\"([^;]*\S)\"\s*(;|\\z)/', $headers['content-disposition'], $matches)) {
$dest_file = $save_dir . DIRECTORY_SEPARATOR . $save_as;
return PEAR::raiseError('SECURITY ERROR: Will not write to ' . $dest_file . ' as it is symlinked to ' . readlink($dest_file) . ' - Possible symlink attack');
if (!$wp = @fopen($dest_file, 'wb')) {
call_user_func($callback, 'writefailed', array ($dest_file, $php_errormsg));
$length = isset ($headers['content-length']) ? $headers['content-length'] : -1;
while ($data = fread($fp, 1024 )) {
call_user_func($callback, 'writefailed', array ($dest_file, $php_errormsg));
if ($lastmodified === false || $lastmodified) {
if (isset ($headers['etag'])) {
$lastmodified = array ('ETag' => $headers['etag']);
if (isset ($headers['last-modified'])) {
$lastmodified['Last-Modified'] = $headers['last-modified'];
$lastmodified = $headers['last-modified'];
return array ($dest_file, $lastmodified, $headers);
Documentation generated on Wed, 06 Jul 2011 23:30:47 +0000 by phpDocumentor 1.4.3. PEAR Logo Copyright © PHP Group 2004.
|