3 * PEAR_Downloader, the PEAR Installer's download utility class
9 * @author Greg Beaver <cellog@php.net>
10 * @author Stig Bakken <ssb@php.net>
11 * @author Tomas V. V. Cox <cox@idecnet.com>
12 * @author Martin Jansen <mj@php.net>
13 * @copyright 1997-2009 The Authors
14 * @license http://opensource.org/licenses/bsd-license.php New BSD License
15 * @link http://pear.php.net/package/PEAR
16 * @since File available since Release 1.3.0
20 * Needed for constants, extending
22 require_once 'PEAR/Common.php';
24 define('PEAR_INSTALLER_OK', 1);
25 define('PEAR_INSTALLER_FAILED', 0);
26 define('PEAR_INSTALLER_SKIPPED', -1);
27 define('PEAR_INSTALLER_ERROR_NO_PREF_STATE', 2);
30 * Administration class used to download anything from the internet (PEAR Packages,
31 * static URLs, xml files)
35 * @author Greg Beaver <cellog@php.net>
36 * @author Stig Bakken <ssb@php.net>
37 * @author Tomas V. V. Cox <cox@idecnet.com>
38 * @author Martin Jansen <mj@php.net>
39 * @copyright 1997-2009 The Authors
40 * @license http://opensource.org/licenses/bsd-license.php New BSD License
41 * @version Release: 1.10.1
42 * @link http://pear.php.net/package/PEAR
43 * @since Class available since Release 1.3.0
45 class PEAR_Downloader extends PEAR_Common
54 * Preferred Installation State (snapshot, devel, alpha, beta, stable)
61 * Options from command-line passed to Install.
63 * Recognized options:<br />
64 * - onlyreqdeps : install all required dependencies as well
65 * - alldeps : install all dependencies, including optional
66 * - installroot : base relative path to install files in
67 * - force : force a download even if warnings would prevent it
68 * - nocompress : download uncompressed tarballs
69 * @see PEAR_Command_Install
76 * Downloaded Packages after a call to download().
78 * Format of each entry:
81 * array('pkg' => 'package_name', 'file' => '/path/to/local/file',
82 * 'info' => array() // parsed package.xml
88 var $_downloadedPackages = array();
91 * Packages slated for download.
93 * This is used to prevent downloading a package more than once should it be a dependency
94 * for two packages to be installed.
95 * Format of each entry:
98 * array('package_name1' => parsed package.xml, 'package_name2' => parsed package.xml,
104 var $_toDownload = array();
107 * Array of every package installed, with names lower-cased.
111 * array('package1' => 0, 'package2' => 1, );
115 var $_installed = array();
121 var $_errorStack = array();
127 var $_internalDownload = false;
130 * Temporary variable used in sorting packages by dependency in {@link sortPkgDeps()}
134 var $_packageSortTree;
137 * Temporary directory, or configuration value where downloads will occur
143 * List of methods that can be called both statically and non-statically.
146 protected static $bivalentMethods = array(
147 'setErrorHandling' => true,
148 'raiseError' => true,
149 'throwError' => true,
150 'pushErrorHandling' => true,
151 'popErrorHandling' => true,
152 'downloadHttp' => true,
156 * @param PEAR_Frontend_*
160 function __construct($ui = null, $options = array(), $config = null)
162 parent::__construct();
163 $this->_options = $options;
164 if ($config !== null) {
165 $this->config = &$config;
166 $this->_preferredState = $this->config->get('preferred_state');
169 if (!$this->_preferredState) {
170 // don't inadvertantly use a non-set preferred_state
171 $this->_preferredState = null;
174 if ($config !== null) {
175 if (isset($this->_options['installroot'])) {
176 $this->config->setInstallRoot($this->_options['installroot']);
178 $this->_registry = &$config->getRegistry();
181 if (isset($this->_options['alldeps']) || isset($this->_options['onlyreqdeps'])) {
182 $this->_installed = $this->_registry->listAllPackages();
183 foreach ($this->_installed as $key => $unused) {
184 if (!count($unused)) {
187 $strtolower = create_function('$a','return strtolower($a);');
188 array_walk($this->_installed[$key], $strtolower);
194 * Attempt to discover a channel's remote capabilities from
199 function discover($channel)
201 $this->log(1, 'Attempting to discover channel "' . $channel . '"...');
202 PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
203 $callback = $this->ui ? array(&$this, '_downloadCallback') : null;
204 if (!class_exists('System')) {
205 require_once 'System.php';
208 $tmpdir = $this->config->get('temp_dir');
209 $tmp = System::mktemp('-d -t "' . $tmpdir . '"');
210 $a = $this->downloadHttp('http://' . $channel . '/channel.xml', $this->ui, $tmp, $callback, false);
211 PEAR::popErrorHandling();
212 if (PEAR::isError($a)) {
213 // Attempt to fallback to https automatically.
214 PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
215 $this->log(1, 'Attempting fallback to https instead of http on channel "' . $channel . '"...');
216 $a = $this->downloadHttp('https://' . $channel . '/channel.xml', $this->ui, $tmp, $callback, false);
217 PEAR::popErrorHandling();
218 if (PEAR::isError($a)) {
223 list($a, $lastmodified) = $a;
224 if (!class_exists('PEAR_ChannelFile')) {
225 require_once 'PEAR/ChannelFile.php';
228 $b = new PEAR_ChannelFile;
229 if ($b->fromXmlFile($a)) {
231 if ($this->config->get('auto_discover')) {
232 $this->_registry->addChannel($b, $lastmodified);
233 $alias = $b->getName();
234 if ($b->getName() == $this->_registry->channelName($b->getAlias())) {
235 $alias = $b->getAlias();
238 $this->log(1, 'Auto-discovered channel "' . $channel .
239 '", alias "' . $alias . '", adding to registry');
250 * For simpler unit-testing
251 * @param PEAR_Downloader
252 * @return PEAR_Downloader_Package
254 function newDownloaderPackage(&$t)
256 if (!class_exists('PEAR_Downloader_Package')) {
257 require_once 'PEAR/Downloader/Package.php';
259 $a = new PEAR_Downloader_Package($t);
264 * For simpler unit-testing
270 function &getDependency2Object(&$c, $i, $p, $s)
272 if (!class_exists('PEAR_Dependency2')) {
273 require_once 'PEAR/Dependency2.php';
275 $z = new PEAR_Dependency2($c, $i, $p, $s);
279 function &download($params)
281 if (!count($params)) {
286 if (!isset($this->_registry)) {
287 $this->_registry = &$this->config->getRegistry();
290 $channelschecked = array();
291 // convert all parameters into PEAR_Downloader_Package objects
292 foreach ($params as $i => $param) {
293 $params[$i] = $this->newDownloaderPackage($this);
294 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
295 $err = $params[$i]->initialize($param);
296 PEAR::staticPopErrorHandling();
298 // skip parameters that were missed by preferred_state
302 if (PEAR::isError($err)) {
303 if (!isset($this->_options['soft']) && $err->getMessage() !== '') {
304 $this->log(0, $err->getMessage());
308 if (is_object($param)) {
309 $param = $param->getChannel() . '/' . $param->getPackage();
312 if (!isset($this->_options['soft'])) {
313 $this->log(2, 'Package "' . $param . '" is not valid');
316 // Message logged above in a specific verbose mode, passing null to not show up on CLI
317 $this->pushError(null, PEAR_INSTALLER_SKIPPED);
320 if ($params[$i] && $params[$i]->getType() == 'local') {
321 // bug #7090 skip channel.xml check for local packages
325 if ($params[$i] && !isset($channelschecked[$params[$i]->getChannel()]) &&
326 !isset($this->_options['offline'])
328 $channelschecked[$params[$i]->getChannel()] = true;
329 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
330 if (!class_exists('System')) {
331 require_once 'System.php';
334 $curchannel = $this->_registry->getChannel($params[$i]->getChannel());
335 if (PEAR::isError($curchannel)) {
336 PEAR::staticPopErrorHandling();
337 return $this->raiseError($curchannel);
340 if (PEAR::isError($dir = $this->getDownloadDir())) {
341 PEAR::staticPopErrorHandling();
345 $mirror = $this->config->get('preferred_mirror', null, $params[$i]->getChannel());
346 $url = 'http://' . $mirror . '/channel.xml';
347 $a = $this->downloadHttp($url, $this->ui, $dir, null, $curchannel->lastModified());
349 PEAR::staticPopErrorHandling();
351 //channel.xml not modified
353 } else if (PEAR::isError($a)) {
354 // Attempt fallback to https automatically
355 PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
356 $a = $this->downloadHttp('https://' . $mirror .
357 '/channel.xml', $this->ui, $dir, null, $curchannel->lastModified());
359 PEAR::staticPopErrorHandling();
360 if (PEAR::isError($a) || !$a) {
364 $this->log(0, 'WARNING: channel "' . $params[$i]->getChannel() . '" has ' .
365 'updated its protocols, use "' . PEAR_RUNTYPE . ' channel-update ' . $params[$i]->getChannel() .
370 if ($params[$i] && !isset($this->_options['downloadonly'])) {
371 if (isset($this->_options['packagingroot'])) {
372 $checkdir = $this->_prependPath(
373 $this->config->get('php_dir', null, $params[$i]->getChannel()),
374 $this->_options['packagingroot']);
376 $checkdir = $this->config->get('php_dir',
377 null, $params[$i]->getChannel());
380 while ($checkdir && $checkdir != '/' && !file_exists($checkdir)) {
381 $checkdir = dirname($checkdir);
384 if ($checkdir == '.') {
388 if (!is_writeable($checkdir)) {
389 return PEAR::raiseError('Cannot install, php_dir for channel "' .
390 $params[$i]->getChannel() . '" is not writeable by the current user');
396 unset($channelschecked);
397 PEAR_Downloader_Package::removeDuplicates($params);
398 if (!count($params)) {
403 if (!isset($this->_options['nodeps']) && !isset($this->_options['offline'])) {
407 foreach ($params as $i => $param) {
408 //PHP Bug 40768 / PEAR Bug #10944
409 //Nested foreaches fail in PHP 5.2.1
411 $ret = $params[$i]->detectDependencies($params);
412 if (PEAR::isError($ret)) {
415 PEAR_Downloader_Package::removeDuplicates($params);
416 if (!isset($this->_options['soft'])) {
417 $this->log(0, $ret->getMessage());
425 if (isset($this->_options['offline'])) {
426 $this->log(3, 'Skipping dependency download check, --offline specified');
429 if (!count($params)) {
434 while (PEAR_Downloader_Package::mergeDependencies($params));
435 PEAR_Downloader_Package::removeDuplicates($params, true);
436 $errorparams = array();
437 if (PEAR_Downloader_Package::detectStupidDuplicates($params, $errorparams)) {
438 if (count($errorparams)) {
439 foreach ($errorparams as $param) {
440 $name = $this->_registry->parsedPackageNameToString($param->getParsedPackage());
441 $this->pushError('Duplicate package ' . $name . ' found', PEAR_INSTALLER_FAILED);
448 PEAR_Downloader_Package::removeInstalled($params);
449 if (!count($params)) {
450 $this->pushError('No valid packages found', PEAR_INSTALLER_FAILED);
455 PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
456 $err = $this->analyzeDependencies($params);
457 PEAR::popErrorHandling();
458 if (!count($params)) {
459 $this->pushError('No valid packages found', PEAR_INSTALLER_FAILED);
465 $newparams = array();
466 if (isset($this->_options['pretend'])) {
471 foreach ($params as $i => $package) {
472 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
473 $pf = &$params[$i]->download();
474 PEAR::staticPopErrorHandling();
475 if (PEAR::isError($pf)) {
476 if (!isset($this->_options['soft'])) {
477 $this->log(1, $pf->getMessage());
478 $this->log(0, 'Error: cannot download "' .
479 $this->_registry->parsedPackageNameToString($package->getParsedPackage(),
487 $newparams[] = &$params[$i];
489 'file' => $pf->getArchiveFile(),
491 'pkg' => $pf->getPackage()
496 // remove params that did not download successfully
497 PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
498 $err = $this->analyzeDependencies($newparams, true);
499 PEAR::popErrorHandling();
500 if (!count($newparams)) {
501 $this->pushError('Download failed', PEAR_INSTALLER_FAILED);
507 $this->_downloadedPackages = $ret;
512 * @param array all packages to be installed
514 function analyzeDependencies(&$params, $force = false)
516 if (isset($this->_options['downloadonly'])) {
520 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
522 $reset = $hasfailed = $failed = false;
525 foreach ($params as $i => $param) {
526 $deps = $param->getDeps();
528 $depchecker = &$this->getDependency2Object($this->config, $this->getOptions(),
529 $param->getParsedPackage(), PEAR_VALIDATE_DOWNLOADING);
530 $send = $param->getPackageFile();
532 $installcheck = $depchecker->validatePackage($send, $this, $params);
533 if (PEAR::isError($installcheck)) {
534 if (!isset($this->_options['soft'])) {
535 $this->log(0, $installcheck->getMessage());
542 PEAR_Downloader_Package::removeDuplicates($params);
548 if (!$reset && $param->alreadyValidated() && !$force) {
553 $depchecker = &$this->getDependency2Object($this->config, $this->getOptions(),
554 $param->getParsedPackage(), PEAR_VALIDATE_DOWNLOADING);
555 $send = $param->getPackageFile();
556 if ($send === null) {
557 $send = $param->getDownloadURL();
560 $installcheck = $depchecker->validatePackage($send, $this, $params);
561 if (PEAR::isError($installcheck)) {
562 if (!isset($this->_options['soft'])) {
563 $this->log(0, $installcheck->getMessage());
570 PEAR_Downloader_Package::removeDuplicates($params);
575 if (isset($deps['required']) && is_array($deps['required'])) {
576 foreach ($deps['required'] as $type => $dep) {
577 // note: Dependency2 will never return a PEAR_Error if ignore-errors
578 // is specified, so soft is needed to turn off logging
579 if (!isset($dep[0])) {
580 if (PEAR::isError($e = $depchecker->{"validate{$type}Dependency"}($dep,
583 if (!isset($this->_options['soft'])) {
584 $this->log(0, $e->getMessage());
586 } elseif (is_array($e) && !$param->alreadyValidated()) {
587 if (!isset($this->_options['soft'])) {
588 $this->log(0, $e[0]);
592 foreach ($dep as $d) {
593 if (PEAR::isError($e =
594 $depchecker->{"validate{$type}Dependency"}($d,
597 if (!isset($this->_options['soft'])) {
598 $this->log(0, $e->getMessage());
600 } elseif (is_array($e) && !$param->alreadyValidated()) {
601 if (!isset($this->_options['soft'])) {
602 $this->log(0, $e[0]);
609 if (isset($deps['optional']) && is_array($deps['optional'])) {
610 foreach ($deps['optional'] as $type => $dep) {
611 if (!isset($dep[0])) {
612 if (PEAR::isError($e =
613 $depchecker->{"validate{$type}Dependency"}($dep,
616 if (!isset($this->_options['soft'])) {
617 $this->log(0, $e->getMessage());
619 } elseif (is_array($e) && !$param->alreadyValidated()) {
620 if (!isset($this->_options['soft'])) {
621 $this->log(0, $e[0]);
625 foreach ($dep as $d) {
626 if (PEAR::isError($e =
627 $depchecker->{"validate{$type}Dependency"}($d,
630 if (!isset($this->_options['soft'])) {
631 $this->log(0, $e->getMessage());
633 } elseif (is_array($e) && !$param->alreadyValidated()) {
634 if (!isset($this->_options['soft'])) {
635 $this->log(0, $e[0]);
643 $groupname = $param->getGroup();
644 if (isset($deps['group']) && $groupname) {
645 if (!isset($deps['group'][0])) {
646 $deps['group'] = array($deps['group']);
650 foreach ($deps['group'] as $group) {
651 if ($group['attribs']['name'] == $groupname) {
658 unset($group['attribs']);
659 foreach ($group as $type => $dep) {
660 if (!isset($dep[0])) {
661 if (PEAR::isError($e =
662 $depchecker->{"validate{$type}Dependency"}($dep,
665 if (!isset($this->_options['soft'])) {
666 $this->log(0, $e->getMessage());
668 } elseif (is_array($e) && !$param->alreadyValidated()) {
669 if (!isset($this->_options['soft'])) {
670 $this->log(0, $e[0]);
674 foreach ($dep as $d) {
675 if (PEAR::isError($e =
676 $depchecker->{"validate{$type}Dependency"}($d,
679 if (!isset($this->_options['soft'])) {
680 $this->log(0, $e->getMessage());
682 } elseif (is_array($e) && !$param->alreadyValidated()) {
683 if (!isset($this->_options['soft'])) {
684 $this->log(0, $e[0]);
693 foreach ($deps as $dep) {
694 if (PEAR::isError($e = $depchecker->validateDependency1($dep, $params))) {
696 if (!isset($this->_options['soft'])) {
697 $this->log(0, $e->getMessage());
699 } elseif (is_array($e) && !$param->alreadyValidated()) {
700 if (!isset($this->_options['soft'])) {
701 $this->log(0, $e[0]);
706 $params[$i]->setValidated();
715 PEAR_Downloader_Package::removeDuplicates($params);
721 PEAR::staticPopErrorHandling();
722 if ($hasfailed && (isset($this->_options['ignore-errors']) ||
723 isset($this->_options['nodeps']))) {
724 // this is probably not needed, but just in case
725 if (!isset($this->_options['soft'])) {
726 $this->log(0, 'WARNING: dependencies failed');
732 * Retrieve the directory that downloads will happen in
736 function getDownloadDir()
738 if (isset($this->_downloadDir)) {
739 return $this->_downloadDir;
742 $downloaddir = $this->config->get('download_dir');
743 if (empty($downloaddir) || (is_dir($downloaddir) && !is_writable($downloaddir))) {
744 if (is_dir($downloaddir) && !is_writable($downloaddir)) {
745 $this->log(0, 'WARNING: configuration download directory "' . $downloaddir .
746 '" is not writeable. Change download_dir config variable to ' .
747 'a writeable dir to avoid this warning');
750 if (!class_exists('System')) {
751 require_once 'System.php';
754 if (PEAR::isError($downloaddir = System::mktemp('-d'))) {
757 $this->log(3, '+ tmp dir created at ' . $downloaddir);
760 if (!is_writable($downloaddir)) {
761 if (PEAR::isError(System::mkdir(array('-p', $downloaddir))) ||
762 !is_writable($downloaddir)) {
763 return PEAR::raiseError('download directory "' . $downloaddir .
764 '" is not writeable. Change download_dir config variable to ' .
769 return $this->_downloadDir = $downloaddir;
772 function setDownloadDir($dir)
774 if (!@is_writable($dir)) {
775 if (PEAR::isError(System::mkdir(array('-p', $dir)))) {
776 return PEAR::raiseError('download directory "' . $dir .
777 '" is not writeable. Change download_dir config variable to ' .
781 $this->_downloadDir = $dir;
784 function configSet($key, $value, $layer = 'user', $channel = false)
786 $this->config->set($key, $value, $layer, $channel);
787 $this->_preferredState = $this->config->get('preferred_state', null, $channel);
788 if (!$this->_preferredState) {
789 // don't inadvertantly use a non-set preferred_state
790 $this->_preferredState = null;
794 function setOptions($options)
796 $this->_options = $options;
799 function getOptions()
801 return $this->_options;
806 * @param array output of {@link parsePackageName()}
809 function _getPackageDownloadUrl($parr)
811 $curchannel = $this->config->get('default_channel');
812 $this->configSet('default_channel', $parr['channel']);
813 // getDownloadURL returns an array. On error, it only contains information
814 // on the latest release as array(version, info). On success it contains
815 // array(version, info, download url string)
816 $state = isset($parr['state']) ? $parr['state'] : $this->config->get('preferred_state');
817 if (!$this->_registry->channelExists($parr['channel'])) {
819 if ($this->config->get('auto_discover') && $this->discover($parr['channel'])) {
823 $this->configSet('default_channel', $curchannel);
824 return PEAR::raiseError('Unknown remote channel: ' . $parr['channel']);
828 $chan = $this->_registry->getChannel($parr['channel']);
829 if (PEAR::isError($chan)) {
833 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
834 $version = $this->_registry->packageInfo($parr['package'], 'version', $parr['channel']);
835 $stability = $this->_registry->packageInfo($parr['package'], 'stability', $parr['channel']);
836 // package is installed - use the installed release stability level
837 if (!isset($parr['state']) && $stability !== null) {
838 $state = $stability['release'];
840 PEAR::staticPopErrorHandling();
843 $preferred_mirror = $this->config->get('preferred_mirror');
844 if (!$chan->supportsREST($preferred_mirror) ||
846 !($base2 = $chan->getBaseURL('REST1.3', $preferred_mirror))
848 !($base = $chan->getBaseURL('REST1.0', $preferred_mirror))
851 return $this->raiseError($parr['channel'] . ' is using a unsupported protocol - This should never happen.');
855 $rest = &$this->config->getREST('1.3', $this->_options);
858 $rest = &$this->config->getREST('1.0', $this->_options);
861 $downloadVersion = false;
862 if (!isset($parr['version']) && !isset($parr['state']) && $version
863 && !PEAR::isError($version)
864 && !isset($this->_options['downloadonly'])
866 $downloadVersion = $version;
869 $url = $rest->getDownloadURL($base, $parr, $state, $downloadVersion, $chan->getName());
870 if (PEAR::isError($url)) {
871 $this->configSet('default_channel', $curchannel);
875 if ($parr['channel'] != $curchannel) {
876 $this->configSet('default_channel', $curchannel);
879 if (!is_array($url)) {
883 $url['raw'] = false; // no checking is necessary for REST
884 if (!is_array($url['info'])) {
885 return PEAR::raiseError('Invalid remote dependencies retrieved from REST - ' .
886 'this should never happen');
889 if (!isset($this->_options['force']) &&
890 !isset($this->_options['downloadonly']) &&
892 !PEAR::isError($version) &&
893 !isset($parr['group'])
895 if (version_compare($version, $url['version'], '=')) {
896 return PEAR::raiseError($this->_registry->parsedPackageNameToString(
897 $parr, true) . ' is already installed and is the same as the ' .
898 'released version ' . $url['version'], -976);
901 if (version_compare($version, $url['version'], '>')) {
902 return PEAR::raiseError($this->_registry->parsedPackageNameToString(
903 $parr, true) . ' is already installed and is newer than detected ' .
904 'released version ' . $url['version'], -976);
908 if (isset($url['info']['required']) || $url['compatible']) {
909 require_once 'PEAR/PackageFile/v2.php';
910 $pf = new PEAR_PackageFile_v2;
911 $pf->setRawChannel($parr['channel']);
912 if ($url['compatible']) {
913 $pf->setRawCompatible($url['compatible']);
916 require_once 'PEAR/PackageFile/v1.php';
917 $pf = new PEAR_PackageFile_v1;
920 $pf->setRawPackage($url['package']);
921 $pf->setDeps($url['info']);
922 if ($url['compatible']) {
923 $pf->setCompatible($url['compatible']);
926 $pf->setRawState($url['stability']);
928 if (!extension_loaded("zlib") || isset($this->_options['nocompress'])) {
934 if (is_array($url) && isset($url['url'])) {
942 * @param array dependency array
945 function _getDepPackageDownloadUrl($dep, $parr)
947 $xsdversion = isset($dep['rel']) ? '1.0' : '2.0';
948 $curchannel = $this->config->get('default_channel');
949 if (isset($dep['uri'])) {
951 $chan = $this->_registry->getChannel('__uri');
952 if (PEAR::isError($chan)) {
956 $version = $this->_registry->packageInfo($dep['name'], 'version', '__uri');
957 $this->configSet('default_channel', '__uri');
959 if (isset($dep['channel'])) {
960 $remotechannel = $dep['channel'];
962 $remotechannel = 'pear.php.net';
965 if (!$this->_registry->channelExists($remotechannel)) {
967 if ($this->config->get('auto_discover')) {
968 if ($this->discover($remotechannel)) {
972 return PEAR::raiseError('Unknown remote channel: ' . $remotechannel);
976 $chan = $this->_registry->getChannel($remotechannel);
977 if (PEAR::isError($chan)) {
981 $version = $this->_registry->packageInfo($dep['name'], 'version', $remotechannel);
982 $this->configSet('default_channel', $remotechannel);
985 $state = isset($parr['state']) ? $parr['state'] : $this->config->get('preferred_state');
986 if (isset($parr['state']) && isset($parr['version'])) {
987 unset($parr['state']);
990 if (isset($dep['uri'])) {
991 $info = $this->newDownloaderPackage($this);
992 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
993 $err = $info->initialize($dep);
994 PEAR::staticPopErrorHandling();
996 // skip parameters that were missed by preferred_state
997 return PEAR::raiseError('Cannot initialize dependency');
1000 if (PEAR::isError($err)) {
1001 if (!isset($this->_options['soft'])) {
1002 $this->log(0, $err->getMessage());
1005 if (is_object($info)) {
1006 $param = $info->getChannel() . '/' . $info->getPackage();
1008 return PEAR::raiseError('Package "' . $param . '" is not valid');
1011 } elseif ($chan->supportsREST($this->config->get('preferred_mirror'))
1014 ($base2 = $chan->getBaseURL('REST1.3', $this->config->get('preferred_mirror')))
1016 ($base = $chan->getBaseURL('REST1.0', $this->config->get('preferred_mirror')))
1021 $rest = &$this->config->getREST('1.3', $this->_options);
1023 $rest = &$this->config->getREST('1.0', $this->_options);
1026 $url = $rest->getDepDownloadURL($base, $xsdversion, $dep, $parr,
1027 $state, $version, $chan->getName());
1028 if (PEAR::isError($url)) {
1032 if ($parr['channel'] != $curchannel) {
1033 $this->configSet('default_channel', $curchannel);
1036 if (!is_array($url)) {
1040 $url['raw'] = false; // no checking is necessary for REST
1041 if (!is_array($url['info'])) {
1042 return PEAR::raiseError('Invalid remote dependencies retrieved from REST - ' .
1043 'this should never happen');
1046 if (isset($url['info']['required'])) {
1047 if (!class_exists('PEAR_PackageFile_v2')) {
1048 require_once 'PEAR/PackageFile/v2.php';
1050 $pf = new PEAR_PackageFile_v2;
1051 $pf->setRawChannel($remotechannel);
1053 if (!class_exists('PEAR_PackageFile_v1')) {
1054 require_once 'PEAR/PackageFile/v1.php';
1056 $pf = new PEAR_PackageFile_v1;
1059 $pf->setRawPackage($url['package']);
1060 $pf->setDeps($url['info']);
1061 if ($url['compatible']) {
1062 $pf->setCompatible($url['compatible']);
1065 $pf->setRawState($url['stability']);
1066 $url['info'] = &$pf;
1067 if (!extension_loaded("zlib") || isset($this->_options['nocompress'])) {
1073 if (is_array($url) && isset($url['url'])) {
1074 $url['url'] .= $ext;
1080 return $this->raiseError($parr['channel'] . ' is using a unsupported protocol - This should never happen.');
1084 * @deprecated in favor of _getPackageDownloadUrl
1086 function getPackageDownloadUrl($package, $version = null, $channel = false)
1089 $package .= "-$version";
1091 if ($this === null || $this->_registry === null) {
1092 $package = "http://pear.php.net/get/$package";
1094 $chan = $this->_registry->getChannel($channel);
1095 if (PEAR::isError($chan)) {
1098 $package = "http://" . $chan->getServer() . "/get/$package";
1100 if (!extension_loaded("zlib")) {
1101 $package .= '?uncompress=yes';
1107 * Retrieve a list of downloaded packages after a call to {@link download()}.
1109 * Also resets the list of downloaded packages.
1112 function getDownloadedPackages()
1114 $ret = $this->_downloadedPackages;
1115 $this->_downloadedPackages = array();
1116 $this->_toDownload = array();
1120 function _downloadCallback($msg, $params = null)
1124 $this->log(1, "downloading $params ...");
1127 $this->log(1, '...done: ' . number_format($params, 0, '', ',') . ' bytes');
1131 if (empty($bytes)) {
1134 if (!($bytes % 10240)) {
1135 $this->log(1, '.', false);
1140 if($params[1] == -1) {
1141 $length = "Unknown size";
1143 $length = number_format($params[1], 0, '', ',')." bytes";
1145 $this->log(1, "Starting to download {$params[0]} ($length)");
1148 if (method_exists($this->ui, '_downloadCallback'))
1149 $this->ui->_downloadCallback($msg, $params);
1152 function _prependPath($path, $prepend)
1154 if (strlen($prepend) > 0) {
1155 if (OS_WINDOWS && preg_match('/^[a-z]:/i', $path)) {
1156 if (preg_match('/^[a-z]:/i', $prepend)) {
1157 $prepend = substr($prepend, 2);
1158 } elseif ($prepend{0} != '\\') {
1159 $prepend = "\\$prepend";
1161 $path = substr($path, 0, 2) . $prepend . substr($path, 2);
1163 $path = $prepend . $path;
1173 function pushError($errmsg, $code = -1)
1175 array_push($this->_errorStack, array($errmsg, $code));
1178 function getErrorMsgs()
1181 $errs = $this->_errorStack;
1182 foreach ($errs as $err) {
1185 $this->_errorStack = array();
1194 function sortPkgDeps(&$packages, $uninstall = false)
1197 $this->sortPackagesForUninstall($packages) :
1198 $this->sortPackagesForInstall($packages);
1202 * Sort a list of arrays of array(downloaded packagefilename) by dependency.
1204 * This uses the topological sort method from graph theory, and the
1205 * Structures_Graph package to properly sort dependencies for installation.
1206 * @param array an array of downloaded PEAR_Downloader_Packages
1207 * @return array array of array(packagefilename, package.xml contents)
1209 function sortPackagesForInstall(&$packages)
1211 require_once 'Structures/Graph.php';
1212 require_once 'Structures/Graph/Node.php';
1213 require_once 'Structures/Graph/Manipulator/TopologicalSorter.php';
1214 $depgraph = new Structures_Graph(true);
1216 $reg = &$this->config->getRegistry();
1217 foreach ($packages as $i => $package) {
1218 $pname = $reg->parsedPackageNameToString(
1220 'channel' => $package->getChannel(),
1221 'package' => strtolower($package->getPackage()),
1223 $nodes[$pname] = new Structures_Graph_Node;
1224 $nodes[$pname]->setData($packages[$i]);
1225 $depgraph->addNode($nodes[$pname]);
1228 $deplinks = array();
1229 foreach ($nodes as $package => $node) {
1230 $pf = &$node->getData();
1231 $pdeps = $pf->getDeps(true);
1236 if ($pf->getPackagexmlVersion() == '1.0') {
1237 foreach ($pdeps as $dep) {
1238 if ($dep['type'] != 'pkg' ||
1239 (isset($dep['optional']) && $dep['optional'] == 'yes')) {
1243 $dname = $reg->parsedPackageNameToString(
1245 'channel' => 'pear.php.net',
1246 'package' => strtolower($dep['name']),
1249 if (isset($nodes[$dname])) {
1250 if (!isset($deplinks[$dname])) {
1251 $deplinks[$dname] = array();
1254 $deplinks[$dname][$package] = 1;
1255 // dependency is in installed packages
1259 $dname = $reg->parsedPackageNameToString(
1261 'channel' => 'pecl.php.net',
1262 'package' => strtolower($dep['name']),
1265 if (isset($nodes[$dname])) {
1266 if (!isset($deplinks[$dname])) {
1267 $deplinks[$dname] = array();
1270 $deplinks[$dname][$package] = 1;
1271 // dependency is in installed packages
1276 // the only ordering we care about is:
1277 // 1) subpackages must be installed before packages that depend on them
1278 // 2) required deps must be installed before packages that depend on them
1279 if (isset($pdeps['required']['subpackage'])) {
1280 $t = $pdeps['required']['subpackage'];
1281 if (!isset($t[0])) {
1285 $this->_setupGraph($t, $reg, $deplinks, $nodes, $package);
1288 if (isset($pdeps['group'])) {
1289 if (!isset($pdeps['group'][0])) {
1290 $pdeps['group'] = array($pdeps['group']);
1293 foreach ($pdeps['group'] as $group) {
1294 if (isset($group['subpackage'])) {
1295 $t = $group['subpackage'];
1296 if (!isset($t[0])) {
1300 $this->_setupGraph($t, $reg, $deplinks, $nodes, $package);
1305 if (isset($pdeps['optional']['subpackage'])) {
1306 $t = $pdeps['optional']['subpackage'];
1307 if (!isset($t[0])) {
1311 $this->_setupGraph($t, $reg, $deplinks, $nodes, $package);
1314 if (isset($pdeps['required']['package'])) {
1315 $t = $pdeps['required']['package'];
1316 if (!isset($t[0])) {
1320 $this->_setupGraph($t, $reg, $deplinks, $nodes, $package);
1323 if (isset($pdeps['group'])) {
1324 if (!isset($pdeps['group'][0])) {
1325 $pdeps['group'] = array($pdeps['group']);
1328 foreach ($pdeps['group'] as $group) {
1329 if (isset($group['package'])) {
1330 $t = $group['package'];
1331 if (!isset($t[0])) {
1335 $this->_setupGraph($t, $reg, $deplinks, $nodes, $package);
1342 $this->_detectDepCycle($deplinks);
1343 foreach ($deplinks as $dependent => $parents) {
1344 foreach ($parents as $parent => $unused) {
1345 $nodes[$dependent]->connectTo($nodes[$parent]);
1349 $installOrder = Structures_Graph_Manipulator_TopologicalSorter::sort($depgraph);
1351 for ($i = 0, $count = count($installOrder); $i < $count; $i++) {
1352 foreach ($installOrder[$i] as $index => $sortedpackage) {
1353 $data = &$installOrder[$i][$index]->getData();
1354 $ret[] = &$nodes[$reg->parsedPackageNameToString(
1356 'channel' => $data->getChannel(),
1357 'package' => strtolower($data->getPackage()),
1367 * Detect recursive links between dependencies and break the cycles
1372 function _detectDepCycle(&$deplinks)
1376 foreach ($deplinks as $dep => $parents) {
1377 foreach ($parents as $parent => $unused) {
1378 // reset the parent cycle detector
1379 $this->_testCycle(null, null, null);
1380 if ($this->_testCycle($dep, $deplinks, $parent)) {
1382 unset($deplinks[$dep][$parent]);
1383 if (count($deplinks[$dep]) == 0) {
1384 unset($deplinks[$dep]);
1391 } while ($keepgoing);
1394 function _testCycle($test, $deplinks, $dep)
1396 static $visited = array();
1397 if ($test === null) {
1402 // this happens when a parent has a dep cycle on another dependency
1403 // but the child is not part of the cycle
1404 if (isset($visited[$dep])) {
1409 if ($test == $dep) {
1413 if (isset($deplinks[$dep])) {
1414 if (in_array($test, array_keys($deplinks[$dep]), true)) {
1418 foreach ($deplinks[$dep] as $parent => $unused) {
1419 if ($this->_testCycle($test, $deplinks, $parent)) {
1429 * Set up the dependency for installation parsing
1431 * @param array $t dependency information
1432 * @param PEAR_Registry $reg
1433 * @param array $deplinks list of dependency links already established
1434 * @param array $nodes all existing package nodes
1435 * @param string $package parent package name
1438 function _setupGraph($t, $reg, &$deplinks, &$nodes, $package)
1440 foreach ($t as $dep) {
1441 $depchannel = !isset($dep['channel']) ? '__uri': $dep['channel'];
1442 $dname = $reg->parsedPackageNameToString(
1444 'channel' => $depchannel,
1445 'package' => strtolower($dep['name']),
1448 if (isset($nodes[$dname])) {
1449 if (!isset($deplinks[$dname])) {
1450 $deplinks[$dname] = array();
1452 $deplinks[$dname][$package] = 1;
1457 function _dependsOn($a, $b)
1459 return $this->_checkDepTree(strtolower($a->getChannel()), strtolower($a->getPackage()), $b);
1462 function _checkDepTree($channel, $package, $b, $checked = array())
1464 $checked[$channel][$package] = true;
1465 if (!isset($this->_depTree[$channel][$package])) {
1469 if (isset($this->_depTree[$channel][$package][strtolower($b->getChannel())]
1470 [strtolower($b->getPackage())])) {
1474 foreach ($this->_depTree[$channel][$package] as $ch => $packages) {
1475 foreach ($packages as $pa => $true) {
1476 if ($this->_checkDepTree($ch, $pa, $b, $checked)) {
1485 function _sortInstall($a, $b)
1487 if (!$a->getDeps() && !$b->getDeps()) {
1488 return 0; // neither package has dependencies, order is insignificant
1490 if ($a->getDeps() && !$b->getDeps()) {
1491 return 1; // $a must be installed after $b because $a has dependencies
1493 if (!$a->getDeps() && $b->getDeps()) {
1494 return -1; // $b must be installed after $a because $b has dependencies
1496 // both packages have dependencies
1497 if ($this->_dependsOn($a, $b)) {
1500 if ($this->_dependsOn($b, $a)) {
1507 * Download a file through HTTP. Considers suggested file name in
1508 * Content-disposition: header and can run a callback function for
1509 * different events. The callback will be called with two
1510 * parameters: the callback type, and parameters. The implemented
1511 * callback types are:
1513 * 'setup' called at the very beginning, parameter is a UI object
1514 * that should be used for all output
1515 * 'message' the parameter is a string with an informational message
1516 * 'saveas' may be used to save with a different file name, the
1517 * parameter is the filename that is about to be used.
1518 * If a 'saveas' callback returns a non-empty string,
1519 * that file name will be used as the filename instead.
1520 * Note that $save_dir will not be affected by this, only
1521 * the basename of the file.
1522 * 'start' download is starting, parameter is number of bytes
1523 * that are expected, or -1 if unknown
1524 * 'bytesread' parameter is the number of bytes read so far
1525 * 'done' download is complete, parameter is the total number
1527 * 'connfailed' if the TCP/SSL connection fails, this callback is called
1528 * with array(host,port,errno,errmsg)
1529 * 'writefailed' if writing to disk fails, this callback is called
1530 * with array(destfile,errmsg)
1532 * If an HTTP proxy has been configured (http_proxy PEAR_Config
1533 * setting), the proxy will be used.
1535 * @param string $url the URL to download
1536 * @param object $ui PEAR_Frontend_* instance
1537 * @param object $config PEAR_Config instance
1538 * @param string $save_dir directory to save file in
1539 * @param mixed $callback function/method to call for status
1541 * @param false|string|array $lastmodified header values to check against for caching
1542 * use false to return the header values from this download
1543 * @param false|array $accept Accept headers to send
1544 * @param false|string $channel Channel to use for retrieving authentication
1545 * @return mixed Returns the full path of the downloaded file or a PEAR
1546 * error on failure. If the error is caused by
1547 * socket-related errors, the error object will
1548 * have the fsockopen error code available through
1549 * getCode(). If caching is requested, then return the header
1551 * If $lastmodified was given and the there are no changes,
1552 * boolean false is returned.
1556 public static function _downloadHttp(
1557 $object, $url, &$ui, $save_dir = '.', $callback = null, $lastmodified = null,
1558 $accept = false, $channel = false
1560 static $redirect = 0;
1561 // always reset , so we are clean case of error
1562 $wasredirect = $redirect;
1565 call_user_func($callback, 'setup', array(&$ui));
1568 $info = parse_url($url);
1569 if (!isset($info['scheme']) || !in_array($info['scheme'], array('http', 'https'))) {
1570 return PEAR::raiseError('Cannot download non-http URL "' . $url . '"');
1573 if (!isset($info['host'])) {
1574 return PEAR::raiseError('Cannot download from non-URL "' . $url . '"');
1577 $host = isset($info['host']) ? $info['host'] : null;
1578 $port = isset($info['port']) ? $info['port'] : null;
1579 $path = isset($info['path']) ? $info['path'] : null;
1581 if ($object !== null) {
1582 $config = $object->config;
1584 $config = &PEAR_Config::singleton();
1587 $proxy_host = $proxy_port = $proxy_user = $proxy_pass = '';
1588 if ($config->get('http_proxy') &&
1589 $proxy = parse_url($config->get('http_proxy'))) {
1590 $proxy_host = isset($proxy['host']) ? $proxy['host'] : null;
1591 if (isset($proxy['scheme']) && $proxy['scheme'] == 'https') {
1592 $proxy_host = 'ssl://' . $proxy_host;
1594 $proxy_port = isset($proxy['port']) ? $proxy['port'] : 8080;
1595 $proxy_user = isset($proxy['user']) ? urldecode($proxy['user']) : null;
1596 $proxy_pass = isset($proxy['pass']) ? urldecode($proxy['pass']) : null;
1599 call_user_func($callback, 'message', "Using HTTP proxy $host:$port");
1604 $port = (isset($info['scheme']) && $info['scheme'] == 'https') ? 443 : 80;
1607 $scheme = (isset($info['scheme']) && $info['scheme'] == 'https') ? 'https' : 'http';
1609 if ($proxy_host != '') {
1610 $fp = @fsockopen($proxy_host, $proxy_port, $errno, $errstr);
1613 call_user_func($callback, 'connfailed', array($proxy_host, $proxy_port,
1616 return PEAR::raiseError("Connection to `$proxy_host:$proxy_port' failed: $errstr", $errno);
1619 if ($lastmodified === false || $lastmodified) {
1620 $request = "GET $url HTTP/1.1\r\n";
1621 $request .= "Host: $host\r\n";
1623 $request = "GET $url HTTP/1.0\r\n";
1624 $request .= "Host: $host\r\n";
1627 $network_host = $host;
1628 if (isset($info['scheme']) && $info['scheme'] == 'https') {
1629 $network_host = 'ssl://' . $host;
1632 $fp = @fsockopen($network_host, $port, $errno, $errstr);
1635 call_user_func($callback, 'connfailed', array($host, $port,
1638 return PEAR::raiseError("Connection to `$host:$port' failed: $errstr", $errno);
1641 if ($lastmodified === false || $lastmodified) {
1642 $request = "GET $path HTTP/1.1\r\n";
1643 $request .= "Host: $host\r\n";
1645 $request = "GET $path HTTP/1.0\r\n";
1646 $request .= "Host: $host\r\n";
1650 $ifmodifiedsince = '';
1651 if (is_array($lastmodified)) {
1652 if (isset($lastmodified['Last-Modified'])) {
1653 $ifmodifiedsince = 'If-Modified-Since: ' . $lastmodified['Last-Modified'] . "\r\n";
1656 if (isset($lastmodified['ETag'])) {
1657 $ifmodifiedsince .= "If-None-Match: $lastmodified[ETag]\r\n";
1660 $ifmodifiedsince = ($lastmodified ? "If-Modified-Since: $lastmodified\r\n" : '');
1663 $request .= $ifmodifiedsince .
1664 "User-Agent: PEAR/1.10.1/PHP/" . PHP_VERSION . "\r\n";
1666 if ($object !== null) { // only pass in authentication for non-static calls
1667 $username = $config->get('username', null, $channel);
1668 $password = $config->get('password', null, $channel);
1669 if ($username && $password) {
1670 $tmp = base64_encode("$username:$password");
1671 $request .= "Authorization: Basic $tmp\r\n";
1675 if ($proxy_host != '' && $proxy_user != '') {
1676 $request .= 'Proxy-Authorization: Basic ' .
1677 base64_encode($proxy_user . ':' . $proxy_pass) . "\r\n";
1681 $request .= 'Accept: ' . implode(', ', $accept) . "\r\n";
1684 $request .= "Connection: close\r\n";
1686 fwrite($fp, $request);
1689 while (trim($line = fgets($fp, 1024))) {
1690 if (preg_match('/^([^:]+):\s+(.*)\s*\\z/', $line, $matches)) {
1691 $headers[strtolower($matches[1])] = trim($matches[2]);
1692 } elseif (preg_match('|^HTTP/1.[01] ([0-9]{3}) |', $line, $matches)) {
1693 $reply = (int)$matches[1];
1694 if ($reply == 304 && ($lastmodified || ($lastmodified === false))) {
1698 if (!in_array($reply, array(200, 301, 302, 303, 305, 307))) {
1699 return PEAR::raiseError("File $scheme://$host:$port$path not valid (received: $line)");
1704 if ($reply != 200) {
1705 if (!isset($headers['location'])) {
1706 return PEAR::raiseError("File $scheme://$host:$port$path not valid (redirected but no location)");
1709 if ($wasredirect > 4) {
1710 return PEAR::raiseError("File $scheme://$host:$port$path not valid (redirection looped more than 5 times)");
1713 $redirect = $wasredirect + 1;
1714 return static::_downloadHttp($object, $headers['location'],
1715 $ui, $save_dir, $callback, $lastmodified, $accept);
1718 if (isset($headers['content-disposition']) &&
1719 preg_match('/\sfilename=\"([^;]*\S)\"\s*(;|\\z)/', $headers['content-disposition'], $matches)) {
1720 $save_as = basename($matches[1]);
1722 $save_as = basename($url);
1726 $tmp = call_user_func($callback, 'saveas', $save_as);
1732 $dest_file = $save_dir . DIRECTORY_SEPARATOR . $save_as;
1733 if (is_link($dest_file)) {
1734 return PEAR::raiseError('SECURITY ERROR: Will not write to ' . $dest_file . ' as it is symlinked to ' . readlink($dest_file) . ' - Possible symlink attack');
1737 if (!$wp = @fopen($dest_file, 'wb')) {
1740 call_user_func($callback, 'writefailed', array($dest_file, $php_errormsg));
1742 return PEAR::raiseError("could not open $dest_file for writing");
1745 $length = isset($headers['content-length']) ? $headers['content-length'] : -1;
1749 call_user_func($callback, 'start', array(basename($dest_file), $length));
1752 while ($data = fread($fp, 1024)) {
1753 $bytes += strlen($data);
1755 call_user_func($callback, 'bytesread', $bytes);
1757 if (!@fwrite($wp, $data)) {
1760 call_user_func($callback, 'writefailed', array($dest_file, $php_errormsg));
1762 return PEAR::raiseError("$dest_file: write failed ($php_errormsg)");
1769 call_user_func($callback, 'done', $bytes);
1772 if ($lastmodified === false || $lastmodified) {
1773 if (isset($headers['etag'])) {
1774 $lastmodified = array('ETag' => $headers['etag']);
1777 if (isset($headers['last-modified'])) {
1778 if (is_array($lastmodified)) {
1779 $lastmodified['Last-Modified'] = $headers['last-modified'];
1781 $lastmodified = $headers['last-modified'];
1784 return array($dest_file, $lastmodified, $headers);