Subversion Repositories Applications.gtt

Rev

Rev 94 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
94 jpm 1
<?php
2
/**
3
 * PEAR_Downloader, the PEAR Installer's download utility class
4
 *
5
 * PHP versions 4 and 5
6
 *
7
 * @category   pear
8
 * @package    PEAR
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>
187 mathias 13
 * @copyright  1997-2009 The Authors
14
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
94 jpm 15
 * @link       http://pear.php.net/package/PEAR
16
 * @since      File available since Release 1.3.0
17
 */
18
 
19
/**
20
 * Needed for constants, extending
21
 */
22
require_once 'PEAR/Common.php';
23
 
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);
28
 
29
/**
30
 * Administration class used to download anything from the internet (PEAR Packages,
31
 * static URLs, xml files)
32
 *
33
 * @category   pear
34
 * @package    PEAR
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>
187 mathias 39
 * @copyright  1997-2009 The Authors
40
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
41
 * @version    Release: 1.10.1
94 jpm 42
 * @link       http://pear.php.net/package/PEAR
43
 * @since      Class available since Release 1.3.0
44
 */
45
class PEAR_Downloader extends PEAR_Common
46
{
47
    /**
48
     * @var PEAR_Registry
49
     * @access private
50
     */
51
    var $_registry;
52
 
53
    /**
54
     * Preferred Installation State (snapshot, devel, alpha, beta, stable)
55
     * @var string|null
56
     * @access private
57
     */
58
    var $_preferredState;
59
 
60
    /**
61
     * Options from command-line passed to Install.
62
     *
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
70
     * @access private
71
     * @var array
72
     */
73
    var $_options;
74
 
75
    /**
76
     * Downloaded Packages after a call to download().
77
     *
78
     * Format of each entry:
79
     *
80
     * <code>
81
     * array('pkg' => 'package_name', 'file' => '/path/to/local/file',
82
     *    'info' => array() // parsed package.xml
83
     * );
84
     * </code>
85
     * @access private
86
     * @var array
87
     */
88
    var $_downloadedPackages = array();
89
 
90
    /**
91
     * Packages slated for download.
92
     *
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:
96
     *
97
     * <pre>
98
     * array('package_name1' => parsed package.xml, 'package_name2' => parsed package.xml,
99
     * );
100
     * </pre>
101
     * @access private
102
     * @var array
103
     */
104
    var $_toDownload = array();
105
 
106
    /**
107
     * Array of every package installed, with names lower-cased.
108
     *
109
     * Format:
110
     * <code>
111
     * array('package1' => 0, 'package2' => 1, );
112
     * </code>
113
     * @var array
114
     */
115
    var $_installed = array();
116
 
117
    /**
118
     * @var array
119
     * @access private
120
     */
121
    var $_errorStack = array();
187 mathias 122
 
94 jpm 123
    /**
124
     * @var boolean
125
     * @access private
126
     */
127
    var $_internalDownload = false;
128
 
129
    /**
130
     * Temporary variable used in sorting packages by dependency in {@link sortPkgDeps()}
131
     * @var array
132
     * @access private
133
     */
134
    var $_packageSortTree;
135
 
136
    /**
137
     * Temporary directory, or configuration value where downloads will occur
138
     * @var string
139
     */
140
    var $_downloadDir;
141
 
142
    /**
187 mathias 143
     * List of methods that can be called both statically and non-statically.
144
     * @var array
145
     */
146
    protected static $bivalentMethods = array(
147
        'setErrorHandling' => true,
148
        'raiseError' => true,
149
        'throwError' => true,
150
        'pushErrorHandling' => true,
151
        'popErrorHandling' => true,
152
        'downloadHttp' => true,
153
    );
154
 
155
    /**
94 jpm 156
     * @param PEAR_Frontend_*
157
     * @param array
158
     * @param PEAR_Config
159
     */
187 mathias 160
    function __construct($ui = null, $options = array(), $config = null)
94 jpm 161
    {
187 mathias 162
        parent::__construct();
94 jpm 163
        $this->_options = $options;
187 mathias 164
        if ($config !== null) {
165
            $this->config = &$config;
166
            $this->_preferredState = $this->config->get('preferred_state');
167
        }
94 jpm 168
        $this->ui = &$ui;
169
        if (!$this->_preferredState) {
170
            // don't inadvertantly use a non-set preferred_state
171
            $this->_preferredState = null;
172
        }
173
 
187 mathias 174
        if ($config !== null) {
175
            if (isset($this->_options['installroot'])) {
176
                $this->config->setInstallRoot($this->_options['installroot']);
177
            }
178
            $this->_registry = &$config->getRegistry();
94 jpm 179
        }
180
 
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)) {
185
                    continue;
186
                }
187
                $strtolower = create_function('$a','return strtolower($a);');
188
                array_walk($this->_installed[$key], $strtolower);
189
            }
190
        }
191
    }
192
 
193
    /**
194
     * Attempt to discover a channel's remote capabilities from
195
     * its server name
196
     * @param string
197
     * @return boolean
198
     */
199
    function discover($channel)
200
    {
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';
206
        }
187 mathias 207
 
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);
94 jpm 211
        PEAR::popErrorHandling();
212
        if (PEAR::isError($a)) {
187 mathias 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)) {
219
                return false;
220
            }
94 jpm 221
        }
187 mathias 222
 
94 jpm 223
        list($a, $lastmodified) = $a;
187 mathias 224
        if (!class_exists('PEAR_ChannelFile')) {
94 jpm 225
            require_once 'PEAR/ChannelFile.php';
226
        }
187 mathias 227
 
94 jpm 228
        $b = new PEAR_ChannelFile;
229
        if ($b->fromXmlFile($a)) {
230
            unlink($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();
236
                }
187 mathias 237
 
94 jpm 238
                $this->log(1, 'Auto-discovered channel "' . $channel .
239
                    '", alias "' . $alias . '", adding to registry');
240
            }
187 mathias 241
 
94 jpm 242
            return true;
243
        }
187 mathias 244
 
94 jpm 245
        unlink($a);
246
        return false;
247
    }
248
 
249
    /**
250
     * For simpler unit-testing
251
     * @param PEAR_Downloader
252
     * @return PEAR_Downloader_Package
253
     */
187 mathias 254
    function newDownloaderPackage(&$t)
94 jpm 255
    {
256
        if (!class_exists('PEAR_Downloader_Package')) {
257
            require_once 'PEAR/Downloader/Package.php';
258
        }
187 mathias 259
        $a = new PEAR_Downloader_Package($t);
94 jpm 260
        return $a;
261
    }
262
 
263
    /**
264
     * For simpler unit-testing
265
     * @param PEAR_Config
266
     * @param array
267
     * @param array
268
     * @param int
269
     */
270
    function &getDependency2Object(&$c, $i, $p, $s)
271
    {
187 mathias 272
        if (!class_exists('PEAR_Dependency2')) {
94 jpm 273
            require_once 'PEAR/Dependency2.php';
274
        }
187 mathias 275
        $z = new PEAR_Dependency2($c, $i, $p, $s);
94 jpm 276
        return $z;
277
    }
278
 
279
    function &download($params)
280
    {
281
        if (!count($params)) {
282
            $a = array();
283
            return $a;
284
        }
187 mathias 285
 
94 jpm 286
        if (!isset($this->_registry)) {
287
            $this->_registry = &$this->config->getRegistry();
288
        }
187 mathias 289
 
94 jpm 290
        $channelschecked = array();
291
        // convert all parameters into PEAR_Downloader_Package objects
292
        foreach ($params as $i => $param) {
187 mathias 293
            $params[$i] = $this->newDownloaderPackage($this);
94 jpm 294
            PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
295
            $err = $params[$i]->initialize($param);
296
            PEAR::staticPopErrorHandling();
297
            if (!$err) {
298
                // skip parameters that were missed by preferred_state
299
                continue;
300
            }
187 mathias 301
 
94 jpm 302
            if (PEAR::isError($err)) {
187 mathias 303
                if (!isset($this->_options['soft']) && $err->getMessage() !== '') {
94 jpm 304
                    $this->log(0, $err->getMessage());
305
                }
187 mathias 306
 
94 jpm 307
                $params[$i] = false;
308
                if (is_object($param)) {
309
                    $param = $param->getChannel() . '/' . $param->getPackage();
310
                }
187 mathias 311
 
312
                if (!isset($this->_options['soft'])) {
313
                    $this->log(2, 'Package "' . $param . '" is not valid');
314
                }
315
 
316
                // Message logged above in a specific verbose mode, passing null to not show up on CLI
317
                $this->pushError(null, PEAR_INSTALLER_SKIPPED);
94 jpm 318
            } else {
319
                do {
320
                    if ($params[$i] && $params[$i]->getType() == 'local') {
187 mathias 321
                        // bug #7090 skip channel.xml check for local packages
94 jpm 322
                        break;
323
                    }
187 mathias 324
 
94 jpm 325
                    if ($params[$i] && !isset($channelschecked[$params[$i]->getChannel()]) &&
187 mathias 326
                          !isset($this->_options['offline'])
327
                    ) {
94 jpm 328
                        $channelschecked[$params[$i]->getChannel()] = true;
329
                        PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
330
                        if (!class_exists('System')) {
331
                            require_once 'System.php';
332
                        }
187 mathias 333
 
334
                        $curchannel = $this->_registry->getChannel($params[$i]->getChannel());
94 jpm 335
                        if (PEAR::isError($curchannel)) {
336
                            PEAR::staticPopErrorHandling();
337
                            return $this->raiseError($curchannel);
338
                        }
187 mathias 339
 
94 jpm 340
                        if (PEAR::isError($dir = $this->getDownloadDir())) {
341
                            PEAR::staticPopErrorHandling();
342
                            break;
343
                        }
344
 
187 mathias 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());
348
 
94 jpm 349
                        PEAR::staticPopErrorHandling();
187 mathias 350
                        if ($a === false) {
351
                            //channel.xml not modified
94 jpm 352
                            break;
187 mathias 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());
358
 
359
                            PEAR::staticPopErrorHandling();
360
                            if (PEAR::isError($a) || !$a) {
361
                                break;
362
                            }
94 jpm 363
                        }
364
                        $this->log(0, 'WARNING: channel "' . $params[$i]->getChannel() . '" has ' .
187 mathias 365
                            'updated its protocols, use "' . PEAR_RUNTYPE . ' channel-update ' . $params[$i]->getChannel() .
94 jpm 366
                            '" to update');
367
                    }
368
                } while (false);
187 mathias 369
 
94 jpm 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']);
375
                    } else {
376
                        $checkdir = $this->config->get('php_dir',
377
                            null, $params[$i]->getChannel());
378
                    }
187 mathias 379
 
94 jpm 380
                    while ($checkdir && $checkdir != '/' && !file_exists($checkdir)) {
381
                        $checkdir = dirname($checkdir);
382
                    }
187 mathias 383
 
94 jpm 384
                    if ($checkdir == '.') {
385
                        $checkdir = '/';
386
                    }
187 mathias 387
 
94 jpm 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');
391
                    }
392
                }
393
            }
394
        }
187 mathias 395
 
94 jpm 396
        unset($channelschecked);
397
        PEAR_Downloader_Package::removeDuplicates($params);
398
        if (!count($params)) {
399
            $a = array();
400
            return $a;
401
        }
187 mathias 402
 
94 jpm 403
        if (!isset($this->_options['nodeps']) && !isset($this->_options['offline'])) {
404
            $reverify = true;
405
            while ($reverify) {
406
                $reverify = false;
407
                foreach ($params as $i => $param) {
187 mathias 408
                    //PHP Bug 40768 / PEAR Bug #10944
409
                    //Nested foreaches fail in PHP 5.2.1
410
                    key($params);
94 jpm 411
                    $ret = $params[$i]->detectDependencies($params);
412
                    if (PEAR::isError($ret)) {
413
                        $reverify = true;
414
                        $params[$i] = false;
415
                        PEAR_Downloader_Package::removeDuplicates($params);
416
                        if (!isset($this->_options['soft'])) {
417
                            $this->log(0, $ret->getMessage());
418
                        }
419
                        continue 2;
420
                    }
421
                }
422
            }
423
        }
187 mathias 424
 
94 jpm 425
        if (isset($this->_options['offline'])) {
426
            $this->log(3, 'Skipping dependency download check, --offline specified');
427
        }
187 mathias 428
 
94 jpm 429
        if (!count($params)) {
430
            $a = array();
431
            return $a;
432
        }
187 mathias 433
 
94 jpm 434
        while (PEAR_Downloader_Package::mergeDependencies($params));
435
        PEAR_Downloader_Package::removeDuplicates($params, true);
187 mathias 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);
442
                }
443
                $a = array();
444
                return $a;
445
            }
446
        }
447
 
94 jpm 448
        PEAR_Downloader_Package::removeInstalled($params);
449
        if (!count($params)) {
450
            $this->pushError('No valid packages found', PEAR_INSTALLER_FAILED);
451
            $a = array();
452
            return $a;
453
        }
187 mathias 454
 
94 jpm 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);
460
            $a = array();
461
            return $a;
462
        }
187 mathias 463
 
94 jpm 464
        $ret = array();
465
        $newparams = array();
466
        if (isset($this->_options['pretend'])) {
467
            return $params;
468
        }
187 mathias 469
 
470
        $somefailed = false;
94 jpm 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(),
480
                            true) .
481
                        '"');
482
                }
187 mathias 483
                $somefailed = true;
94 jpm 484
                continue;
485
            }
187 mathias 486
 
94 jpm 487
            $newparams[] = &$params[$i];
187 mathias 488
            $ret[] = array(
489
                'file' => $pf->getArchiveFile(),
490
                'info' => &$pf,
491
                'pkg'  => $pf->getPackage()
492
            );
94 jpm 493
        }
187 mathias 494
 
495
        if ($somefailed) {
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);
502
                $a = array();
503
                return $a;
504
            }
505
        }
506
 
94 jpm 507
        $this->_downloadedPackages = $ret;
508
        return $newparams;
509
    }
510
 
511
    /**
512
     * @param array all packages to be installed
513
     */
187 mathias 514
    function analyzeDependencies(&$params, $force = false)
94 jpm 515
    {
516
        if (isset($this->_options['downloadonly'])) {
517
            return;
518
        }
187 mathias 519
 
94 jpm 520
        PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
187 mathias 521
        $redo  = true;
522
        $reset = $hasfailed = $failed = false;
94 jpm 523
        while ($redo) {
524
            $redo = false;
525
            foreach ($params as $i => $param) {
526
                $deps = $param->getDeps();
527
                if (!$deps) {
528
                    $depchecker = &$this->getDependency2Object($this->config, $this->getOptions(),
529
                        $param->getParsedPackage(), PEAR_VALIDATE_DOWNLOADING);
187 mathias 530
                    $send = $param->getPackageFile();
531
 
94 jpm 532
                    $installcheck = $depchecker->validatePackage($send, $this, $params);
533
                    if (PEAR::isError($installcheck)) {
534
                        if (!isset($this->_options['soft'])) {
535
                            $this->log(0, $installcheck->getMessage());
536
                        }
187 mathias 537
                        $hasfailed  = true;
94 jpm 538
                        $params[$i] = false;
187 mathias 539
                        $reset      = true;
540
                        $redo       = true;
541
                        $failed     = false;
94 jpm 542
                        PEAR_Downloader_Package::removeDuplicates($params);
543
                        continue 2;
544
                    }
545
                    continue;
546
                }
187 mathias 547
 
548
                if (!$reset && $param->alreadyValidated() && !$force) {
94 jpm 549
                    continue;
550
                }
187 mathias 551
 
94 jpm 552
                if (count($deps)) {
553
                    $depchecker = &$this->getDependency2Object($this->config, $this->getOptions(),
554
                        $param->getParsedPackage(), PEAR_VALIDATE_DOWNLOADING);
187 mathias 555
                    $send = $param->getPackageFile();
556
                    if ($send === null) {
94 jpm 557
                        $send = $param->getDownloadURL();
558
                    }
187 mathias 559
 
94 jpm 560
                    $installcheck = $depchecker->validatePackage($send, $this, $params);
561
                    if (PEAR::isError($installcheck)) {
562
                        if (!isset($this->_options['soft'])) {
563
                            $this->log(0, $installcheck->getMessage());
564
                        }
187 mathias 565
                        $hasfailed  = true;
94 jpm 566
                        $params[$i] = false;
187 mathias 567
                        $reset      = true;
568
                        $redo       = true;
569
                        $failed     = false;
94 jpm 570
                        PEAR_Downloader_Package::removeDuplicates($params);
571
                        continue 2;
572
                    }
187 mathias 573
 
94 jpm 574
                    $failed = false;
187 mathias 575
                    if (isset($deps['required']) && is_array($deps['required'])) {
94 jpm 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,
581
                                      true, $params))) {
582
                                    $failed = true;
583
                                    if (!isset($this->_options['soft'])) {
584
                                        $this->log(0, $e->getMessage());
585
                                    }
586
                                } elseif (is_array($e) && !$param->alreadyValidated()) {
587
                                    if (!isset($this->_options['soft'])) {
588
                                        $this->log(0, $e[0]);
589
                                    }
590
                                }
591
                            } else {
592
                                foreach ($dep as $d) {
593
                                    if (PEAR::isError($e =
594
                                          $depchecker->{"validate{$type}Dependency"}($d,
595
                                          true, $params))) {
596
                                        $failed = true;
597
                                        if (!isset($this->_options['soft'])) {
598
                                            $this->log(0, $e->getMessage());
599
                                        }
600
                                    } elseif (is_array($e) && !$param->alreadyValidated()) {
601
                                        if (!isset($this->_options['soft'])) {
602
                                            $this->log(0, $e[0]);
603
                                        }
604
                                    }
605
                                }
606
                            }
607
                        }
187 mathias 608
 
609
                        if (isset($deps['optional']) && is_array($deps['optional'])) {
94 jpm 610
                            foreach ($deps['optional'] as $type => $dep) {
611
                                if (!isset($dep[0])) {
612
                                    if (PEAR::isError($e =
613
                                          $depchecker->{"validate{$type}Dependency"}($dep,
614
                                          false, $params))) {
615
                                        $failed = true;
616
                                        if (!isset($this->_options['soft'])) {
617
                                            $this->log(0, $e->getMessage());
618
                                        }
619
                                    } elseif (is_array($e) && !$param->alreadyValidated()) {
620
                                        if (!isset($this->_options['soft'])) {
621
                                            $this->log(0, $e[0]);
622
                                        }
623
                                    }
624
                                } else {
625
                                    foreach ($dep as $d) {
626
                                        if (PEAR::isError($e =
627
                                              $depchecker->{"validate{$type}Dependency"}($d,
628
                                              false, $params))) {
629
                                            $failed = true;
630
                                            if (!isset($this->_options['soft'])) {
631
                                                $this->log(0, $e->getMessage());
632
                                            }
633
                                        } elseif (is_array($e) && !$param->alreadyValidated()) {
634
                                            if (!isset($this->_options['soft'])) {
635
                                                $this->log(0, $e[0]);
636
                                            }
637
                                        }
638
                                    }
639
                                }
640
                            }
641
                        }
187 mathias 642
 
94 jpm 643
                        $groupname = $param->getGroup();
644
                        if (isset($deps['group']) && $groupname) {
645
                            if (!isset($deps['group'][0])) {
646
                                $deps['group'] = array($deps['group']);
647
                            }
187 mathias 648
 
94 jpm 649
                            $found = false;
650
                            foreach ($deps['group'] as $group) {
651
                                if ($group['attribs']['name'] == $groupname) {
652
                                    $found = true;
653
                                    break;
654
                                }
655
                            }
187 mathias 656
 
94 jpm 657
                            if ($found) {
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,
663
                                              false, $params))) {
664
                                            $failed = true;
665
                                            if (!isset($this->_options['soft'])) {
666
                                                $this->log(0, $e->getMessage());
667
                                            }
668
                                        } elseif (is_array($e) && !$param->alreadyValidated()) {
669
                                            if (!isset($this->_options['soft'])) {
670
                                                $this->log(0, $e[0]);
671
                                            }
672
                                        }
673
                                    } else {
674
                                        foreach ($dep as $d) {
675
                                            if (PEAR::isError($e =
676
                                                  $depchecker->{"validate{$type}Dependency"}($d,
677
                                                  false, $params))) {
678
                                                $failed = true;
679
                                                if (!isset($this->_options['soft'])) {
680
                                                    $this->log(0, $e->getMessage());
681
                                                }
682
                                            } elseif (is_array($e) && !$param->alreadyValidated()) {
683
                                                if (!isset($this->_options['soft'])) {
684
                                                    $this->log(0, $e[0]);
685
                                                }
686
                                            }
687
                                        }
688
                                    }
689
                                }
690
                            }
691
                        }
692
                    } else {
693
                        foreach ($deps as $dep) {
694
                            if (PEAR::isError($e = $depchecker->validateDependency1($dep, $params))) {
695
                                $failed = true;
696
                                if (!isset($this->_options['soft'])) {
697
                                    $this->log(0, $e->getMessage());
698
                                }
699
                            } elseif (is_array($e) && !$param->alreadyValidated()) {
700
                                if (!isset($this->_options['soft'])) {
701
                                    $this->log(0, $e[0]);
702
                                }
703
                            }
704
                        }
705
                    }
706
                    $params[$i]->setValidated();
707
                }
187 mathias 708
 
94 jpm 709
                if ($failed) {
187 mathias 710
                    $hasfailed  = true;
94 jpm 711
                    $params[$i] = false;
187 mathias 712
                    $reset      = true;
713
                    $redo       = true;
714
                    $failed     = false;
94 jpm 715
                    PEAR_Downloader_Package::removeDuplicates($params);
716
                    continue 2;
717
                }
718
            }
719
        }
187 mathias 720
 
94 jpm 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');
727
            }
728
        }
729
    }
730
 
731
    /**
732
     * Retrieve the directory that downloads will happen in
733
     * @access private
734
     * @return string
735
     */
736
    function getDownloadDir()
737
    {
738
        if (isset($this->_downloadDir)) {
739
            return $this->_downloadDir;
740
        }
187 mathias 741
 
94 jpm 742
        $downloaddir = $this->config->get('download_dir');
187 mathias 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');
748
            }
749
 
94 jpm 750
            if (!class_exists('System')) {
751
                require_once 'System.php';
752
            }
187 mathias 753
 
94 jpm 754
            if (PEAR::isError($downloaddir = System::mktemp('-d'))) {
755
                return $downloaddir;
756
            }
757
            $this->log(3, '+ tmp dir created at ' . $downloaddir);
758
        }
187 mathias 759
 
94 jpm 760
        if (!is_writable($downloaddir)) {
187 mathias 761
            if (PEAR::isError(System::mkdir(array('-p', $downloaddir))) ||
762
                  !is_writable($downloaddir)) {
94 jpm 763
                return PEAR::raiseError('download directory "' . $downloaddir .
764
                    '" is not writeable.  Change download_dir config variable to ' .
765
                    'a writeable dir');
766
            }
767
        }
187 mathias 768
 
94 jpm 769
        return $this->_downloadDir = $downloaddir;
770
    }
771
 
772
    function setDownloadDir($dir)
773
    {
187 mathias 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 ' .
778
                    'a writeable dir');
779
            }
780
        }
94 jpm 781
        $this->_downloadDir = $dir;
782
    }
783
 
784
    function configSet($key, $value, $layer = 'user', $channel = false)
785
    {
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;
791
        }
792
    }
793
 
794
    function setOptions($options)
795
    {
796
        $this->_options = $options;
797
    }
798
 
799
    function getOptions()
800
    {
801
        return $this->_options;
802
    }
803
 
804
 
805
    /**
806
     * @param array output of {@link parsePackageName()}
807
     * @access private
808
     */
809
    function _getPackageDownloadUrl($parr)
810
    {
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'])) {
818
            do {
187 mathias 819
                if ($this->config->get('auto_discover') && $this->discover($parr['channel'])) {
820
                    break;
94 jpm 821
                }
187 mathias 822
 
94 jpm 823
                $this->configSet('default_channel', $curchannel);
187 mathias 824
                return PEAR::raiseError('Unknown remote channel: ' . $parr['channel']);
94 jpm 825
            } while (false);
826
        }
187 mathias 827
 
828
        $chan = $this->_registry->getChannel($parr['channel']);
94 jpm 829
        if (PEAR::isError($chan)) {
830
            return $chan;
831
        }
187 mathias 832
 
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'];
839
        }
840
        PEAR::staticPopErrorHandling();
841
        $base2 = false;
842
 
843
        $preferred_mirror = $this->config->get('preferred_mirror');
844
        if (!$chan->supportsREST($preferred_mirror) ||
845
              (
846
               !($base2 = $chan->getBaseURL('REST1.3', $preferred_mirror))
847
               &&
848
               !($base = $chan->getBaseURL('REST1.0', $preferred_mirror))
849
              )
850
        ) {
851
            return $this->raiseError($parr['channel'] . ' is using a unsupported protocol - This should never happen.');
852
        }
853
 
854
        if ($base2) {
855
            $rest = &$this->config->getREST('1.3', $this->_options);
856
            $base = $base2;
857
        } else {
94 jpm 858
            $rest = &$this->config->getREST('1.0', $this->_options);
859
        }
187 mathias 860
 
861
        $downloadVersion = false;
862
        if (!isset($parr['version']) && !isset($parr['state']) && $version
863
              && !PEAR::isError($version)
864
              && !isset($this->_options['downloadonly'])
865
        ) {
866
            $downloadVersion = $version;
867
        }
868
 
869
        $url = $rest->getDownloadURL($base, $parr, $state, $downloadVersion, $chan->getName());
94 jpm 870
        if (PEAR::isError($url)) {
187 mathias 871
            $this->configSet('default_channel', $curchannel);
94 jpm 872
            return $url;
873
        }
187 mathias 874
 
94 jpm 875
        if ($parr['channel'] != $curchannel) {
876
            $this->configSet('default_channel', $curchannel);
877
        }
187 mathias 878
 
94 jpm 879
        if (!is_array($url)) {
880
            return $url;
881
        }
187 mathias 882
 
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');
887
        }
888
 
889
        if (!isset($this->_options['force']) &&
890
              !isset($this->_options['downloadonly']) &&
891
              $version &&
892
              !PEAR::isError($version) &&
893
              !isset($parr['group'])
894
        ) {
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);
94 jpm 899
            }
187 mathias 900
 
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);
905
            }
94 jpm 906
        }
187 mathias 907
 
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']);
94 jpm 914
            }
187 mathias 915
        } else {
916
            require_once 'PEAR/PackageFile/v1.php';
917
            $pf = new PEAR_PackageFile_v1;
94 jpm 918
        }
187 mathias 919
 
920
        $pf->setRawPackage($url['package']);
921
        $pf->setDeps($url['info']);
922
        if ($url['compatible']) {
923
            $pf->setCompatible($url['compatible']);
924
        }
925
 
926
        $pf->setRawState($url['stability']);
927
        $url['info'] = &$pf;
94 jpm 928
        if (!extension_loaded("zlib") || isset($this->_options['nocompress'])) {
929
            $ext = '.tar';
930
        } else {
931
            $ext = '.tgz';
932
        }
187 mathias 933
 
934
        if (is_array($url) && isset($url['url'])) {
935
            $url['url'] .= $ext;
94 jpm 936
        }
187 mathias 937
 
94 jpm 938
        return $url;
939
    }
940
 
941
    /**
942
     * @param array dependency array
943
     * @access private
944
     */
945
    function _getDepPackageDownloadUrl($dep, $parr)
946
    {
947
        $xsdversion = isset($dep['rel']) ? '1.0' : '2.0';
948
        $curchannel = $this->config->get('default_channel');
949
        if (isset($dep['uri'])) {
950
            $xsdversion = '2.0';
187 mathias 951
            $chan = $this->_registry->getChannel('__uri');
94 jpm 952
            if (PEAR::isError($chan)) {
953
                return $chan;
954
            }
187 mathias 955
 
94 jpm 956
            $version = $this->_registry->packageInfo($dep['name'], 'version', '__uri');
957
            $this->configSet('default_channel', '__uri');
958
        } else {
959
            if (isset($dep['channel'])) {
960
                $remotechannel = $dep['channel'];
961
            } else {
962
                $remotechannel = 'pear.php.net';
963
            }
187 mathias 964
 
94 jpm 965
            if (!$this->_registry->channelExists($remotechannel)) {
966
                do {
967
                    if ($this->config->get('auto_discover')) {
968
                        if ($this->discover($remotechannel)) {
969
                            break;
970
                        }
971
                    }
972
                    return PEAR::raiseError('Unknown remote channel: ' . $remotechannel);
973
                } while (false);
974
            }
187 mathias 975
 
976
            $chan = $this->_registry->getChannel($remotechannel);
94 jpm 977
            if (PEAR::isError($chan)) {
978
                return $chan;
979
            }
187 mathias 980
 
981
            $version = $this->_registry->packageInfo($dep['name'], 'version', $remotechannel);
94 jpm 982
            $this->configSet('default_channel', $remotechannel);
983
        }
187 mathias 984
 
94 jpm 985
        $state = isset($parr['state']) ? $parr['state'] : $this->config->get('preferred_state');
986
        if (isset($parr['state']) && isset($parr['version'])) {
987
            unset($parr['state']);
988
        }
187 mathias 989
 
94 jpm 990
        if (isset($dep['uri'])) {
187 mathias 991
            $info = $this->newDownloaderPackage($this);
94 jpm 992
            PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
993
            $err = $info->initialize($dep);
994
            PEAR::staticPopErrorHandling();
995
            if (!$err) {
996
                // skip parameters that were missed by preferred_state
997
                return PEAR::raiseError('Cannot initialize dependency');
998
            }
187 mathias 999
 
94 jpm 1000
            if (PEAR::isError($err)) {
1001
                if (!isset($this->_options['soft'])) {
1002
                    $this->log(0, $err->getMessage());
1003
                }
187 mathias 1004
 
94 jpm 1005
                if (is_object($info)) {
1006
                    $param = $info->getChannel() . '/' . $info->getPackage();
1007
                }
1008
                return PEAR::raiseError('Package "' . $param . '" is not valid');
1009
            }
1010
            return $info;
187 mathias 1011
        } elseif ($chan->supportsREST($this->config->get('preferred_mirror'))
1012
              &&
1013
                (
1014
                  ($base2 = $chan->getBaseURL('REST1.3', $this->config->get('preferred_mirror')))
1015
                    ||
1016
                  ($base = $chan->getBaseURL('REST1.0', $this->config->get('preferred_mirror')))
1017
                )
1018
        ) {
1019
            if ($base2) {
1020
                $base = $base2;
1021
                $rest = &$this->config->getREST('1.3', $this->_options);
1022
            } else {
1023
                $rest = &$this->config->getREST('1.0', $this->_options);
1024
            }
1025
 
94 jpm 1026
            $url = $rest->getDepDownloadURL($base, $xsdversion, $dep, $parr,
187 mathias 1027
                    $state, $version, $chan->getName());
94 jpm 1028
            if (PEAR::isError($url)) {
1029
                return $url;
1030
            }
187 mathias 1031
 
94 jpm 1032
            if ($parr['channel'] != $curchannel) {
1033
                $this->configSet('default_channel', $curchannel);
1034
            }
187 mathias 1035
 
94 jpm 1036
            if (!is_array($url)) {
1037
                return $url;
1038
            }
187 mathias 1039
 
94 jpm 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');
1044
            }
187 mathias 1045
 
94 jpm 1046
            if (isset($url['info']['required'])) {
1047
                if (!class_exists('PEAR_PackageFile_v2')) {
1048
                    require_once 'PEAR/PackageFile/v2.php';
1049
                }
1050
                $pf = new PEAR_PackageFile_v2;
1051
                $pf->setRawChannel($remotechannel);
1052
            } else {
1053
                if (!class_exists('PEAR_PackageFile_v1')) {
1054
                    require_once 'PEAR/PackageFile/v1.php';
1055
                }
1056
                $pf = new PEAR_PackageFile_v1;
187 mathias 1057
 
94 jpm 1058
            }
1059
            $pf->setRawPackage($url['package']);
1060
            $pf->setDeps($url['info']);
1061
            if ($url['compatible']) {
1062
                $pf->setCompatible($url['compatible']);
1063
            }
187 mathias 1064
 
94 jpm 1065
            $pf->setRawState($url['stability']);
1066
            $url['info'] = &$pf;
1067
            if (!extension_loaded("zlib") || isset($this->_options['nocompress'])) {
1068
                $ext = '.tar';
1069
            } else {
1070
                $ext = '.tgz';
1071
            }
187 mathias 1072
 
1073
            if (is_array($url) && isset($url['url'])) {
1074
                $url['url'] .= $ext;
94 jpm 1075
            }
187 mathias 1076
 
94 jpm 1077
            return $url;
1078
        }
187 mathias 1079
 
1080
        return $this->raiseError($parr['channel'] . ' is using a unsupported protocol - This should never happen.');
94 jpm 1081
    }
1082
 
1083
    /**
1084
     * @deprecated in favor of _getPackageDownloadUrl
1085
     */
1086
    function getPackageDownloadUrl($package, $version = null, $channel = false)
1087
    {
1088
        if ($version) {
1089
            $package .= "-$version";
1090
        }
1091
        if ($this === null || $this->_registry === null) {
1092
            $package = "http://pear.php.net/get/$package";
1093
        } else {
1094
            $chan = $this->_registry->getChannel($channel);
1095
            if (PEAR::isError($chan)) {
1096
                return '';
1097
            }
1098
            $package = "http://" . $chan->getServer() . "/get/$package";
1099
        }
1100
        if (!extension_loaded("zlib")) {
1101
            $package .= '?uncompress=yes';
1102
        }
1103
        return $package;
1104
    }
1105
 
1106
    /**
1107
     * Retrieve a list of downloaded packages after a call to {@link download()}.
1108
     *
1109
     * Also resets the list of downloaded packages.
1110
     * @return array
1111
     */
1112
    function getDownloadedPackages()
1113
    {
1114
        $ret = $this->_downloadedPackages;
1115
        $this->_downloadedPackages = array();
1116
        $this->_toDownload = array();
1117
        return $ret;
1118
    }
1119
 
1120
    function _downloadCallback($msg, $params = null)
1121
    {
1122
        switch ($msg) {
1123
            case 'saveas':
1124
                $this->log(1, "downloading $params ...");
1125
                break;
1126
            case 'done':
1127
                $this->log(1, '...done: ' . number_format($params, 0, '', ',') . ' bytes');
1128
                break;
1129
            case 'bytesread':
1130
                static $bytes;
1131
                if (empty($bytes)) {
1132
                    $bytes = 0;
1133
                }
1134
                if (!($bytes % 10240)) {
1135
                    $this->log(1, '.', false);
1136
                }
1137
                $bytes += $params;
1138
                break;
1139
            case 'start':
1140
                if($params[1] == -1) {
1141
                    $length = "Unknown size";
1142
                } else {
1143
                    $length = number_format($params[1], 0, '', ',')." bytes";
1144
                }
1145
                $this->log(1, "Starting to download {$params[0]} ($length)");
1146
                break;
1147
        }
1148
        if (method_exists($this->ui, '_downloadCallback'))
1149
            $this->ui->_downloadCallback($msg, $params);
1150
    }
1151
 
1152
    function _prependPath($path, $prepend)
1153
    {
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";
1160
                }
1161
                $path = substr($path, 0, 2) . $prepend . substr($path, 2);
1162
            } else {
1163
                $path = $prepend . $path;
1164
            }
1165
        }
1166
        return $path;
1167
    }
1168
 
1169
    /**
1170
     * @param string
1171
     * @param integer
1172
     */
1173
    function pushError($errmsg, $code = -1)
1174
    {
1175
        array_push($this->_errorStack, array($errmsg, $code));
1176
    }
1177
 
1178
    function getErrorMsgs()
1179
    {
1180
        $msgs = array();
1181
        $errs = $this->_errorStack;
1182
        foreach ($errs as $err) {
1183
            $msgs[] = $err[0];
1184
        }
1185
        $this->_errorStack = array();
1186
        return $msgs;
1187
    }
1188
 
1189
    /**
1190
     * for BC
187 mathias 1191
     *
1192
     * @deprecated
94 jpm 1193
     */
1194
    function sortPkgDeps(&$packages, $uninstall = false)
1195
    {
187 mathias 1196
        $uninstall ?
94 jpm 1197
            $this->sortPackagesForUninstall($packages) :
1198
            $this->sortPackagesForInstall($packages);
1199
    }
1200
 
1201
    /**
1202
     * Sort a list of arrays of array(downloaded packagefilename) by dependency.
1203
     *
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)
1208
     */
1209
    function sortPackagesForInstall(&$packages)
1210
    {
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);
1215
        $nodes = array();
1216
        $reg = &$this->config->getRegistry();
1217
        foreach ($packages as $i => $package) {
1218
            $pname = $reg->parsedPackageNameToString(
1219
                array(
1220
                    'channel' => $package->getChannel(),
1221
                    'package' => strtolower($package->getPackage()),
1222
                ));
1223
            $nodes[$pname] = new Structures_Graph_Node;
1224
            $nodes[$pname]->setData($packages[$i]);
1225
            $depgraph->addNode($nodes[$pname]);
1226
        }
187 mathias 1227
 
94 jpm 1228
        $deplinks = array();
1229
        foreach ($nodes as $package => $node) {
1230
            $pf = &$node->getData();
1231
            $pdeps = $pf->getDeps(true);
1232
            if (!$pdeps) {
1233
                continue;
1234
            }
187 mathias 1235
 
94 jpm 1236
            if ($pf->getPackagexmlVersion() == '1.0') {
1237
                foreach ($pdeps as $dep) {
1238
                    if ($dep['type'] != 'pkg' ||
1239
                          (isset($dep['optional']) && $dep['optional'] == 'yes')) {
1240
                        continue;
1241
                    }
187 mathias 1242
 
94 jpm 1243
                    $dname = $reg->parsedPackageNameToString(
1244
                          array(
1245
                              'channel' => 'pear.php.net',
1246
                              'package' => strtolower($dep['name']),
1247
                          ));
187 mathias 1248
 
1249
                    if (isset($nodes[$dname])) {
94 jpm 1250
                        if (!isset($deplinks[$dname])) {
1251
                            $deplinks[$dname] = array();
1252
                        }
187 mathias 1253
 
94 jpm 1254
                        $deplinks[$dname][$package] = 1;
1255
                        // dependency is in installed packages
1256
                        continue;
1257
                    }
187 mathias 1258
 
94 jpm 1259
                    $dname = $reg->parsedPackageNameToString(
1260
                          array(
1261
                              'channel' => 'pecl.php.net',
1262
                              'package' => strtolower($dep['name']),
1263
                          ));
187 mathias 1264
 
1265
                    if (isset($nodes[$dname])) {
94 jpm 1266
                        if (!isset($deplinks[$dname])) {
1267
                            $deplinks[$dname] = array();
1268
                        }
187 mathias 1269
 
94 jpm 1270
                        $deplinks[$dname][$package] = 1;
1271
                        // dependency is in installed packages
1272
                        continue;
1273
                    }
1274
                }
1275
            } else {
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])) {
1282
                        $t = array($t);
1283
                    }
187 mathias 1284
 
94 jpm 1285
                    $this->_setupGraph($t, $reg, $deplinks, $nodes, $package);
1286
                }
187 mathias 1287
 
94 jpm 1288
                if (isset($pdeps['group'])) {
1289
                    if (!isset($pdeps['group'][0])) {
1290
                        $pdeps['group'] = array($pdeps['group']);
1291
                    }
187 mathias 1292
 
94 jpm 1293
                    foreach ($pdeps['group'] as $group) {
1294
                        if (isset($group['subpackage'])) {
1295
                            $t = $group['subpackage'];
1296
                            if (!isset($t[0])) {
1297
                                $t = array($t);
1298
                            }
187 mathias 1299
 
94 jpm 1300
                            $this->_setupGraph($t, $reg, $deplinks, $nodes, $package);
1301
                        }
1302
                    }
1303
                }
187 mathias 1304
 
94 jpm 1305
                if (isset($pdeps['optional']['subpackage'])) {
1306
                    $t = $pdeps['optional']['subpackage'];
1307
                    if (!isset($t[0])) {
1308
                        $t = array($t);
1309
                    }
187 mathias 1310
 
94 jpm 1311
                    $this->_setupGraph($t, $reg, $deplinks, $nodes, $package);
1312
                }
187 mathias 1313
 
94 jpm 1314
                if (isset($pdeps['required']['package'])) {
1315
                    $t = $pdeps['required']['package'];
1316
                    if (!isset($t[0])) {
1317
                        $t = array($t);
1318
                    }
187 mathias 1319
 
94 jpm 1320
                    $this->_setupGraph($t, $reg, $deplinks, $nodes, $package);
1321
                }
187 mathias 1322
 
94 jpm 1323
                if (isset($pdeps['group'])) {
1324
                    if (!isset($pdeps['group'][0])) {
1325
                        $pdeps['group'] = array($pdeps['group']);
1326
                    }
187 mathias 1327
 
94 jpm 1328
                    foreach ($pdeps['group'] as $group) {
1329
                        if (isset($group['package'])) {
1330
                            $t = $group['package'];
1331
                            if (!isset($t[0])) {
1332
                                $t = array($t);
1333
                            }
187 mathias 1334
 
94 jpm 1335
                            $this->_setupGraph($t, $reg, $deplinks, $nodes, $package);
1336
                        }
1337
                    }
1338
                }
1339
            }
1340
        }
187 mathias 1341
 
94 jpm 1342
        $this->_detectDepCycle($deplinks);
1343
        foreach ($deplinks as $dependent => $parents) {
1344
            foreach ($parents as $parent => $unused) {
1345
                $nodes[$dependent]->connectTo($nodes[$parent]);
1346
            }
1347
        }
187 mathias 1348
 
94 jpm 1349
        $installOrder = Structures_Graph_Manipulator_TopologicalSorter::sort($depgraph);
1350
        $ret = array();
187 mathias 1351
        for ($i = 0, $count = count($installOrder); $i < $count; $i++) {
94 jpm 1352
            foreach ($installOrder[$i] as $index => $sortedpackage) {
1353
                $data = &$installOrder[$i][$index]->getData();
1354
                $ret[] = &$nodes[$reg->parsedPackageNameToString(
1355
                          array(
1356
                              'channel' => $data->getChannel(),
1357
                              'package' => strtolower($data->getPackage()),
1358
                          ))]->getData();
1359
            }
1360
        }
187 mathias 1361
 
94 jpm 1362
        $packages = $ret;
1363
        return;
1364
    }
1365
 
1366
    /**
1367
     * Detect recursive links between dependencies and break the cycles
1368
     *
1369
     * @param array
1370
     * @access private
1371
     */
1372
    function _detectDepCycle(&$deplinks)
1373
    {
1374
        do {
1375
            $keepgoing = false;
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)) {
1381
                        $keepgoing = true;
1382
                        unset($deplinks[$dep][$parent]);
1383
                        if (count($deplinks[$dep]) == 0) {
1384
                            unset($deplinks[$dep]);
1385
                        }
187 mathias 1386
 
94 jpm 1387
                        continue 3;
1388
                    }
1389
                }
1390
            }
1391
        } while ($keepgoing);
1392
    }
1393
 
1394
    function _testCycle($test, $deplinks, $dep)
1395
    {
1396
        static $visited = array();
1397
        if ($test === null) {
1398
            $visited = array();
1399
            return;
1400
        }
187 mathias 1401
 
94 jpm 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])) {
1405
            return false;
1406
        }
187 mathias 1407
 
94 jpm 1408
        $visited[$dep] = 1;
1409
        if ($test == $dep) {
1410
            return true;
1411
        }
187 mathias 1412
 
94 jpm 1413
        if (isset($deplinks[$dep])) {
1414
            if (in_array($test, array_keys($deplinks[$dep]), true)) {
1415
                return true;
1416
            }
187 mathias 1417
 
94 jpm 1418
            foreach ($deplinks[$dep] as $parent => $unused) {
1419
                if ($this->_testCycle($test, $deplinks, $parent)) {
1420
                    return true;
1421
                }
1422
            }
1423
        }
187 mathias 1424
 
94 jpm 1425
        return false;
1426
    }
1427
 
1428
    /**
1429
     * Set up the dependency for installation parsing
1430
     *
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
1436
     * @access private
1437
     */
1438
    function _setupGraph($t, $reg, &$deplinks, &$nodes, $package)
1439
    {
1440
        foreach ($t as $dep) {
187 mathias 1441
            $depchannel = !isset($dep['channel']) ? '__uri': $dep['channel'];
94 jpm 1442
            $dname = $reg->parsedPackageNameToString(
1443
                  array(
1444
                      'channel' => $depchannel,
1445
                      'package' => strtolower($dep['name']),
1446
                  ));
187 mathias 1447
 
1448
            if (isset($nodes[$dname])) {
94 jpm 1449
                if (!isset($deplinks[$dname])) {
1450
                    $deplinks[$dname] = array();
1451
                }
1452
                $deplinks[$dname][$package] = 1;
1453
            }
1454
        }
1455
    }
1456
 
1457
    function _dependsOn($a, $b)
1458
    {
187 mathias 1459
        return $this->_checkDepTree(strtolower($a->getChannel()), strtolower($a->getPackage()), $b);
94 jpm 1460
    }
1461
 
1462
    function _checkDepTree($channel, $package, $b, $checked = array())
1463
    {
1464
        $checked[$channel][$package] = true;
1465
        if (!isset($this->_depTree[$channel][$package])) {
1466
            return false;
1467
        }
187 mathias 1468
 
94 jpm 1469
        if (isset($this->_depTree[$channel][$package][strtolower($b->getChannel())]
1470
              [strtolower($b->getPackage())])) {
1471
            return true;
1472
        }
187 mathias 1473
 
94 jpm 1474
        foreach ($this->_depTree[$channel][$package] as $ch => $packages) {
1475
            foreach ($packages as $pa => $true) {
1476
                if ($this->_checkDepTree($ch, $pa, $b, $checked)) {
1477
                    return true;
1478
                }
1479
            }
1480
        }
187 mathias 1481
 
94 jpm 1482
        return false;
1483
    }
1484
 
1485
    function _sortInstall($a, $b)
1486
    {
1487
        if (!$a->getDeps() && !$b->getDeps()) {
1488
            return 0; // neither package has dependencies, order is insignificant
1489
        }
1490
        if ($a->getDeps() && !$b->getDeps()) {
1491
            return 1; // $a must be installed after $b because $a has dependencies
1492
        }
1493
        if (!$a->getDeps() && $b->getDeps()) {
1494
            return -1; // $b must be installed after $a because $b has dependencies
1495
        }
1496
        // both packages have dependencies
1497
        if ($this->_dependsOn($a, $b)) {
1498
            return 1;
1499
        }
1500
        if ($this->_dependsOn($b, $a)) {
1501
            return -1;
1502
        }
1503
        return 0;
1504
    }
1505
 
1506
    /**
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:
1512
     *
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
1526
     *                of bytes read
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)
1531
     *
1532
     * If an HTTP proxy has been configured (http_proxy PEAR_Config
1533
     * setting), the proxy will be used.
1534
     *
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
1540
     *                           updates
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
187 mathias 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
1550
     *                values.
1551
     *                If $lastmodified was given and the there are no changes,
1552
     *                boolean false is returned.
94 jpm 1553
     *
1554
     * @access public
1555
     */
187 mathias 1556
    public static function _downloadHttp(
1557
        $object, $url, &$ui, $save_dir = '.', $callback = null, $lastmodified = null,
1558
        $accept = false, $channel = false
1559
    ) {
94 jpm 1560
        static $redirect = 0;
187 mathias 1561
        // always reset , so we are clean case of error
94 jpm 1562
        $wasredirect = $redirect;
1563
        $redirect = 0;
1564
        if ($callback) {
1565
            call_user_func($callback, 'setup', array(&$ui));
1566
        }
187 mathias 1567
 
94 jpm 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 . '"');
1571
        }
187 mathias 1572
 
94 jpm 1573
        if (!isset($info['host'])) {
1574
            return PEAR::raiseError('Cannot download from non-URL "' . $url . '"');
1575
        }
187 mathias 1576
 
1577
        $host = isset($info['host']) ? $info['host'] : null;
1578
        $port = isset($info['port']) ? $info['port'] : null;
1579
        $path = isset($info['path']) ? $info['path'] : null;
1580
 
1581
        if ($object !== null) {
1582
            $config = $object->config;
94 jpm 1583
        } else {
1584
            $config = &PEAR_Config::singleton();
1585
        }
187 mathias 1586
 
94 jpm 1587
        $proxy_host = $proxy_port = $proxy_user = $proxy_pass = '';
187 mathias 1588
        if ($config->get('http_proxy') &&
94 jpm 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;
1593
            }
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;
1597
 
1598
            if ($callback) {
1599
                call_user_func($callback, 'message', "Using HTTP proxy $host:$port");
1600
            }
1601
        }
187 mathias 1602
 
94 jpm 1603
        if (empty($port)) {
187 mathias 1604
            $port = (isset($info['scheme']) && $info['scheme'] == 'https') ? 443 : 80;
94 jpm 1605
        }
187 mathias 1606
 
1607
        $scheme = (isset($info['scheme']) && $info['scheme'] == 'https') ? 'https' : 'http';
1608
 
94 jpm 1609
        if ($proxy_host != '') {
1610
            $fp = @fsockopen($proxy_host, $proxy_port, $errno, $errstr);
1611
            if (!$fp) {
1612
                if ($callback) {
1613
                    call_user_func($callback, 'connfailed', array($proxy_host, $proxy_port,
1614
                                                                  $errno, $errstr));
1615
                }
1616
                return PEAR::raiseError("Connection to `$proxy_host:$proxy_port' failed: $errstr", $errno);
1617
            }
187 mathias 1618
 
94 jpm 1619
            if ($lastmodified === false || $lastmodified) {
187 mathias 1620
                $request  = "GET $url HTTP/1.1\r\n";
1621
                $request .= "Host: $host\r\n";
94 jpm 1622
            } else {
187 mathias 1623
                $request  = "GET $url HTTP/1.0\r\n";
1624
                $request .= "Host: $host\r\n";
94 jpm 1625
            }
1626
        } else {
187 mathias 1627
            $network_host = $host;
94 jpm 1628
            if (isset($info['scheme']) && $info['scheme'] == 'https') {
187 mathias 1629
                $network_host = 'ssl://' . $host;
94 jpm 1630
            }
187 mathias 1631
 
1632
            $fp = @fsockopen($network_host, $port, $errno, $errstr);
94 jpm 1633
            if (!$fp) {
1634
                if ($callback) {
1635
                    call_user_func($callback, 'connfailed', array($host, $port,
1636
                                                                  $errno, $errstr));
1637
                }
1638
                return PEAR::raiseError("Connection to `$host:$port' failed: $errstr", $errno);
1639
            }
187 mathias 1640
 
94 jpm 1641
            if ($lastmodified === false || $lastmodified) {
1642
                $request = "GET $path HTTP/1.1\r\n";
187 mathias 1643
                $request .= "Host: $host\r\n";
94 jpm 1644
            } else {
1645
                $request = "GET $path HTTP/1.0\r\n";
1646
                $request .= "Host: $host\r\n";
1647
            }
1648
        }
187 mathias 1649
 
94 jpm 1650
        $ifmodifiedsince = '';
1651
        if (is_array($lastmodified)) {
1652
            if (isset($lastmodified['Last-Modified'])) {
1653
                $ifmodifiedsince = 'If-Modified-Since: ' . $lastmodified['Last-Modified'] . "\r\n";
1654
            }
187 mathias 1655
 
94 jpm 1656
            if (isset($lastmodified['ETag'])) {
1657
                $ifmodifiedsince .= "If-None-Match: $lastmodified[ETag]\r\n";
1658
            }
1659
        } else {
1660
            $ifmodifiedsince = ($lastmodified ? "If-Modified-Since: $lastmodified\r\n" : '');
1661
        }
187 mathias 1662
 
1663
        $request .= $ifmodifiedsince .
1664
            "User-Agent: PEAR/1.10.1/PHP/" . PHP_VERSION . "\r\n";
1665
 
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);
94 jpm 1669
            if ($username && $password) {
1670
                $tmp = base64_encode("$username:$password");
1671
                $request .= "Authorization: Basic $tmp\r\n";
1672
            }
1673
        }
187 mathias 1674
 
94 jpm 1675
        if ($proxy_host != '' && $proxy_user != '') {
1676
            $request .= 'Proxy-Authorization: Basic ' .
1677
                base64_encode($proxy_user . ':' . $proxy_pass) . "\r\n";
1678
        }
187 mathias 1679
 
94 jpm 1680
        if ($accept) {
1681
            $request .= 'Accept: ' . implode(', ', $accept) . "\r\n";
1682
        }
187 mathias 1683
 
94 jpm 1684
        $request .= "Connection: close\r\n";
1685
        $request .= "\r\n";
1686
        fwrite($fp, $request);
1687
        $headers = array();
1688
        $reply = 0;
1689
        while (trim($line = fgets($fp, 1024))) {
187 mathias 1690
            if (preg_match('/^([^:]+):\s+(.*)\s*\\z/', $line, $matches)) {
94 jpm 1691
                $headers[strtolower($matches[1])] = trim($matches[2]);
1692
            } elseif (preg_match('|^HTTP/1.[01] ([0-9]{3}) |', $line, $matches)) {
187 mathias 1693
                $reply = (int)$matches[1];
94 jpm 1694
                if ($reply == 304 && ($lastmodified || ($lastmodified === false))) {
1695
                    return false;
1696
                }
187 mathias 1697
 
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)");
94 jpm 1700
                }
1701
            }
1702
        }
187 mathias 1703
 
94 jpm 1704
        if ($reply != 200) {
187 mathias 1705
            if (!isset($headers['location'])) {
1706
                return PEAR::raiseError("File $scheme://$host:$port$path not valid (redirected but no location)");
94 jpm 1707
            }
187 mathias 1708
 
1709
            if ($wasredirect > 4) {
1710
                return PEAR::raiseError("File $scheme://$host:$port$path not valid (redirection looped more than 5 times)");
1711
            }
1712
 
1713
            $redirect = $wasredirect + 1;
1714
            return static::_downloadHttp($object, $headers['location'],
1715
                    $ui, $save_dir, $callback, $lastmodified, $accept);
94 jpm 1716
        }
187 mathias 1717
 
94 jpm 1718
        if (isset($headers['content-disposition']) &&
187 mathias 1719
            preg_match('/\sfilename=\"([^;]*\S)\"\s*(;|\\z)/', $headers['content-disposition'], $matches)) {
94 jpm 1720
            $save_as = basename($matches[1]);
1721
        } else {
1722
            $save_as = basename($url);
1723
        }
187 mathias 1724
 
94 jpm 1725
        if ($callback) {
1726
            $tmp = call_user_func($callback, 'saveas', $save_as);
1727
            if ($tmp) {
1728
                $save_as = $tmp;
1729
            }
1730
        }
187 mathias 1731
 
94 jpm 1732
        $dest_file = $save_dir . DIRECTORY_SEPARATOR . $save_as;
187 mathias 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');
1735
        }
1736
 
94 jpm 1737
        if (!$wp = @fopen($dest_file, 'wb')) {
1738
            fclose($fp);
1739
            if ($callback) {
1740
                call_user_func($callback, 'writefailed', array($dest_file, $php_errormsg));
1741
            }
1742
            return PEAR::raiseError("could not open $dest_file for writing");
1743
        }
187 mathias 1744
 
1745
        $length = isset($headers['content-length']) ? $headers['content-length'] : -1;
1746
 
94 jpm 1747
        $bytes = 0;
1748
        if ($callback) {
1749
            call_user_func($callback, 'start', array(basename($dest_file), $length));
1750
        }
187 mathias 1751
 
94 jpm 1752
        while ($data = fread($fp, 1024)) {
1753
            $bytes += strlen($data);
1754
            if ($callback) {
1755
                call_user_func($callback, 'bytesread', $bytes);
1756
            }
1757
            if (!@fwrite($wp, $data)) {
1758
                fclose($fp);
1759
                if ($callback) {
1760
                    call_user_func($callback, 'writefailed', array($dest_file, $php_errormsg));
1761
                }
1762
                return PEAR::raiseError("$dest_file: write failed ($php_errormsg)");
1763
            }
1764
        }
187 mathias 1765
 
94 jpm 1766
        fclose($fp);
1767
        fclose($wp);
1768
        if ($callback) {
1769
            call_user_func($callback, 'done', $bytes);
1770
        }
187 mathias 1771
 
94 jpm 1772
        if ($lastmodified === false || $lastmodified) {
1773
            if (isset($headers['etag'])) {
1774
                $lastmodified = array('ETag' => $headers['etag']);
1775
            }
187 mathias 1776
 
94 jpm 1777
            if (isset($headers['last-modified'])) {
1778
                if (is_array($lastmodified)) {
1779
                    $lastmodified['Last-Modified'] = $headers['last-modified'];
1780
                } else {
1781
                    $lastmodified = $headers['last-modified'];
1782
                }
1783
            }
1784
            return array($dest_file, $lastmodified, $headers);
1785
        }
1786
        return $dest_file;
1787
    }
1788
}