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';
23 require_once 'PEAR/Proxy.php';
25 define('PEAR_INSTALLER_OK', 1);
26 define('PEAR_INSTALLER_FAILED', 0);
27 define('PEAR_INSTALLER_SKIPPED', -1);
28 define('PEAR_INSTALLER_ERROR_NO_PREF_STATE', 2);
31 * Administration class used to download anything from the internet (PEAR Packages,
32 * static URLs, xml files)
36 * @author Greg Beaver <cellog@php.net>
37 * @author Stig Bakken <ssb@php.net>
38 * @author Tomas V. V. Cox <cox@idecnet.com>
39 * @author Martin Jansen <mj@php.net>
40 * @copyright 1997-2009 The Authors
41 * @license http://opensource.org/licenses/bsd-license.php New BSD License
42 * @version Release: 1.10.5
43 * @link http://pear.php.net/package/PEAR
44 * @since Class available since Release 1.3.0
46 class PEAR_Downloader extends PEAR_Common
55 * Preferred Installation State (snapshot, devel, alpha, beta, stable)
62 * Options from command-line passed to Install.
64 * Recognized options:<br />
65 * - onlyreqdeps : install all required dependencies as well
66 * - alldeps : install all dependencies, including optional
67 * - installroot : base relative path to install files in
68 * - force : force a download even if warnings would prevent it
69 * - nocompress : download uncompressed tarballs
70 * @see PEAR_Command_Install
77 * Downloaded Packages after a call to download().
79 * Format of each entry:
82 * array('pkg' => 'package_name', 'file' => '/path/to/local/file',
83 * 'info' => array() // parsed package.xml
89 var $_downloadedPackages = array();
92 * Packages slated for download.
94 * This is used to prevent downloading a package more than once should it be a dependency
95 * for two packages to be installed.
96 * Format of each entry:
99 * array('package_name1' => parsed package.xml, 'package_name2' => parsed package.xml,
105 var $_toDownload = array();
108 * Array of every package installed, with names lower-cased.
112 * array('package1' => 0, 'package2' => 1, );
116 var $_installed = array();
122 var $_errorStack = array();
128 var $_internalDownload = false;
131 * Temporary variable used in sorting packages by dependency in {@link sortPkgDeps()}
135 var $_packageSortTree;
138 * Temporary directory, or configuration value where downloads will occur
144 * List of methods that can be called both statically and non-statically.
147 protected static $bivalentMethods = array(
148 'setErrorHandling' => true,
149 'raiseError' => true,
150 'throwError' => true,
151 'pushErrorHandling' => true,
152 'popErrorHandling' => true,
153 'downloadHttp' => true,
157 * @param PEAR_Frontend_*
161 function __construct($ui = null, $options = array(), $config = null)
163 parent::__construct();
164 $this->_options = $options;
165 if ($config !== null) {
166 $this->config = &$config;
167 $this->_preferredState = $this->config->get('preferred_state');
170 if (!$this->_preferredState) {
171 // don't inadvertently use a non-set preferred_state
172 $this->_preferredState = null;
175 if ($config !== null) {
176 if (isset($this->_options['installroot'])) {
177 $this->config->setInstallRoot($this->_options['installroot']);
179 $this->_registry = &$config->getRegistry();
182 if (isset($this->_options['alldeps']) || isset($this->_options['onlyreqdeps'])) {
183 $this->_installed = $this->_registry->listAllPackages();
184 foreach ($this->_installed as $key => $unused) {
185 if (!count($unused)) {
188 $strtolower = create_function('$a','return strtolower($a);');
189 array_walk($this->_installed[$key], $strtolower);
195 * Attempt to discover a channel's remote capabilities from
200 function discover($channel)
202 $this->log(1, 'Attempting to discover channel "' . $channel . '"...');
203 PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
204 $callback = $this->ui ? array(&$this, '_downloadCallback') : null;
205 if (!class_exists('System')) {
206 require_once 'System.php';
209 $tmpdir = $this->config->get('temp_dir');
210 $tmp = System::mktemp('-d -t "' . $tmpdir . '"');
211 $a = $this->downloadHttp('http://' . $channel . '/channel.xml', $this->ui, $tmp, $callback, false);
212 PEAR::popErrorHandling();
213 if (PEAR::isError($a)) {
214 // Attempt to fallback to https automatically.
215 PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
216 $this->log(1, 'Attempting fallback to https instead of http on channel "' . $channel . '"...');
217 $a = $this->downloadHttp('https://' . $channel . '/channel.xml', $this->ui, $tmp, $callback, false);
218 PEAR::popErrorHandling();
219 if (PEAR::isError($a)) {
224 list($a, $lastmodified) = $a;
225 if (!class_exists('PEAR_ChannelFile')) {
226 require_once 'PEAR/ChannelFile.php';
229 $b = new PEAR_ChannelFile;
230 if ($b->fromXmlFile($a)) {
232 if ($this->config->get('auto_discover')) {
233 $this->_registry->addChannel($b, $lastmodified);
234 $alias = $b->getName();
235 if ($b->getName() == $this->_registry->channelName($b->getAlias())) {
236 $alias = $b->getAlias();
239 $this->log(1, 'Auto-discovered channel "' . $channel .
240 '", alias "' . $alias . '", adding to registry');
251 * For simpler unit-testing
252 * @param PEAR_Downloader
253 * @return PEAR_Downloader_Package
255 function newDownloaderPackage(&$t)
257 if (!class_exists('PEAR_Downloader_Package')) {
258 require_once 'PEAR/Downloader/Package.php';
260 $a = new PEAR_Downloader_Package($t);
265 * For simpler unit-testing
271 function &getDependency2Object(&$c, $i, $p, $s)
273 if (!class_exists('PEAR_Dependency2')) {
274 require_once 'PEAR/Dependency2.php';
276 $z = new PEAR_Dependency2($c, $i, $p, $s);
280 function &download($params)
282 if (!count($params)) {
287 if (!isset($this->_registry)) {
288 $this->_registry = &$this->config->getRegistry();
291 $channelschecked = array();
292 // convert all parameters into PEAR_Downloader_Package objects
293 foreach ($params as $i => $param) {
294 $params[$i] = $this->newDownloaderPackage($this);
295 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
296 $err = $params[$i]->initialize($param);
297 PEAR::staticPopErrorHandling();
299 // skip parameters that were missed by preferred_state
303 if (PEAR::isError($err)) {
304 if (!isset($this->_options['soft']) && $err->getMessage() !== '') {
305 $this->log(0, $err->getMessage());
309 if (is_object($param)) {
310 $param = $param->getChannel() . '/' . $param->getPackage();
313 if (!isset($this->_options['soft'])) {
314 $this->log(2, 'Package "' . $param . '" is not valid');
317 // Message logged above in a specific verbose mode, passing null to not show up on CLI
318 $this->pushError(null, PEAR_INSTALLER_SKIPPED);
321 if ($params[$i] && $params[$i]->getType() == 'local') {
322 // bug #7090 skip channel.xml check for local packages
326 if ($params[$i] && !isset($channelschecked[$params[$i]->getChannel()]) &&
327 !isset($this->_options['offline'])
329 $channelschecked[$params[$i]->getChannel()] = true;
330 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
331 if (!class_exists('System')) {
332 require_once 'System.php';
335 $curchannel = $this->_registry->getChannel($params[$i]->getChannel());
336 if (PEAR::isError($curchannel)) {
337 PEAR::staticPopErrorHandling();
338 return $this->raiseError($curchannel);
341 if (PEAR::isError($dir = $this->getDownloadDir())) {
342 PEAR::staticPopErrorHandling();
346 $mirror = $this->config->get('preferred_mirror', null, $params[$i]->getChannel());
347 $url = 'http://' . $mirror . '/channel.xml';
348 $a = $this->downloadHttp($url, $this->ui, $dir, null, $curchannel->lastModified());
350 PEAR::staticPopErrorHandling();
352 //channel.xml not modified
354 } else if (PEAR::isError($a)) {
355 // Attempt fallback to https automatically
356 PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
357 $a = $this->downloadHttp('https://' . $mirror .
358 '/channel.xml', $this->ui, $dir, null, $curchannel->lastModified());
360 PEAR::staticPopErrorHandling();
361 if (PEAR::isError($a) || !$a) {
365 $this->log(0, 'WARNING: channel "' . $params[$i]->getChannel() . '" has ' .
366 'updated its protocols, use "' . PEAR_RUNTYPE . ' channel-update ' . $params[$i]->getChannel() .
371 if ($params[$i] && !isset($this->_options['downloadonly'])) {
372 if (isset($this->_options['packagingroot'])) {
373 $checkdir = $this->_prependPath(
374 $this->config->get('php_dir', null, $params[$i]->getChannel()),
375 $this->_options['packagingroot']);
377 $checkdir = $this->config->get('php_dir',
378 null, $params[$i]->getChannel());
381 while ($checkdir && $checkdir != '/' && !file_exists($checkdir)) {
382 $checkdir = dirname($checkdir);
385 if ($checkdir == '.') {
389 if (!is_writeable($checkdir)) {
390 return PEAR::raiseError('Cannot install, php_dir for channel "' .
391 $params[$i]->getChannel() . '" is not writeable by the current user');
397 unset($channelschecked);
398 PEAR_Downloader_Package::removeDuplicates($params);
399 if (!count($params)) {
404 if (!isset($this->_options['nodeps']) && !isset($this->_options['offline'])) {
408 foreach ($params as $i => $param) {
409 //PHP Bug 40768 / PEAR Bug #10944
410 //Nested foreaches fail in PHP 5.2.1
412 $ret = $params[$i]->detectDependencies($params);
413 if (PEAR::isError($ret)) {
416 PEAR_Downloader_Package::removeDuplicates($params);
417 if (!isset($this->_options['soft'])) {
418 $this->log(0, $ret->getMessage());
426 if (isset($this->_options['offline'])) {
427 $this->log(3, 'Skipping dependency download check, --offline specified');
430 if (!count($params)) {
435 while (PEAR_Downloader_Package::mergeDependencies($params));
436 PEAR_Downloader_Package::removeDuplicates($params, true);
437 $errorparams = array();
438 if (PEAR_Downloader_Package::detectStupidDuplicates($params, $errorparams)) {
439 if (count($errorparams)) {
440 foreach ($errorparams as $param) {
441 $name = $this->_registry->parsedPackageNameToString($param->getParsedPackage());
442 $this->pushError('Duplicate package ' . $name . ' found', PEAR_INSTALLER_FAILED);
449 PEAR_Downloader_Package::removeInstalled($params);
450 if (!count($params)) {
451 $this->pushError('No valid packages found', PEAR_INSTALLER_FAILED);
456 PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
457 $err = $this->analyzeDependencies($params);
458 PEAR::popErrorHandling();
459 if (!count($params)) {
460 $this->pushError('No valid packages found', PEAR_INSTALLER_FAILED);
466 $newparams = array();
467 if (isset($this->_options['pretend'])) {
472 foreach ($params as $i => $package) {
473 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
474 $pf = &$params[$i]->download();
475 PEAR::staticPopErrorHandling();
476 if (PEAR::isError($pf)) {
477 if (!isset($this->_options['soft'])) {
478 $this->log(1, $pf->getMessage());
479 $this->log(0, 'Error: cannot download "' .
480 $this->_registry->parsedPackageNameToString($package->getParsedPackage(),
488 $newparams[] = &$params[$i];
490 'file' => $pf->getArchiveFile(),
492 'pkg' => $pf->getPackage()
497 // remove params that did not download successfully
498 PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
499 $err = $this->analyzeDependencies($newparams, true);
500 PEAR::popErrorHandling();
501 if (!count($newparams)) {
502 $this->pushError('Download failed', PEAR_INSTALLER_FAILED);
508 $this->_downloadedPackages = $ret;
513 * @param array all packages to be installed
515 function analyzeDependencies(&$params, $force = false)
517 if (isset($this->_options['downloadonly'])) {
521 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
523 $reset = $hasfailed = $failed = false;
526 foreach ($params as $i => $param) {
527 $deps = $param->getDeps();
529 $depchecker = &$this->getDependency2Object($this->config, $this->getOptions(),
530 $param->getParsedPackage(), PEAR_VALIDATE_DOWNLOADING);
531 $send = $param->getPackageFile();
533 $installcheck = $depchecker->validatePackage($send, $this, $params);
534 if (PEAR::isError($installcheck)) {
535 if (!isset($this->_options['soft'])) {
536 $this->log(0, $installcheck->getMessage());
543 PEAR_Downloader_Package::removeDuplicates($params);
549 if (!$reset && $param->alreadyValidated() && !$force) {
554 $depchecker = &$this->getDependency2Object($this->config, $this->getOptions(),
555 $param->getParsedPackage(), PEAR_VALIDATE_DOWNLOADING);
556 $send = $param->getPackageFile();
557 if ($send === null) {
558 $send = $param->getDownloadURL();
561 $installcheck = $depchecker->validatePackage($send, $this, $params);
562 if (PEAR::isError($installcheck)) {
563 if (!isset($this->_options['soft'])) {
564 $this->log(0, $installcheck->getMessage());
571 PEAR_Downloader_Package::removeDuplicates($params);
576 if (isset($deps['required']) && is_array($deps['required'])) {
577 foreach ($deps['required'] as $type => $dep) {
578 // note: Dependency2 will never return a PEAR_Error if ignore-errors
579 // is specified, so soft is needed to turn off logging
580 if (!isset($dep[0])) {
581 if (PEAR::isError($e = $depchecker->{"validate{$type}Dependency"}($dep,
584 if (!isset($this->_options['soft'])) {
585 $this->log(0, $e->getMessage());
587 } elseif (is_array($e) && !$param->alreadyValidated()) {
588 if (!isset($this->_options['soft'])) {
589 $this->log(0, $e[0]);
593 foreach ($dep as $d) {
594 if (PEAR::isError($e =
595 $depchecker->{"validate{$type}Dependency"}($d,
598 if (!isset($this->_options['soft'])) {
599 $this->log(0, $e->getMessage());
601 } elseif (is_array($e) && !$param->alreadyValidated()) {
602 if (!isset($this->_options['soft'])) {
603 $this->log(0, $e[0]);
610 if (isset($deps['optional']) && is_array($deps['optional'])) {
611 foreach ($deps['optional'] as $type => $dep) {
612 if (!isset($dep[0])) {
613 if (PEAR::isError($e =
614 $depchecker->{"validate{$type}Dependency"}($dep,
617 if (!isset($this->_options['soft'])) {
618 $this->log(0, $e->getMessage());
620 } elseif (is_array($e) && !$param->alreadyValidated()) {
621 if (!isset($this->_options['soft'])) {
622 $this->log(0, $e[0]);
626 foreach ($dep as $d) {
627 if (PEAR::isError($e =
628 $depchecker->{"validate{$type}Dependency"}($d,
631 if (!isset($this->_options['soft'])) {
632 $this->log(0, $e->getMessage());
634 } elseif (is_array($e) && !$param->alreadyValidated()) {
635 if (!isset($this->_options['soft'])) {
636 $this->log(0, $e[0]);
644 $groupname = $param->getGroup();
645 if (isset($deps['group']) && $groupname) {
646 if (!isset($deps['group'][0])) {
647 $deps['group'] = array($deps['group']);
651 foreach ($deps['group'] as $group) {
652 if ($group['attribs']['name'] == $groupname) {
659 unset($group['attribs']);
660 foreach ($group as $type => $dep) {
661 if (!isset($dep[0])) {
662 if (PEAR::isError($e =
663 $depchecker->{"validate{$type}Dependency"}($dep,
666 if (!isset($this->_options['soft'])) {
667 $this->log(0, $e->getMessage());
669 } elseif (is_array($e) && !$param->alreadyValidated()) {
670 if (!isset($this->_options['soft'])) {
671 $this->log(0, $e[0]);
675 foreach ($dep as $d) {
676 if (PEAR::isError($e =
677 $depchecker->{"validate{$type}Dependency"}($d,
680 if (!isset($this->_options['soft'])) {
681 $this->log(0, $e->getMessage());
683 } elseif (is_array($e) && !$param->alreadyValidated()) {
684 if (!isset($this->_options['soft'])) {
685 $this->log(0, $e[0]);
694 foreach ($deps as $dep) {
695 if (PEAR::isError($e = $depchecker->validateDependency1($dep, $params))) {
697 if (!isset($this->_options['soft'])) {
698 $this->log(0, $e->getMessage());
700 } elseif (is_array($e) && !$param->alreadyValidated()) {
701 if (!isset($this->_options['soft'])) {
702 $this->log(0, $e[0]);
707 $params[$i]->setValidated();
716 PEAR_Downloader_Package::removeDuplicates($params);
722 PEAR::staticPopErrorHandling();
723 if ($hasfailed && (isset($this->_options['ignore-errors']) ||
724 isset($this->_options['nodeps']))) {
725 // this is probably not needed, but just in case
726 if (!isset($this->_options['soft'])) {
727 $this->log(0, 'WARNING: dependencies failed');
733 * Retrieve the directory that downloads will happen in
737 function getDownloadDir()
739 if (isset($this->_downloadDir)) {
740 return $this->_downloadDir;
743 $downloaddir = $this->config->get('download_dir');
744 if (empty($downloaddir) || (is_dir($downloaddir) && !is_writable($downloaddir))) {
745 if (is_dir($downloaddir) && !is_writable($downloaddir)) {
746 $this->log(0, 'WARNING: configuration download directory "' . $downloaddir .
747 '" is not writeable. Change download_dir config variable to ' .
748 'a writeable dir to avoid this warning');
751 if (!class_exists('System')) {
752 require_once 'System.php';
755 if (PEAR::isError($downloaddir = System::mktemp('-d'))) {
758 $this->log(3, '+ tmp dir created at ' . $downloaddir);
761 if (!is_writable($downloaddir)) {
762 if (PEAR::isError(System::mkdir(array('-p', $downloaddir))) ||
763 !is_writable($downloaddir)) {
764 return PEAR::raiseError('download directory "' . $downloaddir .
765 '" is not writeable. Change download_dir config variable to ' .
770 return $this->_downloadDir = $downloaddir;
773 function setDownloadDir($dir)
775 if (!@is_writable($dir)) {
776 if (PEAR::isError(System::mkdir(array('-p', $dir)))) {
777 return PEAR::raiseError('download directory "' . $dir .
778 '" is not writeable. Change download_dir config variable to ' .
782 $this->_downloadDir = $dir;
785 function configSet($key, $value, $layer = 'user', $channel = false)
787 $this->config->set($key, $value, $layer, $channel);
788 $this->_preferredState = $this->config->get('preferred_state', null, $channel);
789 if (!$this->_preferredState) {
790 // don't inadvertently use a non-set preferred_state
791 $this->_preferredState = null;
795 function setOptions($options)
797 $this->_options = $options;
800 function getOptions()
802 return $this->_options;
807 * @param array output of {@link parsePackageName()}
810 function _getPackageDownloadUrl($parr)
812 $curchannel = $this->config->get('default_channel');
813 $this->configSet('default_channel', $parr['channel']);
814 // getDownloadURL returns an array. On error, it only contains information
815 // on the latest release as array(version, info). On success it contains
816 // array(version, info, download url string)
817 $state = isset($parr['state']) ? $parr['state'] : $this->config->get('preferred_state');
818 if (!$this->_registry->channelExists($parr['channel'])) {
820 if ($this->config->get('auto_discover') && $this->discover($parr['channel'])) {
824 $this->configSet('default_channel', $curchannel);
825 return PEAR::raiseError('Unknown remote channel: ' . $parr['channel']);
829 $chan = $this->_registry->getChannel($parr['channel']);
830 if (PEAR::isError($chan)) {
834 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
835 $version = $this->_registry->packageInfo($parr['package'], 'version', $parr['channel']);
836 $stability = $this->_registry->packageInfo($parr['package'], 'stability', $parr['channel']);
837 // package is installed - use the installed release stability level
838 if (!isset($parr['state']) && $stability !== null) {
839 $state = $stability['release'];
841 PEAR::staticPopErrorHandling();
844 $preferred_mirror = $this->config->get('preferred_mirror');
845 if (!$chan->supportsREST($preferred_mirror) ||
847 !($base2 = $chan->getBaseURL('REST1.3', $preferred_mirror))
849 !($base = $chan->getBaseURL('REST1.0', $preferred_mirror))
852 return $this->raiseError($parr['channel'] . ' is using a unsupported protocol - This should never happen.');
856 $rest = &$this->config->getREST('1.3', $this->_options);
859 $rest = &$this->config->getREST('1.0', $this->_options);
862 $downloadVersion = false;
863 if (!isset($parr['version']) && !isset($parr['state']) && $version
864 && !PEAR::isError($version)
865 && !isset($this->_options['downloadonly'])
867 $downloadVersion = $version;
870 $url = $rest->getDownloadURL($base, $parr, $state, $downloadVersion, $chan->getName());
871 if (PEAR::isError($url)) {
872 $this->configSet('default_channel', $curchannel);
876 if ($parr['channel'] != $curchannel) {
877 $this->configSet('default_channel', $curchannel);
880 if (!is_array($url)) {
884 $url['raw'] = false; // no checking is necessary for REST
885 if (!is_array($url['info'])) {
886 return PEAR::raiseError('Invalid remote dependencies retrieved from REST - ' .
887 'this should never happen');
890 if (!isset($this->_options['force']) &&
891 !isset($this->_options['downloadonly']) &&
893 !PEAR::isError($version) &&
894 !isset($parr['group'])
896 if (version_compare($version, $url['version'], '=')) {
897 return PEAR::raiseError($this->_registry->parsedPackageNameToString(
898 $parr, true) . ' is already installed and is the same as the ' .
899 'released version ' . $url['version'], -976);
902 if (version_compare($version, $url['version'], '>')) {
903 return PEAR::raiseError($this->_registry->parsedPackageNameToString(
904 $parr, true) . ' is already installed and is newer than detected ' .
905 'released version ' . $url['version'], -976);
909 if (isset($url['info']['required']) || $url['compatible']) {
910 require_once 'PEAR/PackageFile/v2.php';
911 $pf = new PEAR_PackageFile_v2;
912 $pf->setRawChannel($parr['channel']);
913 if ($url['compatible']) {
914 $pf->setRawCompatible($url['compatible']);
917 require_once 'PEAR/PackageFile/v1.php';
918 $pf = new PEAR_PackageFile_v1;
921 $pf->setRawPackage($url['package']);
922 $pf->setDeps($url['info']);
923 if ($url['compatible']) {
924 $pf->setCompatible($url['compatible']);
927 $pf->setRawState($url['stability']);
929 if (!extension_loaded("zlib") || isset($this->_options['nocompress'])) {
935 if (is_array($url) && isset($url['url'])) {
943 * @param array dependency array
946 function _getDepPackageDownloadUrl($dep, $parr)
948 $xsdversion = isset($dep['rel']) ? '1.0' : '2.0';
949 $curchannel = $this->config->get('default_channel');
950 if (isset($dep['uri'])) {
952 $chan = $this->_registry->getChannel('__uri');
953 if (PEAR::isError($chan)) {
957 $version = $this->_registry->packageInfo($dep['name'], 'version', '__uri');
958 $this->configSet('default_channel', '__uri');
960 if (isset($dep['channel'])) {
961 $remotechannel = $dep['channel'];
963 $remotechannel = 'pear.php.net';
966 if (!$this->_registry->channelExists($remotechannel)) {
968 if ($this->config->get('auto_discover')) {
969 if ($this->discover($remotechannel)) {
973 return PEAR::raiseError('Unknown remote channel: ' . $remotechannel);
977 $chan = $this->_registry->getChannel($remotechannel);
978 if (PEAR::isError($chan)) {
982 $version = $this->_registry->packageInfo($dep['name'], 'version', $remotechannel);
983 $this->configSet('default_channel', $remotechannel);
986 $state = isset($parr['state']) ? $parr['state'] : $this->config->get('preferred_state');
987 if (isset($parr['state']) && isset($parr['version'])) {
988 unset($parr['state']);
991 if (isset($dep['uri'])) {
992 $info = $this->newDownloaderPackage($this);
993 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
994 $err = $info->initialize($dep);
995 PEAR::staticPopErrorHandling();
997 // skip parameters that were missed by preferred_state
998 return PEAR::raiseError('Cannot initialize dependency');
1001 if (PEAR::isError($err)) {
1002 if (!isset($this->_options['soft'])) {
1003 $this->log(0, $err->getMessage());
1006 if (is_object($info)) {
1007 $param = $info->getChannel() . '/' . $info->getPackage();
1009 return PEAR::raiseError('Package "' . $param . '" is not valid');
1012 } elseif ($chan->supportsREST($this->config->get('preferred_mirror'))
1015 ($base2 = $chan->getBaseURL('REST1.3', $this->config->get('preferred_mirror')))
1017 ($base = $chan->getBaseURL('REST1.0', $this->config->get('preferred_mirror')))
1022 $rest = &$this->config->getREST('1.3', $this->_options);
1024 $rest = &$this->config->getREST('1.0', $this->_options);
1027 $url = $rest->getDepDownloadURL($base, $xsdversion, $dep, $parr,
1028 $state, $version, $chan->getName());
1029 if (PEAR::isError($url)) {
1033 if ($parr['channel'] != $curchannel) {
1034 $this->configSet('default_channel', $curchannel);
1037 if (!is_array($url)) {
1041 $url['raw'] = false; // no checking is necessary for REST
1042 if (!is_array($url['info'])) {
1043 return PEAR::raiseError('Invalid remote dependencies retrieved from REST - ' .
1044 'this should never happen');
1047 if (isset($url['info']['required'])) {
1048 if (!class_exists('PEAR_PackageFile_v2')) {
1049 require_once 'PEAR/PackageFile/v2.php';
1051 $pf = new PEAR_PackageFile_v2;
1052 $pf->setRawChannel($remotechannel);
1054 if (!class_exists('PEAR_PackageFile_v1')) {
1055 require_once 'PEAR/PackageFile/v1.php';
1057 $pf = new PEAR_PackageFile_v1;
1060 $pf->setRawPackage($url['package']);
1061 $pf->setDeps($url['info']);
1062 if ($url['compatible']) {
1063 $pf->setCompatible($url['compatible']);
1066 $pf->setRawState($url['stability']);
1067 $url['info'] = &$pf;
1068 if (!extension_loaded("zlib") || isset($this->_options['nocompress'])) {
1074 if (is_array($url) && isset($url['url'])) {
1075 $url['url'] .= $ext;
1081 return $this->raiseError($parr['channel'] . ' is using a unsupported protocol - This should never happen.');
1085 * @deprecated in favor of _getPackageDownloadUrl
1087 function getPackageDownloadUrl($package, $version = null, $channel = false)
1090 $package .= "-$version";
1092 if ($this === null || $this->_registry === null) {
1093 $package = "http://pear.php.net/get/$package";
1095 $chan = $this->_registry->getChannel($channel);
1096 if (PEAR::isError($chan)) {
1099 $package = "http://" . $chan->getServer() . "/get/$package";
1101 if (!extension_loaded("zlib")) {
1102 $package .= '?uncompress=yes';
1108 * Retrieve a list of downloaded packages after a call to {@link download()}.
1110 * Also resets the list of downloaded packages.
1113 function getDownloadedPackages()
1115 $ret = $this->_downloadedPackages;
1116 $this->_downloadedPackages = array();
1117 $this->_toDownload = array();
1121 function _downloadCallback($msg, $params = null)
1125 $this->log(1, "downloading $params ...");
1128 $this->log(1, '...done: ' . number_format($params, 0, '', ',') . ' bytes');
1132 if (empty($bytes)) {
1135 if (!($bytes % 10240)) {
1136 $this->log(1, '.', false);
1141 if($params[1] == -1) {
1142 $length = "Unknown size";
1144 $length = number_format($params[1], 0, '', ',')." bytes";
1146 $this->log(1, "Starting to download {$params[0]} ($length)");
1149 if (method_exists($this->ui, '_downloadCallback'))
1150 $this->ui->_downloadCallback($msg, $params);
1153 function _prependPath($path, $prepend)
1155 if (strlen($prepend) > 0) {
1156 if (OS_WINDOWS && preg_match('/^[a-z]:/i', $path)) {
1157 if (preg_match('/^[a-z]:/i', $prepend)) {
1158 $prepend = substr($prepend, 2);
1159 } elseif ($prepend{0} != '\\') {
1160 $prepend = "\\$prepend";
1162 $path = substr($path, 0, 2) . $prepend . substr($path, 2);
1164 $path = $prepend . $path;
1174 function pushError($errmsg, $code = -1)
1176 array_push($this->_errorStack, array($errmsg, $code));
1179 function getErrorMsgs()
1182 $errs = $this->_errorStack;
1183 foreach ($errs as $err) {
1186 $this->_errorStack = array();
1195 function sortPkgDeps(&$packages, $uninstall = false)
1198 $this->sortPackagesForUninstall($packages) :
1199 $this->sortPackagesForInstall($packages);
1203 * Sort a list of arrays of array(downloaded packagefilename) by dependency.
1205 * This uses the topological sort method from graph theory, and the
1206 * Structures_Graph package to properly sort dependencies for installation.
1207 * @param array an array of downloaded PEAR_Downloader_Packages
1208 * @return array array of array(packagefilename, package.xml contents)
1210 function sortPackagesForInstall(&$packages)
1212 require_once 'Structures/Graph.php';
1213 require_once 'Structures/Graph/Node.php';
1214 require_once 'Structures/Graph/Manipulator/TopologicalSorter.php';
1215 $depgraph = new Structures_Graph(true);
1217 $reg = &$this->config->getRegistry();
1218 foreach ($packages as $i => $package) {
1219 $pname = $reg->parsedPackageNameToString(
1221 'channel' => $package->getChannel(),
1222 'package' => strtolower($package->getPackage()),
1224 $nodes[$pname] = new Structures_Graph_Node;
1225 $nodes[$pname]->setData($packages[$i]);
1226 $depgraph->addNode($nodes[$pname]);
1229 $deplinks = array();
1230 foreach ($nodes as $package => $node) {
1231 $pf = &$node->getData();
1232 $pdeps = $pf->getDeps(true);
1237 if ($pf->getPackagexmlVersion() == '1.0') {
1238 foreach ($pdeps as $dep) {
1239 if ($dep['type'] != 'pkg' ||
1240 (isset($dep['optional']) && $dep['optional'] == 'yes')) {
1244 $dname = $reg->parsedPackageNameToString(
1246 'channel' => 'pear.php.net',
1247 'package' => strtolower($dep['name']),
1250 if (isset($nodes[$dname])) {
1251 if (!isset($deplinks[$dname])) {
1252 $deplinks[$dname] = array();
1255 $deplinks[$dname][$package] = 1;
1256 // dependency is in installed packages
1260 $dname = $reg->parsedPackageNameToString(
1262 'channel' => 'pecl.php.net',
1263 'package' => strtolower($dep['name']),
1266 if (isset($nodes[$dname])) {
1267 if (!isset($deplinks[$dname])) {
1268 $deplinks[$dname] = array();
1271 $deplinks[$dname][$package] = 1;
1272 // dependency is in installed packages
1277 // the only ordering we care about is:
1278 // 1) subpackages must be installed before packages that depend on them
1279 // 2) required deps must be installed before packages that depend on them
1280 if (isset($pdeps['required']['subpackage'])) {
1281 $t = $pdeps['required']['subpackage'];
1282 if (!isset($t[0])) {
1286 $this->_setupGraph($t, $reg, $deplinks, $nodes, $package);
1289 if (isset($pdeps['group'])) {
1290 if (!isset($pdeps['group'][0])) {
1291 $pdeps['group'] = array($pdeps['group']);
1294 foreach ($pdeps['group'] as $group) {
1295 if (isset($group['subpackage'])) {
1296 $t = $group['subpackage'];
1297 if (!isset($t[0])) {
1301 $this->_setupGraph($t, $reg, $deplinks, $nodes, $package);
1306 if (isset($pdeps['optional']['subpackage'])) {
1307 $t = $pdeps['optional']['subpackage'];
1308 if (!isset($t[0])) {
1312 $this->_setupGraph($t, $reg, $deplinks, $nodes, $package);
1315 if (isset($pdeps['required']['package'])) {
1316 $t = $pdeps['required']['package'];
1317 if (!isset($t[0])) {
1321 $this->_setupGraph($t, $reg, $deplinks, $nodes, $package);
1324 if (isset($pdeps['group'])) {
1325 if (!isset($pdeps['group'][0])) {
1326 $pdeps['group'] = array($pdeps['group']);
1329 foreach ($pdeps['group'] as $group) {
1330 if (isset($group['package'])) {
1331 $t = $group['package'];
1332 if (!isset($t[0])) {
1336 $this->_setupGraph($t, $reg, $deplinks, $nodes, $package);
1343 $this->_detectDepCycle($deplinks);
1344 foreach ($deplinks as $dependent => $parents) {
1345 foreach ($parents as $parent => $unused) {
1346 $nodes[$dependent]->connectTo($nodes[$parent]);
1350 $installOrder = Structures_Graph_Manipulator_TopologicalSorter::sort($depgraph);
1352 for ($i = 0, $count = count($installOrder); $i < $count; $i++) {
1353 foreach ($installOrder[$i] as $index => $sortedpackage) {
1354 $data = &$installOrder[$i][$index]->getData();
1355 $ret[] = &$nodes[$reg->parsedPackageNameToString(
1357 'channel' => $data->getChannel(),
1358 'package' => strtolower($data->getPackage()),
1368 * Detect recursive links between dependencies and break the cycles
1373 function _detectDepCycle(&$deplinks)
1377 foreach ($deplinks as $dep => $parents) {
1378 foreach ($parents as $parent => $unused) {
1379 // reset the parent cycle detector
1380 $this->_testCycle(null, null, null);
1381 if ($this->_testCycle($dep, $deplinks, $parent)) {
1383 unset($deplinks[$dep][$parent]);
1384 if (count($deplinks[$dep]) == 0) {
1385 unset($deplinks[$dep]);
1392 } while ($keepgoing);
1395 function _testCycle($test, $deplinks, $dep)
1397 static $visited = array();
1398 if ($test === null) {
1403 // this happens when a parent has a dep cycle on another dependency
1404 // but the child is not part of the cycle
1405 if (isset($visited[$dep])) {
1410 if ($test == $dep) {
1414 if (isset($deplinks[$dep])) {
1415 if (in_array($test, array_keys($deplinks[$dep]), true)) {
1419 foreach ($deplinks[$dep] as $parent => $unused) {
1420 if ($this->_testCycle($test, $deplinks, $parent)) {
1430 * Set up the dependency for installation parsing
1432 * @param array $t dependency information
1433 * @param PEAR_Registry $reg
1434 * @param array $deplinks list of dependency links already established
1435 * @param array $nodes all existing package nodes
1436 * @param string $package parent package name
1439 function _setupGraph($t, $reg, &$deplinks, &$nodes, $package)
1441 foreach ($t as $dep) {
1442 $depchannel = !isset($dep['channel']) ? '__uri': $dep['channel'];
1443 $dname = $reg->parsedPackageNameToString(
1445 'channel' => $depchannel,
1446 'package' => strtolower($dep['name']),
1449 if (isset($nodes[$dname])) {
1450 if (!isset($deplinks[$dname])) {
1451 $deplinks[$dname] = array();
1453 $deplinks[$dname][$package] = 1;
1458 function _dependsOn($a, $b)
1460 return $this->_checkDepTree(strtolower($a->getChannel()), strtolower($a->getPackage()), $b);
1463 function _checkDepTree($channel, $package, $b, $checked = array())
1465 $checked[$channel][$package] = true;
1466 if (!isset($this->_depTree[$channel][$package])) {
1470 if (isset($this->_depTree[$channel][$package][strtolower($b->getChannel())]
1471 [strtolower($b->getPackage())])) {
1475 foreach ($this->_depTree[$channel][$package] as $ch => $packages) {
1476 foreach ($packages as $pa => $true) {
1477 if ($this->_checkDepTree($ch, $pa, $b, $checked)) {
1486 function _sortInstall($a, $b)
1488 if (!$a->getDeps() && !$b->getDeps()) {
1489 return 0; // neither package has dependencies, order is insignificant
1491 if ($a->getDeps() && !$b->getDeps()) {
1492 return 1; // $a must be installed after $b because $a has dependencies
1494 if (!$a->getDeps() && $b->getDeps()) {
1495 return -1; // $b must be installed after $a because $b has dependencies
1497 // both packages have dependencies
1498 if ($this->_dependsOn($a, $b)) {
1501 if ($this->_dependsOn($b, $a)) {
1508 * Download a file through HTTP. Considers suggested file name in
1509 * Content-disposition: header and can run a callback function for
1510 * different events. The callback will be called with two
1511 * parameters: the callback type, and parameters. The implemented
1512 * callback types are:
1514 * 'setup' called at the very beginning, parameter is a UI object
1515 * that should be used for all output
1516 * 'message' the parameter is a string with an informational message
1517 * 'saveas' may be used to save with a different file name, the
1518 * parameter is the filename that is about to be used.
1519 * If a 'saveas' callback returns a non-empty string,
1520 * that file name will be used as the filename instead.
1521 * Note that $save_dir will not be affected by this, only
1522 * the basename of the file.
1523 * 'start' download is starting, parameter is number of bytes
1524 * that are expected, or -1 if unknown
1525 * 'bytesread' parameter is the number of bytes read so far
1526 * 'done' download is complete, parameter is the total number
1528 * 'connfailed' if the TCP/SSL connection fails, this callback is called
1529 * with array(host,port,errno,errmsg)
1530 * 'writefailed' if writing to disk fails, this callback is called
1531 * with array(destfile,errmsg)
1533 * If an HTTP proxy has been configured (http_proxy PEAR_Config
1534 * setting), the proxy will be used.
1536 * @param string $url the URL to download
1537 * @param object $ui PEAR_Frontend_* instance
1538 * @param object $config PEAR_Config instance
1539 * @param string $save_dir directory to save file in
1540 * @param mixed $callback function/method to call for status
1542 * @param false|string|array $lastmodified header values to check against for caching
1543 * use false to return the header values from this download
1544 * @param false|array $accept Accept headers to send
1545 * @param false|string $channel Channel to use for retrieving authentication
1546 * @return mixed Returns the full path of the downloaded file or a PEAR
1547 * error on failure. If the error is caused by
1548 * socket-related errors, the error object will
1549 * have the fsockopen error code available through
1550 * getCode(). If caching is requested, then return the header
1552 * If $lastmodified was given and the there are no changes,
1553 * boolean false is returned.
1557 public static function _downloadHttp(
1558 $object, $url, &$ui, $save_dir = '.', $callback = null, $lastmodified = null,
1559 $accept = false, $channel = false
1561 static $redirect = 0;
1562 // always reset , so we are clean case of error
1563 $wasredirect = $redirect;
1566 call_user_func($callback, 'setup', array(&$ui));
1569 $info = parse_url($url);
1570 if (!isset($info['scheme']) || !in_array($info['scheme'], array('http', 'https'))) {
1571 return PEAR::raiseError('Cannot download non-http URL "' . $url . '"');
1574 if (!isset($info['host'])) {
1575 return PEAR::raiseError('Cannot download from non-URL "' . $url . '"');
1578 $host = isset($info['host']) ? $info['host'] : null;
1579 $port = isset($info['port']) ? $info['port'] : null;
1580 $path = isset($info['path']) ? $info['path'] : null;
1582 if ($object !== null) {
1583 $config = $object->config;
1585 $config = &PEAR_Config::singleton();
1588 $proxy = new PEAR_Proxy($config);
1590 if ($proxy->isProxyConfigured() && $callback) {
1591 call_user_func($callback, 'message', "Using HTTP proxy $host:$port");
1595 $port = (isset($info['scheme']) && $info['scheme'] == 'https') ? 443 : 80;
1598 $scheme = (isset($info['scheme']) && $info['scheme'] == 'https') ? 'https' : 'http';
1599 $secure = ($scheme == 'https');
1601 $fp = $proxy->openSocket($host, $port, $secure);
1602 if (PEAR::isError($fp)) {
1604 $errno = $fp->getCode();
1605 $errstr = $fp->getMessage();
1606 call_user_func($callback, 'connfailed', array($host, $port,
1612 $requestPath = $path;
1613 if ($proxy->isProxyConfigured()) {
1614 $requestPath = $url;
1617 if ($lastmodified === false || $lastmodified) {
1618 $request = "GET $requestPath HTTP/1.1\r\n";
1620 $request = "GET $requestPath HTTP/1.0\r\n";
1622 $request .= "Host: $host\r\n";
1624 $ifmodifiedsince = '';
1625 if (is_array($lastmodified)) {
1626 if (isset($lastmodified['Last-Modified'])) {
1627 $ifmodifiedsince = 'If-Modified-Since: ' . $lastmodified['Last-Modified'] . "\r\n";
1630 if (isset($lastmodified['ETag'])) {
1631 $ifmodifiedsince .= "If-None-Match: $lastmodified[ETag]\r\n";
1634 $ifmodifiedsince = ($lastmodified ? "If-Modified-Since: $lastmodified\r\n" : '');
1637 $request .= $ifmodifiedsince .
1638 "User-Agent: PEAR/1.10.5/PHP/" . PHP_VERSION . "\r\n";
1640 if ($object !== null) { // only pass in authentication for non-static calls
1641 $username = $config->get('username', null, $channel);
1642 $password = $config->get('password', null, $channel);
1643 if ($username && $password) {
1644 $tmp = base64_encode("$username:$password");
1645 $request .= "Authorization: Basic $tmp\r\n";
1649 $proxyAuth = $proxy->getProxyAuth();
1651 $request .= 'Proxy-Authorization: Basic ' .
1652 $proxyAuth . "\r\n";
1656 $request .= 'Accept: ' . implode(', ', $accept) . "\r\n";
1659 $request .= "Connection: close\r\n";
1661 fwrite($fp, $request);
1664 while (trim($line = fgets($fp, 1024))) {
1665 if (preg_match('/^([^:]+):\s+(.*)\s*\\z/', $line, $matches)) {
1666 $headers[strtolower($matches[1])] = trim($matches[2]);
1667 } elseif (preg_match('|^HTTP/1.[01] ([0-9]{3}) |', $line, $matches)) {
1668 $reply = (int)$matches[1];
1669 if ($reply == 304 && ($lastmodified || ($lastmodified === false))) {
1673 if (!in_array($reply, array(200, 301, 302, 303, 305, 307))) {
1674 return PEAR::raiseError("File $scheme://$host:$port$path not valid (received: $line)");
1679 if ($reply != 200) {
1680 if (!isset($headers['location'])) {
1681 return PEAR::raiseError("File $scheme://$host:$port$path not valid (redirected but no location)");
1684 if ($wasredirect > 4) {
1685 return PEAR::raiseError("File $scheme://$host:$port$path not valid (redirection looped more than 5 times)");
1688 $redirect = $wasredirect + 1;
1689 return static::_downloadHttp($object, $headers['location'],
1690 $ui, $save_dir, $callback, $lastmodified, $accept);
1693 if (isset($headers['content-disposition']) &&
1694 preg_match('/\sfilename=\"([^;]*\S)\"\s*(;|\\z)/', $headers['content-disposition'], $matches)) {
1695 $save_as = basename($matches[1]);
1697 $save_as = basename($url);
1701 $tmp = call_user_func($callback, 'saveas', $save_as);
1707 $dest_file = $save_dir . DIRECTORY_SEPARATOR . $save_as;
1708 if (is_link($dest_file)) {
1709 return PEAR::raiseError('SECURITY ERROR: Will not write to ' . $dest_file . ' as it is symlinked to ' . readlink($dest_file) . ' - Possible symlink attack');
1712 if (!$wp = @fopen($dest_file, 'wb')) {
1715 call_user_func($callback, 'writefailed', array($dest_file, $php_errormsg));
1717 return PEAR::raiseError("could not open $dest_file for writing");
1720 $length = isset($headers['content-length']) ? $headers['content-length'] : -1;
1724 call_user_func($callback, 'start', array(basename($dest_file), $length));
1727 while ($data = fread($fp, 1024)) {
1728 $bytes += strlen($data);
1730 call_user_func($callback, 'bytesread', $bytes);
1732 if (!@fwrite($wp, $data)) {
1735 call_user_func($callback, 'writefailed', array($dest_file, $php_errormsg));
1737 return PEAR::raiseError("$dest_file: write failed ($php_errormsg)");
1744 call_user_func($callback, 'done', $bytes);
1747 if ($lastmodified === false || $lastmodified) {
1748 if (isset($headers['etag'])) {
1749 $lastmodified = array('ETag' => $headers['etag']);
1752 if (isset($headers['last-modified'])) {
1753 if (is_array($lastmodified)) {
1754 $lastmodified['Last-Modified'] = $headers['last-modified'];
1756 $lastmodified = $headers['last-modified'];
1759 return array($dest_file, $lastmodified, $headers);