Example #1
0
 function _checkChannelForStatus($channel, $chan)
 {
     $rest = new PEAR_REST($this->config);
     PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     $a = $rest->downloadHttp('http://' . $channel . '/channel.xml', $chan->lastModified());
     PEAR::staticPopErrorHandling();
     if (!PEAR::isError($a) && $a) {
         $this->ui->outputData('WARNING: channel "' . $channel . '" has ' . 'updated its protocols, use "channel-update ' . $channel . '" to update');
     }
 }
 /**
  * Test that method returns correct object when DataObject exists and false otherwise.
  *
  * @TODO Add PEAR_Error expectations to simpletest in order to catch them
  */
 function testFactoryDAL()
 {
     // Test when object exists
     $dalBanners = OA_Dal::factoryDAL('banners');
     $this->assertIsA($dalBanners, 'MAX_Dal_Admin_Banners');
     // Test when object doesn't exist
     PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     $dalBanners = OA_Dal::factoryDAL('foo' . rand());
     PEAR::staticPopErrorHandling();
     $this->assertFalse($dalBanners);
 }
 /**
  * Process an aggregate-type bucket.  This is MySQL specific.
  *
  * @param Plugins_DeliveryLog $oBucket a reference to the using (context) object.
  * @param Date $oEnd A PEAR_Date instance, interval_start to process up to (inclusive).
  */
 public function processBucket($oBucket, $oEnd)
 {
     $sTableName = $oBucket->getBucketTableName();
     $oMainDbh =& OA_DB_Distributed::singleton();
     if (PEAR::isError($oMainDbh)) {
         MAX::raiseError($oMainDbh, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
     }
     OA::debug('  - Processing the ' . $sTableName . ' table for data with operation interval start equal to or before ' . $oEnd->format('%Y-%m-%d %H:%M:%S') . ' ' . $oEnd->tz->getShortName(), PEAR_LOG_INFO);
     // Select all rows with interval_start <= previous OI start.
     $rsData =& $this->getBucketTableContent($sTableName, $oEnd);
     $rowCount = $rsData->getRowCount();
     OA::debug('  - ' . $rsData->getRowCount() . ' records found', PEAR_LOG_DEBUG);
     if ($rowCount) {
         // We can't do bulk inserts with ON DUPLICATE.
         $aExecQueries = array();
         if ($rsData->fetch()) {
             // Get first row
             $aRow = $rsData->toArray();
             // Prepare INSERT
             $sInsert = "INSERT INTO {$sTableName} (" . join(',', array_keys($aRow)) . ") VALUES ";
             // Add first row data
             $sRow = '(' . join(',', array_map(array(&$oMainDbh, 'quote'), $aRow)) . ')';
             $sOnDuplicate = ' ON DUPLICATE KEY UPDATE count = count + ' . $aRow['count'];
             // Add first insert
             $aExecQueries[] = $sInsert . $sRow . $sOnDuplicate;
             // Deal with the other rows
             while ($rsData->fetch()) {
                 $aRow = $rsData->toArray();
                 $sRow = '(' . join(',', array_map(array(&$oMainDbh, 'quote'), $aRow)) . ')';
                 $sOnDuplicate = ' ON DUPLICATE KEY UPDATE count = count + ' . $aRow['count'];
                 $aExecQueries[] = $sInsert . $sRow . $sOnDuplicate;
             }
         }
         if (count($aExecQueries)) {
             // Try to disable the binlog for the inserts so we don't
             // replicate back out over our logged data.
             PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
             $result = $oMainDbh->exec('SET SQL_LOG_BIN = 0');
             if (PEAR::isError($result)) {
                 OA::debug('Unable to disable the bin log, proceeding anyway.', PEAR_LOG_WARNING);
             }
             PEAR::staticPopErrorHandling();
             foreach ($aExecQueries as $execQuery) {
                 $result = $oMainDbh->exec($execQuery);
                 if (PEAR::isError($result)) {
                     MAX::raiseError($result, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                 }
             }
         }
     }
 }
Example #4
0
    /**
     * Mark a user for password resetting
     *
     * @param string $user
     * @param string $pass1
     * @param string $pass2
     * @return array
     */
    function resetPassword($user, $pass1, $pass2)
    {
        require_once 'Damblan/Mailer.php';
        $errors = array();
        $salt = md5(mt_rand(4, 13) . $user . time() . $pass1);
        PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
        $this->_dbh->query('DELETE FROM lostpassword WHERE handle=?', array($user));
        $e = $this->_dbh->query('INSERT INTO lostpassword
            (handle, newpassword, salt, requested)
            VALUES(?,?,?,NOW())', array($user, md5($pass1), $salt));
        PEAR::staticPopErrorHandling();
        if (PEAR::isError($e)) {
            $errors[] = 'Could not change password: '******'pear-database-user.php';
            $info = user::info($user);
            $this->_mailer = Damblan_mailer::create(array('To' => array($info['name'] . ' <' . $info['email'] . '>'), 'Reply-To' => array('PEAR QA <' . PEAR_QA_EMAIL . '>'), 'Subject' => '[PEAR-ACCOUNT-PASSWORD] Your password reset request : %username%', 'Body' => 'A request has been made to reset your password for %username%
at pear.php.net.

If you intended to reset the password, please navigate to this page:
  https://' . PEAR_CHANNELNAME . '/account/password-confirm-change.php
and follow the instructions.  Your password reset code is:

%salt%

If you have received this email by mistake or did not request a
password change, no further action is necessary.  Your password
will NOT change until you confirm the change, and it cannot be changed
without the password reset code.  Password change requests are automatically
purged after 24 hours.

PEAR Quality Assurance.'), array('username' => $user, 'salt' => $salt));
            $this->_mailer->send();
        }
        return $errors;
    }
Example #5
0
 /**
  * @param array dependency array
  * @access private
  */
 function _getDepPackageDownloadUrl($dep, $parr)
 {
     $xsdversion = isset($dep['rel']) ? '1.0' : '2.0';
     $curchannel = $this->config->get('default_channel');
     if (isset($dep['uri'])) {
         $xsdversion = '2.0';
         $chan =& $this->_registry->getChannel('__uri');
         if (PEAR::isError($chan)) {
             return $chan;
         }
         $version = $this->_registry->packageInfo($dep['name'], 'version', '__uri');
         $this->configSet('default_channel', '__uri');
     } else {
         if (isset($dep['channel'])) {
             $remotechannel = $dep['channel'];
         } else {
             $remotechannel = 'pear.php.net';
         }
         if (!$this->_registry->channelExists($remotechannel)) {
             do {
                 if ($this->config->get('auto_discover')) {
                     if ($this->discover($remotechannel)) {
                         break;
                     }
                 }
                 return PEAR::raiseError('Unknown remote channel: ' . $remotechannel);
             } while (false);
         }
         $chan =& $this->_registry->getChannel($remotechannel);
         if (PEAR::isError($chan)) {
             return $chan;
         }
         $version = $this->_registry->packageInfo($dep['name'], 'version', $remotechannel);
         $this->configSet('default_channel', $remotechannel);
     }
     $state = isset($parr['state']) ? $parr['state'] : $this->config->get('preferred_state');
     if (isset($parr['state']) && isset($parr['version'])) {
         unset($parr['state']);
     }
     if (isset($dep['uri'])) {
         $info =& $this->newDownloaderPackage($this);
         PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
         $err = $info->initialize($dep);
         PEAR::staticPopErrorHandling();
         if (!$err) {
             // skip parameters that were missed by preferred_state
             return PEAR::raiseError('Cannot initialize dependency');
         }
         if (PEAR::isError($err)) {
             if (!isset($this->_options['soft'])) {
                 $this->log(0, $err->getMessage());
             }
             if (is_object($info)) {
                 $param = $info->getChannel() . '/' . $info->getPackage();
             }
             return PEAR::raiseError('Package "' . $param . '" is not valid');
         }
         return $info;
     } elseif ($chan->supportsREST($this->config->get('preferred_mirror')) && (($base2 = $chan->getBaseURL('REST1.3', $this->config->get('preferred_mirror'))) || ($base = $chan->getBaseURL('REST1.0', $this->config->get('preferred_mirror'))))) {
         if ($base2) {
             $base = $base2;
             $rest =& $this->config->getREST('1.3', $this->_options);
         } else {
             $rest =& $this->config->getREST('1.0', $this->_options);
         }
         $url = $rest->getDepDownloadURL($base, $xsdversion, $dep, $parr, $state, $version, $chan->getName());
         if (PEAR::isError($url)) {
             return $url;
         }
         if ($parr['channel'] != $curchannel) {
             $this->configSet('default_channel', $curchannel);
         }
         if (!is_array($url)) {
             return $url;
         }
         $url['raw'] = false;
         // no checking is necessary for REST
         if (!is_array($url['info'])) {
             return PEAR::raiseError('Invalid remote dependencies retrieved from REST - ' . 'this should never happen');
         }
         if (isset($url['info']['required'])) {
             if (!class_exists('PEAR_PackageFile_v2')) {
                 require_once 'PEAR/PackageFile/v2.php';
             }
             $pf = new PEAR_PackageFile_v2();
             $pf->setRawChannel($remotechannel);
         } else {
             if (!class_exists('PEAR_PackageFile_v1')) {
                 require_once 'PEAR/PackageFile/v1.php';
             }
             $pf = new PEAR_PackageFile_v1();
         }
         $pf->setRawPackage($url['package']);
         $pf->setDeps($url['info']);
         if ($url['compatible']) {
             $pf->setCompatible($url['compatible']);
         }
         $pf->setRawState($url['stability']);
         $url['info'] =& $pf;
         if (!extension_loaded("zlib") || isset($this->_options['nocompress'])) {
             $ext = '.tar';
         } else {
             $ext = '.tgz';
         }
         if (is_array($url) && isset($url['url'])) {
             $url['url'] .= $ext;
         }
         return $url;
     }
     return $this->raiseError($parr['channel'] . ' is using a unsupported protocol - This should never happen.');
 }
Example #6
0
 /**
  * retrieves a list of avaible Packages from master server
  * and downloads them
  *
  * @access public
  * @param string $command the command
  * @param array $options the command options before the command
  * @param array $params the stuff after the command name
  * @return bool true if succesful
  * @throw PEAR_Error
  */
 function doDownloadAll($command, $options, $params)
 {
     $savechannel = $this->config->get('default_channel');
     $reg =& $this->config->getRegistry();
     $channel = isset($options['channel']) ? $options['channel'] : $this->config->get('default_channel');
     if (!$reg->channelExists($channel)) {
         $this->config->set('default_channel', $savechannel);
         return $this->raiseError('Channel "' . $channel . '" does not exist');
     }
     $this->config->set('default_channel', $channel);
     $this->ui->outputData('Using Channel ' . $this->config->get('default_channel'));
     $chan = $reg->getChannel($channel);
     if (PEAR::isError($chan)) {
         return $this->raiseError($chan);
     }
     if ($chan->supportsREST($this->config->get('preferred_mirror')) && ($base = $chan->getBaseURL('REST1.0', $this->config->get('preferred_mirror')))) {
         $rest =& $this->config->getREST('1.0', array());
         $remoteInfo = array_flip($rest->listPackages($base, $channel));
     }
     if (PEAR::isError($remoteInfo)) {
         return $remoteInfo;
     }
     $cmd =& $this->factory("download");
     if (PEAR::isError($cmd)) {
         return $cmd;
     }
     $this->ui->outputData('Using Preferred State of ' . $this->config->get('preferred_state'));
     $this->ui->outputData('Gathering release information, please wait...');
     /**
      * Error handling not necessary, because already done by
      * the download command
      */
     PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     $err = $cmd->run('download', array('downloadonly' => true), array_keys($remoteInfo));
     PEAR::staticPopErrorHandling();
     $this->config->set('default_channel', $savechannel);
     if (PEAR::isError($err)) {
         $this->ui->outputData($err->getMessage());
     }
     return true;
 }
Example #7
0
 /**
  * Create a PEAR_PackageFile_v* from a compresed Tar or Tgz file.
  * @access  public
  * @param string contents of package.xml file
  * @param int package state (one of PEAR_VALIDATE_* constants)
  * @return  PEAR_PackageFile_v1|PEAR_PackageFile_v2
  * @using   Archive_Tar to extract the files
  * @using   fromPackageFile() to load the package after the package.xml
  *          file is extracted.
  */
 function &fromTgzFile($file, $state)
 {
     if (!class_exists('Archive_Tar')) {
         require_once 'Archive/Tar.php';
     }
     $tar = new Archive_Tar($file);
     if ($this->_debug <= 1) {
         $tar->pushErrorHandling(PEAR_ERROR_RETURN);
     }
     $content = $tar->listContent();
     if ($this->_debug <= 1) {
         $tar->popErrorHandling();
     }
     if (!is_array($content)) {
         if (is_string($file) && strlen($file < 255) && (!file_exists($file) || !@is_file($file))) {
             $ret = PEAR::raiseError("could not open file \"{$file}\"");
             return $ret;
         }
         $file = realpath($file);
         $ret = PEAR::raiseError("Could not get contents of package \"{$file}\"" . '. Invalid tgz file.');
         return $ret;
     } else {
         if (!count($content) && !@is_file($file)) {
             $ret = PEAR::raiseError("could not open file \"{$file}\"");
             return $ret;
         }
     }
     $xml = null;
     $origfile = $file;
     foreach ($content as $file) {
         $name = $file['filename'];
         if ($name == 'package2.xml') {
             // allow a .tgz to distribute both versions
             $xml = $name;
             break;
         }
         if ($name == 'package.xml') {
             $xml = $name;
             break;
         } elseif (ereg('package.xml$', $name, $match)) {
             $xml = $name;
             break;
         }
     }
     if ($this->_tmpdir) {
         $tmpdir = $this->_tmpdir;
     } else {
         $tmpdir = System::mkTemp(array('-d', 'pear'));
         PEAR_PackageFile::addTempFile($tmpdir);
     }
     $this->_extractErrors();
     PEAR::staticPushErrorHandling(PEAR_ERROR_CALLBACK, array($this, '_extractErrors'));
     if (!$xml || !$tar->extractList(array($xml), $tmpdir)) {
         $extra = implode("\n", $this->_extractErrors());
         if ($extra) {
             $extra = ' ' . $extra;
         }
         PEAR::staticPopErrorHandling();
         $ret = PEAR::raiseError('could not extract the package.xml file from "' . $origfile . '"' . $extra);
         return $ret;
     }
     PEAR::staticPopErrorHandling();
     $ret =& PEAR_PackageFile::fromPackageFile("{$tmpdir}/{$xml}", $state, $origfile);
     return $ret;
 }
Example #8
0
 /**
  * Uninstall a package
  *
  * This method removes all files installed by the application, and then
  * removes any empty directories.
  * @param string package name
  * @param array Command-line options.  Possibilities include:
  *
  *              - installroot: base installation dir, if not the default
  *              - nodeps: do not process dependencies of other packages to ensure
  *                        uninstallation does not break things
  */
 function uninstall($package, $options = array())
 {
     if (isset($options['installroot'])) {
         $this->config->setInstallRoot($options['installroot']);
         $this->installroot = '';
     } else {
         $this->config->setInstallRoot('');
         $this->installroot = '';
     }
     $this->_registry =& $this->config->getRegistry();
     if (is_object($package)) {
         $channel = $package->getChannel();
         $pkg = $package;
         $package = $pkg->getPackage();
     } else {
         $pkg = false;
         $info = $this->_registry->parsePackageName($package, $this->config->get('default_channel'));
         $channel = $info['channel'];
         $package = $info['package'];
     }
     $savechannel = $this->config->get('default_channel');
     $this->configSet('default_channel', $channel);
     if (!is_object($pkg)) {
         $pkg = $this->_registry->getPackage($package, $channel);
     }
     if (!$pkg) {
         $this->configSet('default_channel', $savechannel);
         return $this->raiseError($this->_registry->parsedPackageNameToString(array('channel' => $channel, 'package' => $package), true) . ' not installed');
     }
     if ($pkg->getInstalledBinary()) {
         // this is just an alias for a binary package
         return $this->_registry->deletePackage($package, $channel);
     }
     $filelist = $pkg->getFilelist();
     PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     if (!class_exists('PEAR_Dependency2')) {
         require_once 'PEAR/Dependency2.php';
     }
     $depchecker =& new PEAR_Dependency2($this->config, $options, array('channel' => $channel, 'package' => $package), PEAR_VALIDATE_UNINSTALLING);
     $e = $depchecker->validatePackageUninstall($this);
     PEAR::staticPopErrorHandling();
     if (PEAR::isError($e)) {
         if (!isset($options['ignore-errors'])) {
             return $this->raiseError($e);
         } else {
             if (!isset($options['soft'])) {
                 $this->log(0, 'WARNING: ' . $e->getMessage());
             }
         }
     } elseif (is_array($e)) {
         if (!isset($options['soft'])) {
             $this->log(0, $e[0]);
         }
     }
     // {{{ Delete the files
     $this->startFileTransaction();
     PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
     if (PEAR::isError($err = $this->_deletePackageFiles($package, $channel))) {
         PEAR::popErrorHandling();
         $this->rollbackFileTransaction();
         $this->configSet('default_channel', $savechannel);
         if (!isset($options['ignore-errors'])) {
             return $this->raiseError($err);
         } else {
             if (!isset($options['soft'])) {
                 $this->log(0, 'WARNING: ' . $err->getMessage());
             }
         }
     } else {
         PEAR::popErrorHandling();
     }
     if (!$this->commitFileTransaction()) {
         $this->rollbackFileTransaction();
         if (!isset($options['ignore-errors'])) {
             return $this->raiseError("uninstall failed");
         } elseif (!isset($options['soft'])) {
             $this->log(0, 'WARNING: uninstall failed');
         }
     } else {
         $this->startFileTransaction();
         if ($dirtree = $pkg->getDirTree()) {
             // attempt to delete empty directories
             uksort($dirtree, array($this, '_sortDirs'));
             foreach ($dirtree as $dir => $notused) {
                 $this->addFileOperation('rmdir', array($dir));
             }
         } else {
             $this->configSet('default_channel', $savechannel);
             return $this->_registry->deletePackage($package, $channel);
         }
         if (!$this->commitFileTransaction()) {
             $this->rollbackFileTransaction();
         }
     }
     // }}}
     $this->configSet('default_channel', $savechannel);
     // Register that the package is no longer installed
     return $this->_registry->deletePackage($package, $channel);
 }
Example #9
0
 function package($pkgfile = null, $compress = true, $pkg2 = null)
 {
     // {{{ validate supplied package.xml file
     if (empty($pkgfile)) {
         $pkgfile = 'package.xml';
     }
     PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     $pkg = new PEAR_PackageFile($this->config, $this->debug);
     $pf =& $pkg->fromPackageFile($pkgfile, PEAR_VALIDATE_NORMAL);
     $main =& $pf;
     PEAR::staticPopErrorHandling();
     if (PEAR::isError($pf)) {
         if (is_array($pf->getUserInfo())) {
             foreach ($pf->getUserInfo() as $error) {
                 $this->log(0, 'Error: ' . $error['message']);
             }
         }
         $this->log(0, $pf->getMessage());
         return $this->raiseError("Cannot package, errors in package file");
     }
     foreach ($pf->getValidationWarnings() as $warning) {
         $this->log(1, 'Warning: ' . $warning['message']);
     }
     // }}}
     if ($pkg2) {
         $this->log(0, 'Attempting to process the second package file');
         PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
         $pf2 =& $pkg->fromPackageFile($pkg2, PEAR_VALIDATE_NORMAL);
         PEAR::staticPopErrorHandling();
         if (PEAR::isError($pf2)) {
             if (is_array($pf2->getUserInfo())) {
                 foreach ($pf2->getUserInfo() as $error) {
                     $this->log(0, 'Error: ' . $error['message']);
                 }
             }
             $this->log(0, $pf2->getMessage());
             return $this->raiseError("Cannot package, errors in second package file");
         }
         foreach ($pf2->getValidationWarnings() as $warning) {
             $this->log(1, 'Warning: ' . $warning['message']);
         }
         if ($pf2->getPackagexmlVersion() == '2.0' || $pf2->getPackagexmlVersion() == '2.1') {
             $main =& $pf2;
             $other =& $pf;
         } else {
             $main =& $pf;
             $other =& $pf2;
         }
         if ($main->getPackagexmlVersion() != '2.0' && $main->getPackagexmlVersion() != '2.1') {
             return PEAR::raiseError('Error: cannot package two package.xml version 1.0, can ' . 'only package together a package.xml 1.0 and package.xml 2.0');
         }
         if ($other->getPackagexmlVersion() != '1.0') {
             return PEAR::raiseError('Error: cannot package two package.xml version 2.0, can ' . 'only package together a package.xml 1.0 and package.xml 2.0');
         }
     }
     $main->setLogger($this);
     if (!$main->validate(PEAR_VALIDATE_PACKAGING)) {
         foreach ($main->getValidationWarnings() as $warning) {
             $this->log(0, 'Error: ' . $warning['message']);
         }
         return $this->raiseError("Cannot package, errors in package");
     }
     foreach ($main->getValidationWarnings() as $warning) {
         $this->log(1, 'Warning: ' . $warning['message']);
     }
     if ($pkg2) {
         $other->setLogger($this);
         $a = false;
         if (!$other->validate(PEAR_VALIDATE_NORMAL) || ($a = !$main->isEquivalent($other))) {
             foreach ($other->getValidationWarnings() as $warning) {
                 $this->log(0, 'Error: ' . $warning['message']);
             }
             foreach ($main->getValidationWarnings() as $warning) {
                 $this->log(0, 'Error: ' . $warning['message']);
             }
             if ($a) {
                 return $this->raiseError('The two package.xml files are not equivalent!');
             }
             return $this->raiseError("Cannot package, errors in package");
         }
         foreach ($other->getValidationWarnings() as $warning) {
             $this->log(1, 'Warning: ' . $warning['message']);
         }
         $gen =& $main->getDefaultGenerator();
         $tgzfile = $gen->toTgz2($this, $other, $compress);
         if (PEAR::isError($tgzfile)) {
             return $tgzfile;
         }
         $dest_package = basename($tgzfile);
         $pkgdir = dirname($pkgfile);
         // TAR the Package -------------------------------------------
         $this->log(1, "Package {$dest_package} done");
         if (file_exists("{$pkgdir}/CVS/Root")) {
             $cvsversion = preg_replace('/[^a-z0-9]/i', '_', $pf->getVersion());
             $cvstag = "RELEASE_{$cvsversion}";
             $this->log(1, 'Tag the released code with "pear cvstag ' . $main->getPackageFile() . '"');
             $this->log(1, "(or set the CVS tag {$cvstag} by hand)");
         } elseif (file_exists("{$pkgdir}/.svn")) {
             $svnversion = preg_replace('/[^a-z0-9]/i', '.', $pf->getVersion());
             $svntag = $pf->getName() . "-{$svnversion}";
             $this->log(1, 'Tag the released code with "pear svntag ' . $main->getPackageFile() . '"');
             $this->log(1, "(or set the SVN tag {$svntag} by hand)");
         }
     } else {
         // this branch is executed for single packagefile packaging
         $gen =& $pf->getDefaultGenerator();
         $tgzfile = $gen->toTgz($this, $compress);
         if (PEAR::isError($tgzfile)) {
             $this->log(0, $tgzfile->getMessage());
             return $this->raiseError("Cannot package, errors in package");
         }
         $dest_package = basename($tgzfile);
         $pkgdir = dirname($pkgfile);
         // TAR the Package -------------------------------------------
         $this->log(1, "Package {$dest_package} done");
         if (file_exists("{$pkgdir}/CVS/Root")) {
             $cvsversion = preg_replace('/[^a-z0-9]/i', '_', $pf->getVersion());
             $cvstag = "RELEASE_{$cvsversion}";
             $this->log(1, "Tag the released code with `pear cvstag {$pkgfile}'");
             $this->log(1, "(or set the CVS tag {$cvstag} by hand)");
         } elseif (file_exists("{$pkgdir}/.svn")) {
             $svnversion = preg_replace('/[^a-z0-9]/i', '.', $pf->getVersion());
             $svntag = $pf->getName() . "-{$svnversion}";
             $this->log(1, "Tag the released code with `pear svntag {$pkgfile}'");
             $this->log(1, "(or set the SVN tag {$svntag} by hand)");
         }
     }
     return $dest_package;
 }
Example #10
0
 function doRunTests($command, $options, $params)
 {
     if (isset($options['phpunit']) && isset($options['tapoutput'])) {
         return $this->raiseError('ERROR: cannot use both --phpunit and --tapoutput at the same time');
     }
     require_once 'PEAR/Common.php';
     require_once 'System.php';
     $log = new PEAR_Common();
     $log->ui =& $this->ui;
     // slightly hacky, but it will work
     $tests = array();
     $depth = isset($options['recur']) ? 4 : 1;
     if (!count($params)) {
         $params[] = '.';
     }
     if (isset($options['package'])) {
         $oldparams = $params;
         $params = array();
         $reg =& $this->config->getRegistry();
         foreach ($oldparams as $param) {
             $pname = $reg->parsePackageName($param, $this->config->get('default_channel'));
             if (PEAR::isError($pname)) {
                 return $this->raiseError($pname);
             }
             $package =& $reg->getPackage($pname['package'], $pname['channel']);
             if (!$package) {
                 return PEAR::raiseError('Unknown package "' . $reg->parsedPackageNameToString($pname) . '"');
             }
             $filelist = $package->getFilelist();
             foreach ($filelist as $name => $atts) {
                 if (isset($atts['role']) && $atts['role'] != 'test') {
                     continue;
                 }
                 if (isset($options['phpunit']) && preg_match('/AllTests\\.php\\z/i', $name)) {
                     $params[] = $atts['installed_as'];
                     continue;
                 } elseif (!preg_match('/\\.phpt\\z/', $name)) {
                     continue;
                 }
                 $params[] = $atts['installed_as'];
             }
         }
     }
     foreach ($params as $p) {
         if (is_dir($p)) {
             if (isset($options['phpunit'])) {
                 $dir = System::find(array($p, '-type', 'f', '-maxdepth', $depth, '-name', 'AllTests.php'));
                 if (count($dir)) {
                     foreach ($dir as $p) {
                         $p = realpath($p);
                         if (!count($tests) || count($tests) && strlen($p) < strlen($tests[0])) {
                             // this is in a higher-level directory, use this one instead.
                             $tests = array($p);
                         }
                     }
                 }
                 continue;
             }
             $dir = System::find(array($p, '-type', 'f', '-maxdepth', $depth, '-name', '*.phpt'));
             $tests = array_merge($tests, $dir);
         } else {
             if (isset($options['phpunit'])) {
                 if (preg_match('/AllTests\\.php\\z/i', $p)) {
                     $p = realpath($p);
                     if (!count($tests) || count($tests) && strlen($p) < strlen($tests[0])) {
                         // this is in a higher-level directory, use this one instead.
                         $tests = array($p);
                     }
                 }
                 continue;
             }
             if (file_exists($p) && preg_match('/\\.phpt$/', $p)) {
                 $tests[] = $p;
                 continue;
             }
             if (!preg_match('/\\.phpt\\z/', $p)) {
                 $p .= '.phpt';
             }
             $dir = System::find(array(dirname($p), '-type', 'f', '-maxdepth', $depth, '-name', $p));
             $tests = array_merge($tests, $dir);
         }
     }
     $ini_settings = '';
     if (isset($options['ini'])) {
         $ini_settings .= $options['ini'];
     }
     if (isset($_ENV['TEST_PHP_INCLUDE_PATH'])) {
         $ini_settings .= " -d include_path={$_ENV['TEST_PHP_INCLUDE_PATH']}";
     }
     if ($ini_settings) {
         $this->ui->outputData('Using INI settings: "' . $ini_settings . '"');
     }
     $skipped = $passed = $failed = array();
     $tests_count = count($tests);
     $this->ui->outputData('Running ' . $tests_count . ' tests', $command);
     $start = time();
     if (isset($options['realtimelog']) && file_exists('run-tests.log')) {
         unlink('run-tests.log');
     }
     if (isset($options['tapoutput'])) {
         $tap = '1..' . $tests_count . "\n";
     }
     require_once 'PEAR/RunTest.php';
     $run = new PEAR_RunTest($log, $options);
     $run->tests_count = $tests_count;
     if (isset($options['coverage']) && extension_loaded('xdebug')) {
         $run->xdebug_loaded = true;
     } else {
         $run->xdebug_loaded = false;
     }
     $j = $i = 1;
     foreach ($tests as $t) {
         if (isset($options['realtimelog'])) {
             $fp = @fopen('run-tests.log', 'a');
             if ($fp) {
                 fwrite($fp, "Running test [{$i} / {$tests_count}] {$t}...");
                 fclose($fp);
             }
         }
         PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
         if (isset($options['phpunit'])) {
             $result = $run->runPHPUnit($t, $ini_settings);
         } else {
             $result = $run->run($t, $ini_settings, $j);
         }
         PEAR::staticPopErrorHandling();
         if (PEAR::isError($result)) {
             $this->ui->log($result->getMessage());
             continue;
         }
         if (isset($options['tapoutput'])) {
             $tap .= $result[0] . ' ' . $i . $result[1] . "\n";
             continue;
         }
         if (isset($options['realtimelog'])) {
             $fp = @fopen('run-tests.log', 'a');
             if ($fp) {
                 fwrite($fp, "{$result}\n");
                 fclose($fp);
             }
         }
         if ($result == 'FAILED') {
             $failed[] = $t;
         }
         if ($result == 'PASSED') {
             $passed[] = $t;
         }
         if ($result == 'SKIPPED') {
             $skipped[] = $t;
         }
         $j++;
     }
     $total = date('i:s', time() - $start);
     if (isset($options['tapoutput'])) {
         $fp = @fopen('run-tests.log', 'w');
         if ($fp) {
             fwrite($fp, $tap, strlen($tap));
             fclose($fp);
             $this->ui->outputData('wrote TAP-format log to "' . realpath('run-tests.log') . '"', $command);
         }
     } else {
         if (count($failed)) {
             $output = "TOTAL TIME: {$total}\n";
             $output .= count($passed) . " PASSED TESTS\n";
             $output .= count($skipped) . " SKIPPED TESTS\n";
             $output .= count($failed) . " FAILED TESTS:\n";
             foreach ($failed as $failure) {
                 $output .= $failure . "\n";
             }
             $mode = isset($options['realtimelog']) ? 'a' : 'w';
             $fp = @fopen('run-tests.log', $mode);
             if ($fp) {
                 fwrite($fp, $output, strlen($output));
                 fclose($fp);
                 $this->ui->outputData('wrote log to "' . realpath('run-tests.log') . '"', $command);
             }
         } elseif (file_exists('run-tests.log') && !is_dir('run-tests.log')) {
             @unlink('run-tests.log');
         }
     }
     $this->ui->outputData('TOTAL TIME: ' . $total);
     $this->ui->outputData(count($passed) . ' PASSED TESTS', $command);
     $this->ui->outputData(count($skipped) . ' SKIPPED TESTS', $command);
     if (count($failed)) {
         $this->ui->outputData(count($failed) . ' FAILED TESTS:', $command);
         foreach ($failed as $failure) {
             $this->ui->outputData($failure, $command);
         }
     }
     return true;
 }
Example #11
0
File: Test.php Project: OTiZ/osx
 function doRunTests($command, $options, $params)
 {
     require_once 'PEAR/Common.php';
     require_once 'PEAR/RunTest.php';
     require_once 'System.php';
     $log = new PEAR_Common();
     $log->ui =& $this->ui;
     // slightly hacky, but it will work
     $run = new PEAR_RunTest($log, $options);
     $tests = array();
     if (isset($options['recur'])) {
         $depth = 4;
     } else {
         $depth = 1;
     }
     if (!count($params)) {
         $params[] = '.';
     }
     if (isset($options['package'])) {
         $oldparams = $params;
         $params = array();
         $reg =& $this->config->getRegistry();
         foreach ($oldparams as $param) {
             $pname = $reg->parsePackageName($param, $this->config->get('default_channel'));
             if (PEAR::isError($pname)) {
                 return $this->raiseError($pname);
             }
             $package =& $reg->getPackage($pname['package'], $pname['channel']);
             if (!$package) {
                 return PEAR::raiseError('Unknown package "' . $reg->parsedPackageNameToString($pname) . '"');
             }
             $filelist = $package->getFilelist();
             foreach ($filelist as $name => $atts) {
                 if (isset($atts['role']) && $atts['role'] != 'test') {
                     continue;
                 }
                 if (!preg_match('/\\.phpt$/', $name)) {
                     continue;
                 }
                 $params[] = $atts['installed_as'];
             }
         }
     }
     foreach ($params as $p) {
         if (is_dir($p)) {
             $dir = System::find(array($p, '-type', 'f', '-maxdepth', $depth, '-name', '*.phpt'));
             $tests = array_merge($tests, $dir);
         } else {
             if (!@file_exists($p)) {
                 if (!preg_match('/\\.phpt$/', $p)) {
                     $p .= '.phpt';
                 }
                 $dir = System::find(array(dirname($p), '-type', 'f', '-maxdepth', $depth, '-name', $p));
                 $tests = array_merge($tests, $dir);
             } else {
                 $tests[] = $p;
             }
         }
     }
     $ini_settings = '';
     if (isset($options['ini'])) {
         $ini_settings .= $options['ini'];
     }
     if (isset($_ENV['TEST_PHP_INCLUDE_PATH'])) {
         $ini_settings .= " -d include_path={$_ENV['TEST_PHP_INCLUDE_PATH']}";
     }
     if ($ini_settings) {
         $this->ui->outputData('Using INI settings: "' . $ini_settings . '"');
     }
     $skipped = $passed = $failed = array();
     $this->ui->outputData('Running ' . count($tests) . ' tests', $command);
     $start = time();
     if (isset($options['realtimelog'])) {
         @unlink('run-tests.log');
     }
     foreach ($tests as $t) {
         if (isset($options['realtimelog'])) {
             $fp = @fopen('run-tests.log', 'a');
             if ($fp) {
                 fwrite($fp, "Running test {$t}...");
                 fclose($fp);
             }
         }
         PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
         $result = $run->run($t, $ini_settings);
         PEAR::staticPopErrorHandling();
         if (PEAR::isError($result)) {
             $this->ui->log(0, $result->getMessage());
             continue;
         }
         if (OS_WINDOWS) {
             for ($i = 0; $i < 2000; $i++) {
                 $i = $i;
                 // delay - race conditions on windows
             }
         }
         if (isset($options['realtimelog'])) {
             $fp = @fopen('run-tests.log', 'a');
             if ($fp) {
                 fwrite($fp, "{$result}\n");
                 fclose($fp);
             }
         }
         if ($result == 'FAILED') {
             $failed[] = $t;
         }
         if ($result == 'PASSED') {
             $passed[] = $t;
         }
         if ($result == 'SKIPPED') {
             $skipped[] = $t;
         }
     }
     $total = date('i:s', time() - $start);
     if (count($failed)) {
         $output = "TOTAL TIME: {$total}\n";
         $output .= count($passed) . " PASSED TESTS\n";
         $output .= count($skipped) . " SKIPPED TESTS\n";
         $output .= count($failed) . " FAILED TESTS:\n";
         foreach ($failed as $failure) {
             $output .= $failure . "\n";
         }
         if (isset($options['realtimelog'])) {
             $fp = @fopen('run-tests.log', 'a');
         } else {
             $fp = @fopen('run-tests.log', 'w');
         }
         if ($fp) {
             fwrite($fp, $output, strlen($output));
             fclose($fp);
             $this->ui->outputData('wrote log to "' . realpath('run-tests.log') . '"', $command);
         }
     } elseif (@file_exists('run-tests.log') && !@is_dir('run-tests.log')) {
         @unlink('run-tests.log');
     }
     $this->ui->outputData('TOTAL TIME: ' . $total);
     $this->ui->outputData(count($passed) . ' PASSED TESTS', $command);
     $this->ui->outputData(count($skipped) . ' SKIPPED TESTS', $command);
     if (count($failed)) {
         $this->ui->outputData(count($failed) . ' FAILED TESTS:', $command);
         foreach ($failed as $failure) {
             $this->ui->outputData($failure, $command);
         }
     }
     return true;
 }
Example #12
0
 /**
  * Initialize a TemplateObject
  *
  * @param string  $file     filename of the template file
  *
  * @return object Object of HTML/IT - Template - Class
  */
 function _initTemplate($file)
 {
     // Errors here can not be displayed using the UI
     PEAR::staticPushErrorHandling(PEAR_ERROR_DIE);
     $tpl_dir = $this->config->get('data_dir') . DIRECTORY_SEPARATOR . 'PEAR_Frontend_Web' . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'templates';
     if (!file_exists($tpl_dir) || !is_readable($tpl_dir)) {
         PEAR::raiseError('<b>Error:</b> the template directory <i>(' . $tpl_dir . ')</i> is not a directory, or not readable. Make sure the \'data_dir\' of your config file <i>(' . $this->config->get('data_dir') . ')</i> points to the correct location !');
     }
     $tpl = new HTML_Template_IT($tpl_dir);
     $tpl->loadTemplateFile($file);
     $tpl->setVariable("InstallerURL", $_SERVER["PHP_SELF"]);
     PEAR::staticPopErrorHandling();
     // reset error handling
     return $tpl;
 }
Example #13
0
 /**
  */
 public static function disableConversion()
 {
     $oldErrorReportingLevel = error_reporting(error_reporting() & ~E_STRICT);
     PEAR::staticPopErrorHandling();
     error_reporting($oldErrorReportingLevel);
 }
 /**
  * Added handling any errors caused by queries send from DataObjects to database
  *
  * @param string $string  Query
  * @return PEAR_Error or mixed none
  */
 function _query($string)
 {
     $production = empty($GLOBALS['_MAX']['CONF']['debug']['production']) ? false : true;
     if ($production) {
         // supress any PEAR errors if in production
         PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     }
     // execute query
     $ret = parent::_query($string);
     if ($production) {
         PEAR::staticPopErrorHandling();
     }
     if (PEAR::isError($ret)) {
         if (!$production) {
             $GLOBALS['_MAX']['ERRORS'][] = $ret;
         }
         if ($this->triggerSqlDie && function_exists('phpAds_sqlDie')) {
             $GLOBALS['phpAds_last_query'] = $string;
             if (empty($GLOBALS['_MAX']['PAN']['DB'])) {
                 $GLOBALS['_MAX']['PAN']['DB'] = $GLOBALS['_DB_DATAOBJECT']['CONNECTIONS'][$this->_database_dsn_md5];
             }
             phpAds_sqlDie();
         }
     }
     return $ret;
 }
Example #15
0
 /**
  * create a new {@link Net_UserAgent_Mobile_Common} subclass instance
  *
  * parses HTTP headers and constructs {@link Net_UserAgent_Mobile_Common}
  * subclass instance.
  * If no argument is supplied, $_SERVER{'HTTP_*'} is used.
  *
  * @param string $userAgent User-Agent string
  * @return Net_UserAgent_Mobile_Common a newly created or an existing
  *     Net_UserAgent_Mobile_Common object
  * @throws Net_UserAgent_Mobile_Error
  */
 function &factory($userAgent = null)
 {
     if (is_null($userAgent)) {
         $userAgent = @$_SERVER['HTTP_USER_AGENT'];
     }
     // parse User-Agent string
     if (Net_UserAgent_Mobile::isDoCoMo($userAgent)) {
         $driver = 'DoCoMo';
     } elseif (Net_UserAgent_Mobile::isEZweb($userAgent)) {
         $driver = 'EZweb';
     } elseif (Net_UserAgent_Mobile::isSoftBank($userAgent)) {
         $driver = 'SoftBank';
     } elseif (Net_UserAgent_Mobile::isWillcom($userAgent)) {
         $driver = 'Willcom';
     } else {
         $driver = 'NonMobile';
     }
     $class = "Net_UserAgent_Mobile_{$driver}";
     if (!class_exists($class)) {
         $file = dirname(__FILE__) . "/Mobile/{$driver}.php";
         if (!(include_once $file)) {
             return PEAR::raiseError(null, NET_USERAGENT_MOBILE_ERROR_NOT_FOUND, null, null, "Unable to include the {$file} file", 'Net_UserAgent_Mobile_Error', true);
         }
     }
     PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     $instance = new $class($userAgent);
     PEAR::staticPopErrorHandling();
     $error =& $instance->getError();
     if (Net_UserAgent_Mobile::isError($error)) {
         if ($GLOBALS['NET_USERAGENT_MOBILE_FallbackOnNomatch'] && $error->getCode() == NET_USERAGENT_MOBILE_ERROR_NOMATCH) {
             $instance =& Net_UserAgent_Mobile::factory('Net_UserAgent_Mobile_Fallback_On_NoMatch');
             return $instance;
         }
         return PEAR::raiseError($error);
     }
     return $instance;
 }
Example #16
0
 static function filename($profile, $basename, $mimetype)
 {
     require_once 'MIME/Type/Extension.php';
     // We have to temporarily disable auto handling of PEAR errors...
     PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     $mte = new MIME_Type_Extension();
     $ext = $mte->getExtension($mimetype);
     if (PEAR::isError($ext)) {
         $ext = strtolower(preg_replace('/\\W/', '', $mimetype));
     }
     // Restore error handling.
     PEAR::staticPopErrorHandling();
     $nickname = $profile->nickname;
     $datestamp = strftime('%Y%m%dT%H%M%S', time());
     $random = strtolower(common_confirmation_code(32));
     return "{$nickname}-{$datestamp}-{$random}.{$ext}";
 }
Example #17
0
 /**
  * Validate XML package definition file.
  *
  * @param  string $info Filename of the package archive or of the
  *                package definition file
  * @param  array $errors Array that will contain the errors
  * @param  array $warnings Array that will contain the warnings
  * @param  string $dir_prefix (optional) directory where source files
  *                may be found, or empty if they are not available
  * @access public
  * @return boolean
  * @deprecated use the validation of PEAR_PackageFile objects
  */
 function validatePackageInfo($info, &$errors, &$warnings, $dir_prefix = '')
 {
     include_once 'PEAR/PackageFile.php';
     include_once 'PEAR/Config.php';
     $config =& PEAR_Config::singleton();
     $packagefile =& new PEAR_PackageFile($config);
     PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     if (is_array($info)) {
         $pf =& $packagefile->fromArray($info);
         if (!$pf->validate(PEAR_VALIDATE_NORMAL)) {
             foreach ($pf->getValidationWarnings() as $err) {
                 if ($error['level'] == 'error') {
                     $errors[] = $error['message'];
                 } else {
                     $warnings[] = $error['message'];
                 }
             }
             return false;
         }
     } else {
         $pf =& $packagefile->fromAnyFile($info, PEAR_VALIDATE_NORMAL);
     }
     PEAR::staticPopErrorHandling();
     if (PEAR::isError($pf)) {
         $errs = $pf->getUserinfo();
         if (is_array($errs)) {
             foreach ($errs as $error) {
                 if ($error['level'] == 'error') {
                     $errors[] = $error['message'];
                 } else {
                     $warnings[] = $error['message'];
                 }
             }
         }
         return false;
     }
     return true;
 }
Example #18
0
 /**
  * Executes a query.
  *
  * @param string                $query
  * @param MDB2_Statement_Common $sth
  * @return MDB2_Result_Common|integer
  * @throws PIECE_ORM_ERROR_CANNOT_INVOKE
  * @throws PIECE_ORM_ERROR_UNEXPECTED_VALUE
  * @throws PIECE_ORM_ERROR_CONSTRAINT
  */
 function &execute($query, $sth)
 {
     $dbh =& $this->_mapper->getConnection();
     PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     if (!$this->_isManip) {
         $result =& $dbh->query($query);
     } else {
         if (is_null($sth)) {
             $result = $dbh->exec($query);
         } else {
             if (!is_subclass_of($sth, 'MDB2_Statement_Common')) {
                 PEAR::staticPopErrorHandling();
                 Piece_ORM_Error::push(PIECE_ORM_ERROR_UNEXPECTED_VALUE, 'An unexpected value detected. executeQuery() with a prepared statement can only receive a MDB2_Statement_Common object.');
                 $return = null;
                 return $return;
             }
             $result = $sth->execute();
         }
     }
     PEAR::staticPopErrorHandling();
     $this->_mapper->setLastQuery($dbh->last_query);
     if (MDB2::isError($result)) {
         if ($result->getCode() == MDB2_ERROR_CONSTRAINT) {
             $code = PIECE_ORM_ERROR_CONSTRAINT;
         } else {
             $code = PIECE_ORM_ERROR_CANNOT_INVOKE;
         }
         Piece_ORM_Error::pushPEARError($result, $code, "Failed to invoke MDB2_Driver_{$dbh->phptype}::query() for any reasons.");
         $return = null;
         return $return;
     }
     return $result;
 }
Example #19
0
 /**
  * @param array dependency array
  * @access private
  */
 function _getDepPackageDownloadUrl($dep, $parr)
 {
     $xsdversion = isset($dep['rel']) ? '1.0' : '2.0';
     $curchannel = $this->config->get('default_channel');
     if (isset($dep['channel'])) {
         $remotechannel = $dep['channel'];
     } else {
         $remotechannel = 'pear.php.net';
     }
     if (!$this->_registry->channelExists($remotechannel)) {
         do {
             if ($this->config->get('auto_discover')) {
                 if ($this->discover($remotechannel)) {
                     break;
                 }
             }
             return PEAR::raiseError('Unknown remote channel: ' . $remotechannel);
         } while (false);
     }
     $this->configSet('default_channel', $remotechannel);
     $state = isset($parr['state']) ? $parr['state'] : $this->config->get('preferred_state');
     if (isset($parr['state']) && isset($parr['version'])) {
         unset($parr['state']);
     }
     $chan =& $this->_registry->getChannel($remotechannel);
     if (PEAR::isError($chan)) {
         return $chan;
     }
     $version = $this->_registry->packageInfo($dep['name'], 'version', $remotechannel);
     if ($chan->supportsREST($this->config->get('preferred_mirror')) && ($base = $chan->getBaseURL('REST1.0', $this->config->get('preferred_mirror')))) {
         $rest =& $this->config->getREST('1.0', $this->_options);
         $url = $rest->getDepDownloadURL($base, $xsdversion, $dep, $parr, $state, $version);
         if (PEAR::isError($url)) {
             return $url;
         }
         if ($parr['channel'] != $curchannel) {
             $this->configSet('default_channel', $curchannel);
         }
         if (!is_array($url)) {
             return $url;
         }
         $url['raw'] = false;
         // no checking is necessary for REST
         if (!is_array($url['info'])) {
             return PEAR::raiseError('Invalid remote dependencies retrieved from REST - ' . 'this should never happen');
         }
         if (isset($url['info']['required'])) {
             if (!class_exists('PEAR_PackageFile_v2')) {
                 require_once 'PEAR/PackageFile/v2.php';
             }
             $pf = new PEAR_PackageFile_v2();
             $pf->setRawChannel($remotechannel);
         } else {
             if (!class_exists('PEAR_PackageFile_v1')) {
                 require_once 'PEAR/PackageFile/v1.php';
             }
             $pf = new PEAR_PackageFile_v1();
         }
         $pf->setRawPackage($url['package']);
         $pf->setDeps($url['info']);
         $pf->setRawState($url['stability']);
         $url['info'] =& $pf;
         if (!extension_loaded("zlib") || isset($this->_options['nocompress'])) {
             $ext = '.tar';
         } else {
             $ext = '.tgz';
         }
         if (is_array($url)) {
             if (isset($url['url'])) {
                 $url['url'] .= $ext;
             }
         }
         return $url;
     } elseif ($chan->supports('xmlrpc', 'package.getDepDownloadURL', false, '1.1')) {
         if ($version) {
             $url = $this->_remote->call('package.getDepDownloadURL', $xsdversion, $dep, $parr, $state, $version);
         } else {
             $url = $this->_remote->call('package.getDepDownloadURL', $xsdversion, $dep, $parr, $state);
         }
     } else {
         $url = $this->_remote->call('package.getDepDownloadURL', $xsdversion, $dep, $parr, $state);
     }
     if ($parr['channel'] != $curchannel) {
         $this->configSet('default_channel', $curchannel);
     }
     if (!is_array($url)) {
         return $url;
     }
     if (isset($url['__PEAR_ERROR_CLASS__'])) {
         return PEAR::raiseError($url['message']);
     }
     $url['raw'] = $url['info'];
     $pkg =& $this->getPackagefileObject($this->config, $this->debug);
     PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     $pinfo =& $pkg->fromXmlString($url['info'], PEAR_VALIDATE_DOWNLOADING, 'remote');
     PEAR::staticPopErrorHandling();
     if (PEAR::isError($pinfo)) {
         if (!isset($this->_options['soft'])) {
             $this->log(0, $pinfo->getMessage());
         }
         return PEAR::raiseError('Remote package.xml is not valid - this should never happen');
     }
     $url['info'] =& $pinfo;
     if (is_array($url)) {
         if (!extension_loaded("zlib") || isset($this->_options['nocompress'])) {
             $ext = '.tar';
         } else {
             $ext = '.tgz';
         }
         if (isset($url['url'])) {
             $url['url'] .= $ext;
         }
     }
     return $url;
 }
Example #20
0
 /**
  * Loads a value with a result object.
  *
  * @param MDB2_Result &$result
  * @return string
  * @throws PIECE_ORM_ERROR_CANNOT_INVOKE
  * @since Method available since Release 0.3.0
  */
 function _loadValue(&$result)
 {
     PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     $value = $result->fetchOne();
     PEAR::staticPopErrorHandling();
     if (MDB2::isError($value)) {
         Piece_ORM_Error::pushPEARError($value, PIECE_ORM_ERROR_CANNOT_INVOKE, "Failed to invoke MDB2_Driver_{$this->_dbh->phptype}::fetchOne() for any reasons.");
         return;
     }
     return $value;
 }
 function doConvert($command, $options, $params)
 {
     $packagexml = isset($params[0]) ? $params[0] : 'package.xml';
     $newpackagexml = isset($params[1]) ? $params[1] : dirname($packagexml) . DIRECTORY_SEPARATOR . 'package2.xml';
     $pkg =& $this->getPackageFile($this->config, $this->_debug);
     PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     $pf = $pkg->fromPackageFile($packagexml, PEAR_VALIDATE_NORMAL);
     PEAR::staticPopErrorHandling();
     if (!PEAR::isError($pf)) {
         if (is_a($pf, 'PEAR_PackageFile_v2')) {
             $this->ui->outputData($packagexml . ' is already a package.xml version 2.0');
             return true;
         }
         $gen =& $pf->getDefaultGenerator();
         $newpf =& $gen->toV2();
         $newpf->setPackagefile($newpackagexml);
         $gen =& $newpf->getDefaultGenerator();
         PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
         $state = isset($options['flat']) ? PEAR_VALIDATE_PACKAGING : PEAR_VALIDATE_NORMAL;
         $saved = $gen->toPackageFile(dirname($newpackagexml), $state, basename($newpackagexml));
         PEAR::staticPopErrorHandling();
         if (PEAR::isError($saved)) {
             if (is_array($saved->getUserInfo())) {
                 foreach ($saved->getUserInfo() as $warning) {
                     $this->ui->outputData($warning['message']);
                 }
             }
             $this->ui->outputData($saved->getMessage());
             return true;
         }
         $this->ui->outputData('Wrote new version 2.0 package.xml to "' . $saved . '"');
         return true;
     } else {
         if (is_array($pf->getUserInfo())) {
             foreach ($pf->getUserInfo() as $warning) {
                 $this->ui->outputData($warning['message']);
             }
         }
         return $this->raiseError($pf);
     }
 }
 /**
  * Checks that the dependency is valid.
  *
  * @param  array   $dependency A dependency array
  *
  * @return Boolean true if the dependency is valid, false otherwise
  */
 protected function checkDependency($dependency)
 {
     $dependencyChecker = new PEAR_Dependency2($this->environment->getConfig(), array(), array('package' => '', 'channel' => ''));
     PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     $e = $dependencyChecker->validatePackageDependency($dependency, true, array());
     PEAR::staticPopErrorHandling();
     if (PEAR::isError($e)) {
         return false;
     }
     return true;
 }
 /**
  * Given a list of packages, filter out those ones that are already up to date
  *
  * @param $packages: packages, in parsed array format !
  * @return list of packages that can be upgraded
  */
 function _filterUptodatePackages($packages, $command)
 {
     $reg =& $this->config->getRegistry();
     $latestReleases = array();
     $ret = array();
     foreach ($packages as $package) {
         if (isset($package['group'])) {
             $ret[] = $package;
             continue;
         }
         $channel = $package['channel'];
         $name = $package['package'];
         if (!$reg->packageExists($name, $channel)) {
             $ret[] = $package;
             continue;
         }
         if (!isset($latestReleases[$channel])) {
             // fill in cache for this channel
             $chan =& $reg->getChannel($channel);
             if (PEAR::isError($chan)) {
                 return $this->raiseError($chan);
             }
             if ($chan->supportsREST($this->config->get('preferred_mirror', null, $channel)) && ($base = $chan->getBaseURL('REST1.0', $this->config->get('preferred_mirror', null, $channel)))) {
                 $dorest = true;
             } else {
                 $dorest = false;
                 $remote =& $this->config->getRemote($this->config);
             }
             PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
             if ($dorest) {
                 $rest =& $this->config->getREST('1.0', array());
                 $installed = array_flip($reg->listPackages($channel));
                 $latest = $rest->listLatestUpgrades($base, $this->config->get('preferred_state', null, $channel), $installed, $channel, $reg);
             } else {
                 $latest = $remote->call("package.listLatestReleases", $this->config->get('preferred_state', null, $channel));
                 unset($remote);
             }
             PEAR::staticPopErrorHandling();
             if (PEAR::isError($latest)) {
                 $this->ui->outputData('Error getting channel info from ' . $channel . ': ' . $latest->getMessage());
                 continue;
             }
             $latestReleases[$channel] = array_change_key_case($latest);
         }
         // check package for latest release
         if (isset($latestReleases[$channel][strtolower($name)])) {
             // if not set, up to date
             $inst_version = $reg->packageInfo($name, 'version', $channel);
             $channel_version = $latestReleases[$channel][strtolower($name)]['version'];
             if (version_compare($channel_version, $inst_version, "le")) {
                 // installed version is up-to-date
                 continue;
             }
             // maintain BC
             if ($command == 'upgrade-all') {
                 $this->ui->outputData(array('data' => 'Will upgrade ' . $reg->parsedPackageNameToString($package)), $command);
             }
             $ret[] = $package;
         }
     }
     return $ret;
 }
 function doRunScripts($command, $options, $params)
 {
     if (!isset($params[0])) {
         return $this->raiseError('run-scripts expects 1 parameter: a package name');
     }
     $reg =& $this->config->getRegistry();
     PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     $parsed = $reg->parsePackageName($params[0], $this->config->get('default_channel'));
     PEAR::staticPopErrorHandling();
     if (PEAR::isError($parsed)) {
         return $this->raiseError($parsed);
     }
     $package =& $reg->getPackage($parsed['package'], $parsed['channel']);
     if (is_object($package)) {
         $package->setConfig($this->config);
         $package->runPostinstallScripts();
     } else {
         return $this->raiseError('Could not retrieve package "' . $params[0] . '" from registry');
     }
     $this->ui->outputData('Install scripts complete', $command);
     return true;
 }
Example #25
0
$config->set('preferred_state', 'stable');
foreach ($config_vars as $var) {
    if (isset(${$var}) && ${$var} != '') {
        $config->set($var, ${$var});
    }
}
$config->set('download_dir', $temp_dir . '/download');
$config->set('temp_dir', $temp_dir);
$config->store();
$registry = new PEAR_Registry($php_dir);
PEAR_Command::setFrontendType('CLI');
PEAR::staticPushErrorHandling(PEAR_ERROR_DIE);
//fail silently
$ch_cmd =& PEAR_Command::factory('update-channels', $config);
$ch_cmd->run('update-channels', $options, array());
PEAR::staticPopErrorHandling();
// reset error handling
unset($ch_cmd);
print "\n" . 'Installing selected packages..................' . "\n";
displayHTMLProgress($progress = 45);
$install =& PEAR_Command::factory('install', $config);
foreach ($to_install as $pkg) {
    $pkg_basename = substr($pkg, 0, strpos($pkg, '-'));
    if (in_array($pkg, $installer_packages)) {
        $options = array('nodeps' => true);
    } else {
        $options = array('onlyreqdeps' => true);
    }
    if ($registry->packageExists($pkg) || $registry->packageExists($pkg_basename)) {
        print str_pad("Package: {$pkg}", max(50, 9 + strlen($pkg) + 4), '.') . ' already installed ... ok' . "\n";
        displayHTMLProgress($progress += round(50 / count($to_install)));
Example #26
0
 function doUpdate($command, $options, $params)
 {
     $tmpdir = $this->config->get('temp_dir');
     if (!file_exists($tmpdir)) {
         require_once 'System.php';
         PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
         $err = System::mkdir(array('-p', $tmpdir));
         PEAR::staticPopErrorHandling();
         if (PEAR::isError($err)) {
             return $this->raiseError('channel-add: temp_dir does not exist: "' . $tmpdir . '" - You can change this location with "pear config-set temp_dir"');
         }
     }
     if (!is_writable($tmpdir)) {
         return $this->raiseError('channel-add: temp_dir is not writable: "' . $tmpdir . '" - You can change this location with "pear config-set temp_dir"');
     }
     $reg =& $this->config->getRegistry();
     if (sizeof($params) != 1) {
         return $this->raiseError("No channel file specified");
     }
     $lastmodified = false;
     if ((!file_exists($params[0]) || is_dir($params[0])) && $reg->channelExists(strtolower($params[0]))) {
         $c = $reg->getChannel(strtolower($params[0]));
         if (PEAR::isError($c)) {
             return $this->raiseError($c);
         }
         $this->ui->outputData("Updating channel \"{$params['0']}\"", $command);
         $dl =& $this->getDownloader(array());
         // if force is specified, use a timestamp of "1" to force retrieval
         $lastmodified = isset($options['force']) ? false : $c->lastModified();
         PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
         $contents = $dl->downloadHttp('http://' . $c->getName() . '/channel.xml', $this->ui, $tmpdir, null, $lastmodified);
         PEAR::staticPopErrorHandling();
         if (PEAR::isError($contents)) {
             return $this->raiseError('Cannot retrieve channel.xml for channel "' . $c->getName() . '" (' . $contents->getMessage() . ')');
         }
         list($contents, $lastmodified) = $contents;
         if (!$contents) {
             $this->ui->outputData("Channel \"{$params['0']}\" is up to date");
             return;
         }
         $contents = implode('', file($contents));
         if (!class_exists('PEAR_ChannelFile')) {
             require_once 'PEAR/ChannelFile.php';
         }
         $channel = new PEAR_ChannelFile();
         $channel->fromXmlString($contents);
         if (!$channel->getErrors()) {
             // security check: is the downloaded file for the channel we got it from?
             if (strtolower($channel->getName()) != strtolower($c->getName())) {
                 if (isset($options['force'])) {
                     $this->ui->log(0, 'WARNING: downloaded channel definition file' . ' for channel "' . $channel->getName() . '" from channel "' . strtolower($c->getName()) . '"');
                 } else {
                     return $this->raiseError('ERROR: downloaded channel definition file' . ' for channel "' . $channel->getName() . '" from channel "' . strtolower($c->getName()) . '"');
                 }
             }
         }
     } else {
         if (strpos($params[0], '://')) {
             $dl =& $this->getDownloader();
             PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
             $loc = $dl->downloadHttp($params[0], $this->ui, $tmpdir, null, $lastmodified);
             PEAR::staticPopErrorHandling();
             if (PEAR::isError($loc)) {
                 return $this->raiseError("Cannot open " . $params[0] . ' (' . $loc->getMessage() . ')');
             } else {
                 list($loc, $lastmodified) = $loc;
                 $contents = implode('', file($loc));
             }
         } else {
             $fp = false;
             if (file_exists($params[0])) {
                 $fp = fopen($params[0], 'r');
             }
             if (!$fp) {
                 return $this->raiseError("Cannot open " . $params[0]);
             }
             $contents = '';
             while (!feof($fp)) {
                 $contents .= fread($fp, 1024);
             }
             fclose($fp);
         }
         if (!class_exists('PEAR_ChannelFile')) {
             require_once 'PEAR/ChannelFile.php';
         }
         $channel = new PEAR_ChannelFile();
         $channel->fromXmlString($contents);
     }
     $exit = false;
     if (count($errors = $channel->getErrors(true))) {
         foreach ($errors as $error) {
             $this->ui->outputData(ucfirst($error['level'] . ': ' . $error['message']));
             if (!$exit) {
                 $exit = $error['level'] == 'error' ? true : false;
             }
         }
         if ($exit) {
             return $this->raiseError('Invalid channel.xml file');
         }
     }
     if (!$reg->channelExists($channel->getName())) {
         return $this->raiseError('Error: Channel "' . $channel->getName() . '" does not exist, use channel-add to add an entry');
     }
     $ret = $reg->updateChannel($channel, $lastmodified);
     if (PEAR::isError($ret)) {
         return $ret;
     }
     if (!$ret) {
         return $this->raiseError('Updating Channel "' . $channel->getName() . '" in registry failed');
     }
     $this->config->setChannels($reg->listChannels());
     $this->config->writeConfigFile();
     $this->ui->outputData('Update of Channel "' . $channel->getName() . '" succeeded');
 }
Example #27
0
 /**
  * Validate XML package definition file.
  *
  * @param  string $info Filename of the package archive or of the
  *                package definition file
  * @param  array $errors Array that will contain the errors
  * @param  array $warnings Array that will contain the warnings
  * @param  string $dir_prefix (optional) directory where source files
  *                may be found, or empty if they are not available
  * @access public
  * @return boolean
  * @deprecated use the validation of PEAR_PackageFile objects
  */
 function validatePackageInfo($info, &$errors, &$warnings, $dir_prefix = '')
 {
     $config =& PEAR_Config::singleton();
     $packagefile =& new PEAR_PackageFile($config);
     PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     if (strpos($info, '<?xml') !== false) {
         $pf =& $packagefile->fromXmlString($info, PEAR_VALIDATE_NORMAL, '');
     } else {
         $pf =& $packagefile->fromAnyFile($info, PEAR_VALIDATE_NORMAL);
     }
     PEAR::staticPopErrorHandling();
     if (PEAR::isError($pf)) {
         $errs = $pf->getUserinfo();
         if (is_array($errs)) {
             foreach ($errs as $error) {
                 if ($error['level'] == 'error') {
                     $errors[] = $error['message'];
                 } else {
                     $warnings[] = $error['message'];
                 }
             }
         }
         return false;
     }
     return true;
 }
Example #28
0
 function doInfo($command, $options, $params)
 {
     if (count($params) !== 1) {
         return $this->raiseError('pear info expects 1 parameter');
     }
     $info = $fp = false;
     $reg =& $this->config->getRegistry();
     if (file_exists($params[0]) && is_file($params[0]) && !is_dir($params[0]) || ($fp = @fopen($params[0], 'r'))) {
         if ($fp) {
             fclose($fp);
         }
         if (!class_exists('PEAR_PackageFile')) {
             require_once 'PEAR/PackageFile.php';
         }
         $pkg =& new PEAR_PackageFile($this->config, $this->_debug);
         PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
         $obj =& $pkg->fromAnyFile($params[0], PEAR_VALIDATE_NORMAL);
         PEAR::staticPopErrorHandling();
         if (PEAR::isError($obj)) {
             $uinfo = $obj->getUserInfo();
             if (is_array($uinfo)) {
                 foreach ($uinfo as $message) {
                     if (is_array($message)) {
                         $message = $message['message'];
                     }
                     $this->ui->outputData($message);
                 }
             }
             return $this->raiseError($obj);
         }
         if ($obj->getPackagexmlVersion() != '1.0') {
             return $this->_doInfo2($command, $options, $params, $obj, false);
         }
         $info = $obj->toArray();
     } else {
         $parsed = $reg->parsePackageName($params[0], $this->config->get('default_channel'));
         if (PEAR::isError($parsed)) {
             return $this->raiseError($parsed);
         }
         $package = $parsed['package'];
         $channel = $parsed['channel'];
         $info = $reg->packageInfo($package, null, $channel);
         if (isset($info['old'])) {
             $obj = $reg->getPackage($package, $channel);
             return $this->_doInfo2($command, $options, $params, $obj, true);
         }
     }
     if (PEAR::isError($info)) {
         return $info;
     }
     if (empty($info)) {
         $this->raiseError("No information found for `{$params['0']}'");
         return;
     }
     unset($info['filelist']);
     unset($info['dirtree']);
     unset($info['changelog']);
     if (isset($info['xsdversion'])) {
         $info['package.xml version'] = $info['xsdversion'];
         unset($info['xsdversion']);
     }
     if (isset($info['packagerversion'])) {
         $info['packaged with PEAR version'] = $info['packagerversion'];
         unset($info['packagerversion']);
     }
     $keys = array_keys($info);
     $longtext = array('description', 'summary');
     foreach ($keys as $key) {
         if (is_array($info[$key])) {
             switch ($key) {
                 case 'maintainers':
                     $i = 0;
                     $mstr = '';
                     foreach ($info[$key] as $m) {
                         if ($i++ > 0) {
                             $mstr .= "\n";
                         }
                         $mstr .= $m['name'] . " <";
                         if (isset($m['email'])) {
                             $mstr .= $m['email'];
                         } else {
                             $mstr .= $m['handle'] . '@php.net';
                         }
                         $mstr .= "> ({$m['role']})";
                     }
                     $info[$key] = $mstr;
                     break;
                 case 'release_deps':
                     $i = 0;
                     $dstr = '';
                     foreach ($info[$key] as $d) {
                         if (isset($this->_deps_rel_trans[$d['rel']])) {
                             $rel = $this->_deps_rel_trans[$d['rel']];
                         } else {
                             $rel = $d['rel'];
                         }
                         if (isset($this->_deps_type_trans[$d['type']])) {
                             $type = ucfirst($this->_deps_type_trans[$d['type']]);
                         } else {
                             $type = $d['type'];
                         }
                         if (isset($d['name'])) {
                             $name = $d['name'] . ' ';
                         } else {
                             $name = '';
                         }
                         if (isset($d['version'])) {
                             $version = $d['version'] . ' ';
                         } else {
                             $version = '';
                         }
                         if (isset($d['optional']) && $d['optional'] == 'yes') {
                             $optional = ' (optional)';
                         } else {
                             $optional = '';
                         }
                         $dstr .= "{$type} {$name}{$rel} {$version}{$optional}\n";
                     }
                     $info[$key] = $dstr;
                     break;
                 case 'provides':
                     $debug = $this->config->get('verbose');
                     if ($debug < 2) {
                         $pstr = 'Classes: ';
                     } else {
                         $pstr = '';
                     }
                     $i = 0;
                     foreach ($info[$key] as $p) {
                         if ($debug < 2 && $p['type'] != "class") {
                             continue;
                         }
                         // Only print classes when verbosity mode is < 2
                         if ($debug < 2) {
                             if ($i++ > 0) {
                                 $pstr .= ", ";
                             }
                             $pstr .= $p['name'];
                         } else {
                             if ($i++ > 0) {
                                 $pstr .= "\n";
                             }
                             $pstr .= ucfirst($p['type']) . " " . $p['name'];
                             if (isset($p['explicit']) && $p['explicit'] == 1) {
                                 $pstr .= " (explicit)";
                             }
                         }
                     }
                     $info[$key] = $pstr;
                     break;
                 case 'configure_options':
                     foreach ($info[$key] as $i => $p) {
                         $info[$key][$i] = array_map(null, array_keys($p), array_values($p));
                         $info[$key][$i] = array_map(create_function('$a', 'return join(" = ",$a);'), $info[$key][$i]);
                         $info[$key][$i] = implode(', ', $info[$key][$i]);
                     }
                     $info[$key] = implode("\n", $info[$key]);
                     break;
                 default:
                     $info[$key] = implode(", ", $info[$key]);
                     break;
             }
         }
         if ($key == '_lastmodified') {
             $hdate = date('Y-m-d', $info[$key]);
             unset($info[$key]);
             $info['Last Modified'] = $hdate;
         } elseif ($key == '_lastversion') {
             $info['Previous Installed Version'] = $info[$key] ? $info[$key] : '- None -';
             unset($info[$key]);
         } else {
             $info[$key] = trim($info[$key]);
             if (in_array($key, $longtext)) {
                 $info[$key] = preg_replace('/  +/', ' ', $info[$key]);
             }
         }
     }
     $caption = 'About ' . $info['package'] . '-' . $info['version'];
     $data = array('caption' => $caption, 'border' => true);
     foreach ($info as $key => $value) {
         $key = ucwords(trim(str_replace('_', ' ', $key)));
         $data['data'][] = array($key, $value);
     }
     $data['raw'] = $info;
     $this->ui->outputData($data, 'package-info');
 }
Example #29
0
 function doListUpgrades($command, $options, $params)
 {
     require_once 'PEAR/Common.php';
     if (isset($params[0]) && !is_array(PEAR_Common::betterStates($params[0]))) {
         return $this->raiseError($params[0] . ' is not a valid state (stable/beta/alpha/devel/etc.) try "pear help list-upgrades"');
     }
     $savechannel = $channel = $this->config->get('default_channel');
     $reg =& $this->config->getRegistry();
     foreach ($reg->listChannels() as $channel) {
         $inst = array_flip($reg->listPackages($channel));
         if (!count($inst)) {
             continue;
         }
         if ($channel == '__uri') {
             continue;
         }
         $this->config->set('default_channel', $channel);
         if (empty($params[0])) {
             $state = $this->config->get('preferred_state');
         } else {
             $state = $params[0];
         }
         $caption = $channel . ' Available Upgrades';
         $chan = $reg->getChannel($channel);
         if (PEAR::isError($e = $this->_checkChannelForStatus($channel, $chan))) {
             return $e;
         }
         if ($chan->supportsREST($this->config->get('preferred_mirror')) && ($base = $chan->getBaseURL('REST1.0', $this->config->get('preferred_mirror')))) {
             $rest =& $this->config->getREST('1.0', array());
             if (empty($state) || $state == 'any') {
                 $state = false;
             } else {
                 $caption .= ' (' . implode(', ', PEAR_Common::betterStates($state, true)) . ')';
             }
             PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
             $latest = $rest->listLatestUpgrades($base, $state, $inst, $channel, $reg);
             PEAR::staticPopErrorHandling();
         } else {
             $remote =& $this->config->getRemote();
             $remote->pushErrorHandling(PEAR_ERROR_RETURN);
             if (empty($state) || $state == 'any') {
                 $latest = $remote->call("package.listLatestReleases");
             } else {
                 $latest = $remote->call("package.listLatestReleases", $state);
                 $caption .= ' (' . implode(', ', PEAR_Common::betterStates($state, true)) . ')';
             }
             $remote->popErrorHandling();
         }
         if (PEAR::isError($latest)) {
             $this->ui->outputData($latest->getMessage());
             continue;
         }
         $caption .= ':';
         if (PEAR::isError($latest)) {
             $this->config->set('default_channel', $savechannel);
             return $latest;
         }
         $data = array('caption' => $caption, 'border' => 1, 'headline' => array('Channel', 'Package', 'Local', 'Remote', 'Size'), 'channel' => $channel);
         foreach ((array) $latest as $pkg => $info) {
             $package = strtolower($pkg);
             if (!isset($inst[$package])) {
                 // skip packages we don't have installed
                 continue;
             }
             extract($info);
             $inst_version = $reg->packageInfo($package, 'version', $channel);
             $inst_state = $reg->packageInfo($package, 'release_state', $channel);
             if (version_compare("{$version}", "{$inst_version}", "le")) {
                 // installed version is up-to-date
                 continue;
             }
             if ($filesize >= 20480) {
                 $filesize += 1024 - $filesize % 1024;
                 $fs = sprintf("%dkB", $filesize / 1024);
             } elseif ($filesize > 0) {
                 $filesize += 103 - $filesize % 103;
                 $fs = sprintf("%.1fkB", $filesize / 1024.0);
             } else {
                 $fs = "  -";
                 // XXX center instead
             }
             $data['data'][] = array($channel, $pkg, "{$inst_version} ({$inst_state})", "{$version} ({$state})", $fs);
         }
         if (isset($options['channelinfo'])) {
             if (empty($data['data'])) {
                 unset($data['headline']);
                 if (count($inst) == 0) {
                     $data['data'] = '(no packages installed)';
                 } else {
                     $data['data'] = '(no upgrades available)';
                 }
             }
             $this->ui->outputData($data, $command);
         } else {
             if (empty($data['data'])) {
                 $this->ui->outputData('Channel ' . $channel . ': No upgrades available');
             } else {
                 $this->ui->outputData($data, $command);
             }
         }
     }
     $this->config->set('default_channel', $savechannel);
     return true;
 }
    function doListCategories($command, $options, $params)
    {
        $reg = &$this->config->getRegistry();
        if (isset($options['allchannels']) && $options['allchannels'] == true) {
            // over all channels
            unset($options['allchannels']);
            $channels = $reg->getChannels();
            $errors = array();
            foreach ($channels as $channel) {
                if ($channel->getName() != '__uri') {
                    $options['channel'] = $channel->getName();
                    $ret = $this->doListCategories($command, $options, $params);
                    if ($ret !== true) {
                        $errors[] = $ret;
                    }
                }
            }
            if (count($errors) !== 0) {
                // for now, only give first error
                return $errors[0];
            }
            return true;
        }

        $savechannel = $channel = $this->config->get('default_channel');
        if (isset($options['channel'])) {
            $channel = $options['channel'];
            if ($reg->channelExists($channel)) {
                $this->config->set('default_channel', $channel);
            } else {
                return $this->raiseError("Channel \"$channel\" does not exist");
            }
        }
        $chan = $reg->getChannel($channel);
        PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
        // we need Remote::_checkChannelForStatus()
        require_once 'PEAR/Command/Remote.php';
        //$cmd = new PEAR_Command_Remote($this->ui, $this->config);
        //if (PEAR::isError($e = $cmd->_checkChannelForStatus($channel, $chan))) {
        if (PEAR::isError($e = PEAR_Command_Remote::_checkChannelForStatus($channel, $chan))) {
            return $e;
        }
        if ($chan->supportsREST($this->config->get('preferred_mirror')) &&
              $base = $chan->getBaseURL('REST1.1', $this->config->get('preferred_mirror'))) {
            $rest = &$this->config->getREST('1.1', array());
        } elseif ($chan->supportsREST($this->config->get('preferred_mirror')) &&
              $base = $chan->getBaseURL('REST1.0', $this->config->get('preferred_mirror'))) {
            $rest = &$this->config->getREST('1.0', array());
        } else {
            return PEAR::raiseError($command.' only works for REST servers');
        }
        $categories = $rest->listCategories($base);

        $data = array(
            'caption' => 'Channel ' . $channel . ' All categories:',
            'border' => true,
            'headline' => array('Channel', 'Category'),
            'channel' => $channel,
            );
        if (isset($options['packages']) && $options['packages']) {
            $data['headline'][] = 'Packages';
        }

        if (PEAR::isError($categories)) {
            unset($data['headline']);
            $data['data'] = 'The category list could not be fetched from the remote server. Please try again. (Debug info: "' . $categories->getMessage() . '")';
        } elseif (count($categories) === 0) {
            unset($data['headline']);
            $data['data'] = 'No categories registered';
        } else {
            $data['data'] = array();

            foreach($categories as $item) {
                $category = $item['_content'];
                $array = array(
                        $channel,
                        $category);

                if (isset($options['packages']) && $options['packages']) {
                    // get packagenames
                    $cat_pkgs = $rest->listCategory($base, $category);
                    if (!PEAR::isError($cat_pkgs)) {
                        $packages = array();
                        foreach($cat_pkgs as $cat_pkg) {
                            $packages[] = $cat_pkg['_content'];
                        }
                        $array[] = $packages;
                    }
                }
                $data['data'][] = $array;
            }
        }
        PEAR::staticPopErrorHandling();

        $this->config->set('default_channel', $savechannel);
        $this->ui->outputData($data, $command);
        return true;
    }