extractInString() public method

The return value is a string with the file content, or NULL on error.
public extractInString ( string $p_filename ) : a
$p_filename string The path of the file to extract in a string.
return a string with the file content or NULL.
 function testBz2()
 {
     $oTar = new Archive_Tar($this->sFileBz2, 'bz2');
     $sExpected = $oTar->extractInString('Beautifier.php');
     unset($oTar);
     $sActual = file_get_contents('tarz://' . $this->sFileBz2 . "#Beautifier.php");
     $this->assertTrue($sExpected == $sActual, 'file_get_contents');
 }
 /**
  * @param string $tar - path to tar file
  */
 public function __construct($_tar)
 {
     $tar = new Archive_Tar($_tar);
     $this->package_xml = $tar->extractInString('package.xml');
     unset($tar);
     $this->parse_package();
     $files = $this->files();
     //	$xml = simplexml_load_string(str_replace('xmlns=', 'xmlns:default=', $this->package_xml));
     //	$namespaces = $xml->getNamespaces(true);
     //	$xml->registerXPathNamespace('default', 'default');
 }
 public function installFromFile($file)
 {
     require_once "/var/www/localhost/htdocs/papyrine/libraries/PEAR.php";
     require_once "/var/www/localhost/htdocs/papyrine/libraries/Archive_Tar.php";
     $tar = new Archive_Tar($file, 'bz2');
     $about = $tar->extractInString("about.xml");
     $xml = simplexml_load_string($about);
     $dir = "/var/www/localhost/htdocs/papyrine/data/plugins/tmp/" . $xml->id . "/";
     if (!is_dir($dir)) {
         $tar->extract($dir);
     }
     $this->installFromDirectory($dir);
 }
 public function uploadPackage()
 {
     $tgz = $this->getValue('tgz_file');
     $svn = $this->getValue('svn_url');
     $gitUrl = $this->getValue('git_url');
     $gitCommit = $this->getValue('git_commit');
     $memberId = sfContext::getInstance()->getUser()->getMemberId();
     $pear = opPluginChannelServerToolkit::registerPearChannel($this->getChannel());
     if ($tgz) {
         require_once 'Archive/Tar.php';
         $info = $pear->infoFromTgzFile($tgz->getTempName());
         if ($info instanceof PEAR_Error) {
             throw new RuntimeException($info->getMessage());
         }
         $tar = new Archive_Tar($tgz->getTempName());
         $xml = '';
         foreach ($tar->listContent() as $file) {
             if ('package.xml' === $file['filename']) {
                 $xml = $tar->extractInString($file['filename']);
             }
         }
         $file = new File();
         $file->setFromValidatedFile($tgz);
         $file->save();
         $this->uploadToS3($file);
         $release = Doctrine::getTable('PluginRelease')->createByPackageInfo($info, $file, $memberId, $xml);
         $this->package->PluginRelease[] = $release;
         $this->package->save();
     } elseif ($svn) {
         $dir = $this->importFromSvn($svn);
         $this->importSCMFile($pear, $memberId, $dir);
     } elseif ($gitUrl && $gitCommit) {
         $dir = $this->importFromGit($gitUrl, $gitCommit);
         $this->importSCMFile($pear, $memberId, $dir);
     }
 }
 function getTarContent($file)
 {
     if (!preg_match("/\\.(tar|cbt)\$/", strtolower($file))) {
         return "";
     }
     $tar = new Archive_Tar($file);
     $content = "";
     $entries = $tar->listContent();
     if (count($entries)) {
         $files = array();
         foreach ($entries as $entry) {
             $name = $entry['filename'];
             if (preg_match("/\\.(png|jpeg|jpg|jpe|gif)\$/", strtolower($name))) {
                 $files[] = $name;
             }
         }
         if (count($files)) {
             sort($files);
             $content = $tar->extractInString($files[0]);
         }
     }
     unset($tar);
     return $content;
 }
示例#6
0
 function get_icon()
 {
     global $WI;
     $src = WIdirWeb . "/ipkfile.php?pack=" . $WI->settings['icon_pack'] . '&icon=' . $this->decoded_metar['icon'] . '&type=' . $WI->icon_packs[$WI->settings['icon_pack']]['formats']['format'][$WI->settings['icon_ext']];
     // Change the $before tag for this element ... append
     // class="wicon" to it.
     $wicon_before = $this->before;
     if (substr($wicon_before, -1, 1) == '>') {
         $wicon_before = substr($wicon_before, 0, strlen($wicon_before) - 1) . ' class="wicon">';
     }
     $WI->status[] = $WI->gmtime() . " wicon_before is " . htmlentities($wicon_before);
     // If the user is using IE5 or IE6 and we're using PNG images, do an IE hack because IE is retarded.
     if (preg_match('/msie\\s(5\\.[5-9]|6\\.[0-9]*).*(win)/i', $_SERVER['HTTP_USER_AGENT']) && strtolower(substr($src, -4)) == '.png') {
         // Get image Size (requires GD support in PHP)
         if (function_exists('getimagesize')) {
             $tar = new Archive_Tar(WIicondir . $WI->settings['icon_pack'] . '.ipk');
             $img = $tar->extractInString($this->decoded_metar['icon'] . $WI->icon_packs[$WI->settings['icon_pack']]['formats']['format'][$WI->settings['icon_ext']]);
             // Should never be empty in a properly designed image pack.
             if (!empty($img)) {
                 $width = imagesx($img);
                 $height = imagesy($img);
             }
         } else {
             $width = 80;
             $height = 80;
         }
         return $wicon_before . '<span style="height:' . $height . 'px; width:' . $width . 'px; display:inline-block; position:relative; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' . $src . '\', sizingMethod=\'scale\');" title="' . $this->get_status() . '"></span>' . $this->after;
     } else {
         return $wicon_before . '<img src="' . $src . '"' . $style . ' title="' . $this->get_status() . '" alt="' . $this->get_status() . '" />' . $this->after;
     }
 }
示例#7
0
<?php

define('WIdir', dirname(__FILE__));
define('WIicondir', WIdir . '/icons/');
require_once 'libraries/Tar.php';
$tar = new Archive_Tar(WIicondir . '/' . $_GET['pack'] . '.ipk');
$image = $tar->extractInString($_GET['icon'] . '.' . $_GET['type']);
header('content-type: image/' . $_GET['type']);
echo $image;
 function doMakeRPM($command, $options, $params)
 {
     require_once 'System.php';
     require_once 'Archive/Tar.php';
     if (sizeof($params) != 1) {
         return $this->raiseError("bad parameter(s), try \"help {$command}\"");
     }
     if (!file_exists($params[0])) {
         return $this->raiseError("file does not exist: {$params['0']}");
     }
     $reg =& $this->config->getRegistry();
     $pkg =& $this->getPackageFile($this->config, $this->_debug);
     $pf =& $pkg->fromAnyFile($params[0], PEAR_VALIDATE_NORMAL);
     if (PEAR::isError($pf)) {
         $u = $pf->getUserinfo();
         if (is_array($u)) {
             foreach ($u as $err) {
                 if (is_array($err)) {
                     $err = $err['message'];
                 }
                 $this->ui->outputData($err);
             }
         }
         return $this->raiseError("{$params['0']} is not a valid package");
     }
     $tmpdir = System::mktemp(array('-d', 'pear2rpm'));
     $instroot = System::mktemp(array('-d', 'pear2rpm'));
     $tmp = $this->config->get('verbose');
     $this->config->set('verbose', 0);
     $installer = $this->getInstaller($this->ui);
     require_once 'PEAR/Downloader/Package.php';
     $pack = new PEAR_Downloader_Package($installer);
     $pack->setPackageFile($pf);
     $params[0] =& $pack;
     $installer->setOptions(array('installroot' => $instroot, 'nodeps' => true, 'soft' => true));
     $installer->setDownloadedPackages($params);
     $info = $installer->install($params[0], array('installroot' => $instroot, 'nodeps' => true, 'soft' => true));
     $pkgdir = $pf->getPackage() . '-' . $pf->getVersion();
     $info['rpm_xml_dir'] = '/var/lib/pear';
     $this->config->set('verbose', $tmp);
     if (isset($options['spec-template'])) {
         $spec_template = $options['spec-template'];
     } else {
         $spec_template = '@DATA-DIR@/PEAR/template.spec';
     }
     $info['possible_channel'] = '';
     $info['extra_config'] = '';
     if (isset($options['rpm-pkgname'])) {
         $rpm_pkgname_format = $options['rpm-pkgname'];
     } else {
         if ($pf->getChannel() == 'pear.php.net' || $pf->getChannel() == 'pecl.php.net') {
             $alias = 'PEAR';
         } else {
             $chan =& $reg->getChannel($pf->getChannel());
             $alias = $chan->getAlias();
             $alias = strtoupper($alias);
             $info['possible_channel'] = $pf->getChannel() . '/';
         }
         $rpm_pkgname_format = $alias . '::%s';
     }
     $info['extra_headers'] = '';
     $info['doc_files'] = '';
     $info['files'] = '';
     $info['package2xml'] = '';
     $info['rpm_package'] = sprintf($rpm_pkgname_format, $pf->getPackage());
     $srcfiles = 0;
     foreach ($info['filelist'] as $name => $attr) {
         if (!isset($attr['role'])) {
             continue;
         }
         $name = preg_replace('![/:\\\\]!', '/', $name);
         if ($attr['role'] == 'doc') {
             $info['doc_files'] .= " {$name}";
             // Map role to the rpm vars
         } else {
             $c_prefix = '%{_libdir}/php/pear';
             switch ($attr['role']) {
                 case 'php':
                     $prefix = $c_prefix;
                     break;
                 case 'ext':
                     $prefix = '%{_libdir}/php';
                     break;
                     // XXX good place?
                 // XXX good place?
                 case 'src':
                     $srcfiles++;
                     $prefix = '%{_includedir}/php';
                     break;
                     // XXX good place?
                 // XXX good place?
                 case 'test':
                     $prefix = "{$c_prefix}/tests/" . $pf->getPackage();
                     break;
                 case 'data':
                     $prefix = "{$c_prefix}/data/" . $pf->getPackage();
                     break;
                 case 'script':
                     $prefix = '%{_bindir}';
                     break;
                 default:
                     // non-standard roles
                     $prefix = "{$c_prefix}/{$attr['role']}/" . $pf->getPackage();
                     $info['extra_config'] .= "\n        -d {$attr[role]}_dir={$c_prefix}/{$attr[role]} \\";
                     $this->ui->outputData('WARNING: role "' . $attr['role'] . '" used, ' . 'and will be installed in "' . $c_prefix . '/' . $attr['role'] . '/' . $pf->getPackage() . ' - hand-edit the final .spec if this is wrong', $command);
                     break;
             }
             $name = str_replace('\\', '/', $name);
             $info['files'] .= "{$prefix}/{$name}\n";
         }
     }
     if ($srcfiles > 0) {
         require_once 'OS/Guess.php';
         $os = new OS_Guess();
         $arch = $os->getCpu();
     } else {
         $arch = 'noarch';
     }
     $cfg = array('master_server', 'php_dir', 'ext_dir', 'doc_dir', 'bin_dir', 'data_dir', 'test_dir');
     foreach ($cfg as $k) {
         if ($k == 'master_server') {
             $chan = $reg->getChannel($pf->getChannel());
             $info[$k] = $chan->getServer();
             continue;
         }
         $info[$k] = $this->config->get($k);
     }
     $info['arch'] = $arch;
     $fp = @fopen($spec_template, "r");
     if (!$fp) {
         return $this->raiseError("could not open RPM spec file template {$spec_template}: {$php_errormsg}");
     }
     $info['package'] = $pf->getPackage();
     $info['version'] = $pf->getVersion();
     $info['release_license'] = $pf->getLicense();
     if ($pf->getDeps()) {
         if ($pf->getPackagexmlVersion() == '1.0') {
             $requires = $conflicts = array();
             foreach ($pf->getDeps() as $dep) {
                 if (isset($dep['optional']) && $dep['optional'] == 'yes') {
                     continue;
                 }
                 if ($dep['type'] != 'pkg') {
                     continue;
                 }
                 if (isset($dep['channel']) && $dep['channel'] != 'pear.php.net' && $dep['channel'] != 'pecl.php.net') {
                     $chan =& $reg->getChannel($dep['channel']);
                     $package = strtoupper($chan->getAlias()) . '::' . $dep['name'];
                 } else {
                     $package = 'PEAR::' . $dep['name'];
                 }
                 $trans = array('>' => '>', '<' => '<', '>=' => '>=', '<=' => '<=', '=' => '=', 'gt' => '>', 'lt' => '<', 'ge' => '>=', 'le' => '<=', 'eq' => '=');
                 if ($dep['rel'] == 'has') {
                     $requires[] = $package;
                 } elseif ($dep['rel'] == 'not') {
                     $conflicts[] = $package;
                 } elseif ($dep['rel'] == 'ne') {
                     $conflicts[] = $package . ' = ' . $dep['version'];
                 } elseif (isset($trans[$dep['rel']])) {
                     $requires[] = $package . ' ' . $trans[$dep['rel']] . ' ' . $dep['version'];
                 }
             }
             if (count($requires)) {
                 $info['extra_headers'] .= 'Requires: ' . implode(', ', $requires) . "\n";
             }
             if (count($conflicts)) {
                 $info['extra_headers'] .= 'Conflicts: ' . implode(', ', $conflicts) . "\n";
             }
         } else {
             $info['package2xml'] = '2';
             // tell the spec to use package2.xml
             $requires = $conflicts = array();
             $deps = $pf->getDeps(true);
             if (isset($deps['required']['package'])) {
                 if (!isset($deps['required']['package'][0])) {
                     $deps['required']['package'] = array($deps['required']['package']);
                 }
                 foreach ($deps['required']['package'] as $dep) {
                     if ($dep['channel'] != 'pear.php.net' && $dep['channel'] != 'pecl.php.net') {
                         $chan =& $reg->getChannel($dep['channel']);
                         $package = strtoupper($chan->getAlias()) . '::' . $dep['name'];
                     } else {
                         $package = 'PEAR::' . $dep['name'];
                     }
                     if (isset($dep['conflicts']) && (isset($dep['min']) || isset($dep['max']))) {
                         $deprange = array();
                         if (isset($dep['min'])) {
                             $deprange[] = array($dep['min'], '>=');
                         }
                         if (isset($dep['max'])) {
                             $deprange[] = array($dep['max'], '<=');
                         }
                         if (isset($dep['exclude'])) {
                             if (!is_array($dep['exclude']) || !isset($dep['exclude'][0])) {
                                 $dep['exclude'] = array($dep['exclude']);
                             }
                             if (count($deprange)) {
                                 $excl = $dep['exclude'];
                                 // change >= to > if excluding the min version
                                 // change <= to < if excluding the max version
                                 for ($i = 0; $i < count($excl); $i++) {
                                     if (isset($deprange[0]) && $excl[$i] == $deprange[0][0]) {
                                         $deprange[0][1] = '<';
                                         unset($dep['exclude'][$i]);
                                     }
                                     if (isset($deprange[1]) && $excl[$i] == $deprange[1][0]) {
                                         $deprange[1][1] = '>';
                                         unset($dep['exclude'][$i]);
                                     }
                                 }
                             }
                             if (count($dep['exclude'])) {
                                 $dep['exclude'] = array_values($dep['exclude']);
                                 $newdeprange = array();
                                 // remove excludes that are outside the existing range
                                 for ($i = 0; $i < count($dep['exclude']); $i++) {
                                     if ($dep['exclude'][$i] < $dep['min'] || $dep['exclude'][$i] > $dep['max']) {
                                         unset($dep['exclude'][$i]);
                                     }
                                 }
                                 $dep['exclude'] = array_values($dep['exclude']);
                                 usort($dep['exclude'], 'version_compare');
                                 // take the remaining excludes and
                                 // split the dependency into sub-ranges
                                 $lastmin = $deprange[0];
                                 for ($i = 0; $i < count($dep['exclude']) - 1; $i++) {
                                     $newdeprange[] = '(' . $package . " {$lastmin[1]} {$lastmin[0]} and " . $package . ' < ' . $dep['exclude'][$i] . ')';
                                     $lastmin = array($dep['exclude'][$i], '>');
                                 }
                                 if (isset($dep['max'])) {
                                     $newdeprange[] = '(' . $package . " {$lastmin[1]} {$lastmin[0]} and " . $package . ' < ' . $dep['max'] . ')';
                                 }
                                 $conflicts[] = implode(' or ', $deprange);
                             } else {
                                 $conflicts[] = $package . " {$deprange[0][1]} {$deprange[0][0]}" . (isset($deprange[1]) ? " and {$package} {$deprange[1][1]} {$deprange[1][0]}" : '');
                             }
                         }
                         continue;
                     }
                     if (!isset($dep['min']) && !isset($dep['max']) && !isset($dep['exclude'])) {
                         if (isset($dep['conflicts'])) {
                             $conflicts[] = $package;
                         } else {
                             $requires[] = $package;
                         }
                     } else {
                         if (isset($dep['min'])) {
                             $requires[] = $package . ' >= ' . $dep['min'];
                         }
                         if (isset($dep['max'])) {
                             $requires[] = $package . ' <= ' . $dep['max'];
                         }
                         if (isset($dep['exclude'])) {
                             $ex = $dep['exclude'];
                             if (!is_array($ex)) {
                                 $ex = array($ex);
                             }
                             foreach ($ex as $ver) {
                                 $conflicts[] = $package . ' = ' . $ver;
                             }
                         }
                     }
                 }
                 require_once 'Archive/Tar.php';
                 $tar = new Archive_Tar($pf->getArchiveFile());
                 $tar->pushErrorHandling(PEAR_ERROR_RETURN);
                 $a = $tar->extractInString('package2.xml');
                 $tar->popErrorHandling();
                 if ($a === null || PEAR::isError($a)) {
                     $info['package2xml'] = '';
                     // this doesn't have a package.xml version 1.0
                     $requires[] = 'PEAR::PEAR >= ' . $deps['required']['pearinstaller']['min'];
                 }
                 if (count($requires)) {
                     $info['extra_headers'] .= 'Requires: ' . implode(', ', $requires) . "\n";
                 }
                 if (count($conflicts)) {
                     $info['extra_headers'] .= 'Conflicts: ' . implode(', ', $conflicts) . "\n";
                 }
             }
         }
     }
     // remove the trailing newline
     $info['extra_headers'] = trim($info['extra_headers']);
     if (function_exists('file_get_contents')) {
         fclose($fp);
         $spec_contents = preg_replace('/@([a-z0-9_-]+)@/e', '$info["\\1"]', file_get_contents($spec_template));
     } else {
         $spec_contents = preg_replace('/@([a-z0-9_-]+)@/e', '$info["\\1"]', fread($fp, filesize($spec_template)));
         fclose($fp);
     }
     $spec_file = "{$info['rpm_package']}-{$info['version']}.spec";
     $wp = fopen($spec_file, "wb");
     if (!$wp) {
         return $this->raiseError("could not write RPM spec file {$spec_file}: {$php_errormsg}");
     }
     fwrite($wp, $spec_contents);
     fclose($wp);
     $this->ui->outputData("Wrote RPM spec file {$spec_file}", $command);
     return true;
 }
 $translations_array = array();
 if (!$booleans['only_archive']) {
     foreach ($found_modules as $module => $top_module) {
         if ((!array_key_exists($module, $templates) || !is_array($templates[$module])) && (!array_key_exists($module, $configs) || !$configs[$module])) {
             I2CE::raiseError("No translatable templates or configs for {$module}");
             continue;
         }
         $launchpad_name = launchpad($module);
         if (!$booleans['read_po_files']) {
             $mo_file = $locale . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR . $launchpad_name . '.mo';
             if (!in_array($mo_file, $tar_files)) {
                 continue;
             }
             $contents = false;
             I2CE::raiseError("Extracting {$mo_file}");
             $contents = $tar->extractInString($mo_file);
             if (!$contents) {
                 I2CE::raiseError("Bad extraction for {$mo_file}");
                 continue;
             }
             $mo_resource = fopen("php://temp", 'r+');
             fputs($mo_resource, $contents);
             rewind($mo_resource);
             $translations_array[$module] = loadMO($mo_resource);
         } else {
             $po_file = $templates_dir . launchpad($module) . DIRECTORY_SEPARATOR . $locale . '.po';
             if (!is_readable($po_file)) {
                 I2CE::raiseError($po_file . " is not readable for {$module}");
                 continue;
             }
             $t_translations = loadPOT($po_file);
 /**
  *
  * Extract theme from archive
  * @throws Exception
  * @param string $source_path archive path
  *
  * @return waTheme
  */
 public static function extract($source_path)
 {
     static $white_list = array('js', 'css', 'html', 'txt', 'png', 'jpg', 'jpeg', 'jpe', 'tiff', 'bmp', 'gif', 'svg', 'htc', 'cur', 'ttf', 'eot', 'otf', 'woff', '');
     $autoload = waAutoload::getInstance();
     $autoload->add('Archive_Tar', 'wa-installer/lib/vendors/PEAR/Tar.php');
     $autoload->add('PEAR', 'wa-installer/lib/vendors/PEAR/PEAR.php');
     $instance = null;
     if (class_exists('Archive_Tar')) {
         try {
             $tar_object = new Archive_Tar($source_path, true);
             $files = $tar_object->listContent();
             if (!$files) {
                 self::throwArchiveException('INVALID_OR_EMPTY_ARCHIVE');
             }
             //search theme info
             $info = false;
             $pattern = "@(/|^)" . wa_make_pattern(self::PATH, '@') . "\$@";
             foreach ($files as $file) {
                 if (preg_match($pattern, $file['filename'])) {
                     $info = $tar_object->extractInString($file['filename']);
                     break;
                 }
             }
             if (!$info) {
                 self::throwThemeException('MISSING_THEME_XML');
             }
             $xml = @simplexml_load_string($info);
             $app_id = (string) $xml['app'];
             $id = (string) $xml['id'];
             if (!$app_id) {
                 self::throwThemeException('MISSING_APP_ID');
             } elseif (!$id) {
                 self::throwThemeException('MISSING_THEME_ID');
             } else {
                 if ($app_info = wa()->getAppInfo($app_id)) {
                     //TODO check theme support
                     if ($parent_theme = (string) $xml['parent_theme_id']) {
                         $parent_theme = explode(':', $parent_theme, 2);
                         try {
                             if (count($parent_theme) == 2) {
                                 new waTheme($parent_theme[1], $parent_theme[0]);
                             } else {
                                 new waTheme($parent_theme[0], $app_id);
                             }
                         } catch (Exception $ex) {
                             self::throwThemeException('PARENT_THEME_NOT_FOUND', $ex->getMessage());
                         }
                     }
                 } else {
                     $message = sprintf(_w('Theme “%s” is for app “%s”, which is not installed in your Webasyst. Install the app, and upload theme once again.'), $id, $app_id);
                     throw new waException($message);
                 }
             }
             $wa_path = "wa-apps/{$app_id}/themes/{$id}";
             $wa_pattern = wa_make_pattern($wa_path, '@');
             $file = reset($files);
             if (preg_match("@^{$wa_pattern}(/|\$)@", $file['filename'])) {
                 $extract_path = $wa_path;
                 $extract_pattern = $wa_pattern;
             } else {
                 $extract_path = $id;
                 $extract_pattern = wa_make_pattern($id, '@');
                 if (!preg_match("@^{$extract_pattern}(/|\$)@", $file['filename'])) {
                     $extract_path = '';
                     $extract_pattern = false;
                 }
             }
             if ($extract_path) {
                 $extract_path = trim($extract_path, '/') . '/';
             }
             $missed_files = array();
             foreach ($xml->xpath('/theme/files/file') as $theme_file) {
                 $path = (string) $theme_file['path'];
                 $parent = intval((string) $theme_file['parent']);
                 if (!in_array(pathinfo($theme_file['path'], PATHINFO_EXTENSION), array('html', 'js', 'css'))) {
                     self::throwThemeException('UNEXPECTED_EDITABLE_FILE_TYPE', $theme_file['path']);
                 }
                 if (!$parent) {
                     $missed_files[$path] = $extract_path . $path;
                 }
             }
             #angry check
             foreach ($files as $file) {
                 if ($extract_pattern && !preg_match("@^{$extract_pattern}(/|\$)@", $file['filename'])) {
                     self::throwThemeException('UNEXPECTED_FILE_PATH', "{$file['filename']}. Expect files in [{$extract_path}] directory");
                 } elseif (preg_match('@\\.(php\\d*|pl)@', $file['filename'], $matches)) {
                     if (preg_match('@(^|/)build\\.php$@', $file['filename'])) {
                         $file['content'] = $tar_object->extractInString($file['filename']);
                         if (!preg_match('@^<\\?php[\\s\\n]+return[\\s\\n]+\\d+;[\\s\\n]*$@', $file['content'])) {
                             self::throwThemeException('UNEXPECTED_FILE_CONTENT', $file['filename']);
                         }
                     } else {
                         self::throwThemeException('UNEXPECTED_FILE_TYPE', $file['filename']);
                     }
                 } else {
                     if (preg_match('@(^|/)\\.htaccess$@', $file['filename'])) {
                         $file['content'] = $tar_object->extractInString($file['filename']);
                         if (preg_match('@\\b(add|set)Handler\\b@ui', $file['content'])) {
                             self::throwThemeException('INVALID_HTACCESS', $file['filename']);
                         }
                     } elseif (!in_array(pathinfo($file['filename'], PATHINFO_EXTENSION), $white_list)) {
                         if (!in_array(strtolower(basename($file['filename'])), array('theme.xml', 'build.php', '.htaccess', 'readme'))) {
                             self::throwThemeException('UNEXPECTED_FILE_TYPE', $file['filename']);
                         }
                     }
                     if ($extract_pattern) {
                         $file['filename'] = preg_replace("@^{$extract_pattern}/?@", '', $file['filename']);
                     }
                     if (empty($file['typeflag']) && !empty($file['filename']) && isset($missed_files[$file['filename']])) {
                         unset($missed_files[$file['filename']]);
                     }
                 }
             }
             if (!empty($missed_files)) {
                 self::throwThemeException('MISSING_DESCRIBED_FILES', implode(', ', $missed_files));
             }
             self::verify($id);
             self::protect($app_id);
             $target_path = wa()->getDataPath("themes/{$id}", true, $app_id, false);
             waFiles::delete($target_path);
             if ($extract_path && !$tar_object->extractModify($target_path, $extract_path)) {
                 self::throwArchiveException('INTERNAL_ARCHIVE_ERROR');
             } elseif (!$tar_object->extract($target_path)) {
                 self::throwArchiveException('INTERNAL_ARCHIVE_ERROR');
             }
             $instance = new self($id, $app_id);
             $instance->check();
         } catch (Exception $ex) {
             if (isset($target_path) && $target_path) {
                 waFiles::delete($target_path, true);
             }
             throw $ex;
         }
     } else {
         self::throwArchiveException('UNSUPPORTED_ARCHIVE_TYPE');
     }
     return $instance;
 }
示例#11
0
 /**
  * Unpacks the downloaded timezone database and parses all files.
  */
 protected function _extractAndParse()
 {
     if (isset($this->_params['cache'])) {
         $result = @unserialize($this->_params['cache']->get('horde_timezone', $this->_params['cachettl']));
         if ($result) {
             $this->_zones = $result['zones'];
             $this->_rules = $result['rules'];
             $this->_links = $result['links'];
             return;
         }
     }
     if (!$this->_tmpfile) {
         $this->_download();
     }
     $tar = new Archive_Tar($this->_tmpfile);
     foreach ($tar->listContent() as $file) {
         if ($file['typeflag'] != 0) {
             continue;
         }
         $this->_parse($tar->extractInString($file['filename']));
     }
     if (isset($this->_params['cache'])) {
         $this->_params['cache']->set('horde_timezone', serialize(array('zones' => $this->_zones, 'rules' => $this->_rules, 'links' => $this->_links)), $this->_params['cachettl']);
     }
 }
示例#12
0
function plug_upload($idclient = '0', $override = false)
{
    global $rep, $cfg_cms, $sess, $s_upload, $db, $cms_db;
    if (is_array($s_upload) && $override) {
        $tmp_file = $s_upload;
        $returncode = $s_upload['returncode'];
        if ($sess->is_registered('s_upload')) {
            $sess->unregister('s_upload');
        }
    } else {
        $tmp_file = lib_get_upload('plug_upload_file');
    }
    //Es wurde keine Datei hochgeladen
    if (!is_array($tmp_file) || $tmp_file['error'] == '-1' || $tmp_file['error'] == '-2') {
        if ($tmp_file['code'] >= 1) {
            //if (lib_test_safemode()) return array('1801', false);
            if ($tmp_file['code'] == 1) {
                return array('0708', false);
            }
            if ($tmp_file['code'] == 2) {
                return array('0709', false);
            }
            if ($tmp_file['code'] == 3) {
                return array('0710', false);
            }
            if ($tmp_file['code'] == 4) {
                return array('0711', false);
            }
        } else {
            return array('1604', false);
        }
    }
    if (!($file_content = $rep->_file($tmp_file['copy']))) {
        lib_delete_file($tmp_file['copy']);
        if (lib_test_safemode()) {
            return array('1801', false);
        } else {
            return array('1600', false);
        }
    }
    require_once "Archive/Tar.php";
    if (false === ($tar = new Archive_Tar($tmp_file['copy']))) {
        $return = '1615';
        if ($tar->_error_message != '') {
            $error = $tar->_error_message;
        }
        return array($return, $error);
    } elseif ($tar == '-1') {
        return array('1621', false);
    }
    $tmp_plugin = $tar->listContent();
    if ($tmp_plugin[0]['filename'] == '' || $tmp_plugin[0]['typeflag'] != 5) {
        return array('1604', false);
    }
    $name = substr($tmp_plugin[0]['filename'], -1) == '/' ? substr($tmp_plugin[0]['filename'], 0, -1) : $tmp_plugin[0]['filename'];
    $tmp_cmsplug = $tar->extractInString($name . '/' . $name . '.cmsplug');
    //todo: 2remove
    if (empty($tmp_cmsplug)) {
        $tmp_cmsplug = $tar->extractInString($name . '/' . $name . '.dediplug');
    }
    list($idplug, $xml_array) = $rep->plug_import($tmp_cmsplug, $idclient, $override);
    if ($idplug == '-1' || $idplug == '-2') {
        $s_upload = $tmp_file;
        $s_upload['returncode'] = $idplug;
        $s_upload['plugversion'] = $xml_array['version'];
        $s_upload['plugname'] = $xml_array['name'];
        list($type, $rid, $uid) = explode(":", $xml_array['repository_id']);
        $s_upload['plugrepid'] = $type . ':' . $rid;
        $sess->register('s_upload');
        return array('1617', false);
    } elseif ($idplug == '-3') {
        $s_upload = $tmp_file;
        $s_upload['returncode'] = $idplug;
        $s_upload['plugversion'] = $xml_array['version'];
        $s_upload['plugname'] = $xml_array['name'];
        list($type, $rid, $uid) = explode(":", $xml_array['repository_id']);
        $s_upload['plugrepid'] = $type . ':' . $rid;
        $sess->register('s_upload');
        return array('1619', false);
    } elseif ($idplug == '-4') {
        lib_delete_file($tmp_file['copy']);
        return array('1603', false);
    } elseif (!$idplug || !is_array($xml_array)) {
        lib_delete_file($tmp_file['copy']);
        return array('1600', false);
    }
    if (!$tar->extract($cfg_cms['cms_path'] . 'plugins/')) {
        // check error
        if ($tar->_error_message != '') {
            $error = $tar->_error_message;
        }
        // force delete the plugin
        plug_delete($idplug, $idclient);
        return array('1615', $error);
    }
    // get the new Plugin data
    $plugin = $rep->plug_data($idplug, $idclient);
    // Event
    fire_event('plug_upload', array('idplug' => $idplug, 'name' => $plugin['name']));
    if ($override && $returncode == '-1' || $returncode == '-2') {
        if ((bool) $plugin['is_install']) {
            $rep->plug_execute($idplug, 'update', '', 'meta');
            if ((bool) $rep->plug_execute($idplug, 'multi_client') && $idclient == '0') {
                global $client;
                $sql = "SELECT idclient from " . $cms_db['plug'] . " WHERE source_id='{$idplug}' AND is_install='1'";
                $db->query($sql);
                while ($db->next_record()) {
                    $client = $db->f('idclient');
                    $rep->plug_execute($idplug, 'update', 'client', 'meta');
                    // Event
                    fire_event('plug_update_client', array('idplug' => $idplug, 'name' => $plugin['name']));
                }
            }
        }
        // Event
        fire_event('plug_update', array('idplug' => $idplug, 'name' => $plugin['name']));
    } elseif ($override && $returncode == '-3') {
        if ((bool) $plugin['is_install']) {
            $_recurse = array();
            global $client;
            if ((bool) $rep->plug_execute($idplug, 'multi_client') && $idclient == '0') {
                $sql = "SELECT idclient from " . $cms_db['plug'] . " WHERE source_id='{$idplug}' AND is_install='1'";
                $db->query($sql);
                while ($db->next_record()) {
                    array_push($_recurse, $db->f('idclient'));
                    // Event
                    fire_event('plug_reinstall_client', array('idplug' => $idplug, 'name' => $plugin['name']));
                }
            }
            reset($_recurse);
            foreach ($_recurse as $_k => $_v) {
                $client = $_v;
                $rep->plug_execute($idplug, 'uninstall', 'client', 'meta');
            }
            $rep->plug_execute($idplug, 'uninstall', '', 'meta');
            $rep->plug_execute($idplug, 'install', '', 'meta');
            foreach ($_recurse as $_k => $_v) {
                $client = $_v;
                $rep->plug_execute($idplug, 'install', 'client', 'meta');
            }
        }
        // Event
        fire_event('plug_reinstall', array('idplug' => $idplug, 'name' => $plugin['name']));
    }
    lib_delete_file($tmp_file['copy']);
    return array('1612', false);
}
示例#13
0
 public static function readPackageFile($file)
 {
     // Sanity
     if (!file_exists($file) || !is_file($file) || strtolower(pathinfo($file, PATHINFO_EXTENSION)) != 'tar') {
         throw new Engine_Package_Exception('File does not exist or is not a tar file');
     }
     self::_loadArchiveClass();
     // Create archive object
     $archive = new Archive_Tar($file);
     // List files
     $fileList = $archive->listContent();
     if (empty($fileList)) {
         throw new Engine_Package_Exception('Unable to open archive');
     }
     // Check for root package file
     $rootPackageFile = null;
     foreach ($fileList as $arFile) {
         if ($arFile['filename'] == 'package.json') {
             $rootPackageFile = $arFile['filename'];
             break;
         }
     }
     if (null === $rootPackageFile) {
         throw new Engine_Package_Exception('Root package file not found.');
     }
     // Start building package stuff
     $packageFileObject = new Engine_Package_Manifest();
     $packageFileObject->fromString($archive->extractInString($rootPackageFile), 'json');
     return $packageFileObject;
 }
示例#14
0
 /**
  * This method opens and validates the uploaded PEAR package
  * and assembles the content of the package file itself, the
  * dependencies and the release notes.
  *
  * @param Faett_Package_Model_Link $link The link with the PEAR package file
  * @return void
  */
 public function generatePEARInfos(Faett_Package_Model_Link $link)
 {
     // initialize the PEAR service implementation
     $service = Faett_Core_Factory::get(Mage::getBaseDir());
     // initialize the PEAR_PackageFile_v2 instance
     $pf = $service->packageFile($packageFile = Faett_Package_Model_Link::getBasePath() . $link->getLinkFile());
     // initialize the archive
     $tar = new Archive_Tar($packageFile);
     // try to load the content of the package2.xml file
     $contents = $tar->extractInString('package2.xml');
     // if not available, try to load from package.xml file
     if (!$contents) {
         $contents = $tar->extractInString('package.xml');
     }
     // load the data to assemble the link with
     $link->setPackageFile($contents);
     $link->setPackageName($pf->getName());
     $link->setPackageSize(filesize($packageFile));
     $link->setDependencies(serialize($pf->getDependencies()));
     $link->setState($pf->getState());
     $link->setVersion($pf->getVersion());
     $link->setReleaseDate($pf->getDate());
     $link->setLicence($pf->getLicense());
     $link->setSummary($pf->getSummary());
     $link->setDescription($pf->getDescription());
     $link->setNotes($pf->getNotes());
     // set the licence URI
     if (is_array($loc = $pf->getLicenseLocation())) {
         if (array_key_exists('uri', $loc)) {
             $link->setLicenceUri($loc['uri']);
         } elseif (array_key_exists('filesource', $loc)) {
             $link->setLicenceUri($loc['filesource']);
         }
     }
     // save the completed link
     $link->save();
 }
示例#15
0
 function _generatePackageDeps($pf)
 {
     $requires = $conflicts = array();
     if ($pf->getPackagexmlVersion() == '1.0') {
         foreach ($pf->getDeps() as $dep) {
             if (isset($dep['optional']) && $dep['optional'] == 'yes') {
                 continue;
             }
             if (!isset($dep['type']) || $dep['type'] == 'pkg') {
                 $type = 'pkgdep';
             } else {
                 $type = $dep['type'];
             }
             if (!isset($dep['channel'])) {
                 $dep['channel'] = null;
             }
             if (!isset($dep['name'])) {
                 $dep['name'] = '';
             }
             //e.g. "php" dep
             // $package contains the *dependency name* here, which may or may
             // not be the same as the package name
             $package = $this->_getRPMName($dep['name'], $dep['channel'], null, $type);
             // If we could not find an RPM namespace equivalent, don't add the dependency
             if (empty($package)) {
                 continue;
             }
             $trans = array('>' => '>', '<' => '<', '>=' => '>=', '<=' => '<=', '=' => '=', 'gt' => '>', 'lt' => '<', 'ge' => '>=', 'le' => '<=', 'eq' => '=');
             if ($dep['rel'] == 'has') {
                 // We use $package as the index to the $requires array to de-duplicate deps.
                 // Note that in the case of duplicate deps, versioned deps will "win" - see several lines down.
                 $requires[$package] = $package;
             } elseif ($dep['rel'] == 'not') {
                 $conflicts[] = $package;
             } elseif ($dep['rel'] == 'ne') {
                 $conflicts[] = $package . ' = ' . $dep['version'];
             } elseif (isset($trans[$dep['rel']])) {
                 $requires[$package] = $package . ' ' . $trans[$dep['rel']] . ' ' . $dep['version'];
             }
         }
         if (count($requires)) {
             $this->_output['extra_headers'] .= $this->_formatRpmHeader('Requires', implode(', ', $requires)) . "\n";
         }
         if (count($conflicts)) {
             $this->_output['extra_headers'] .= $this->_formatRpmHeader('Conflicts', implode(', ', $conflicts)) . "\n";
         }
     } else {
         $this->_output['package2xml'] = '2';
         // tell the spec to use package2.xml
         $deps = $pf->getDeps(true);
         if (isset($deps['required']['package'])) {
             if (!isset($deps['required']['package'][0])) {
                 $deps['required']['package'] = array($deps['required']['package']);
             }
             foreach ($deps['required']['package'] as $dep) {
                 if (!isset($dep['type']) || $dep['type'] == 'pkg') {
                     $type = 'pkgdep';
                 } else {
                     $type = $dep['type'];
                 }
                 if (!isset($dep['channel'])) {
                     $dep['channel'] = null;
                 }
                 // $package contains the *dependency name* here, which may or may
                 // not be the same as the package name
                 $package = $this->_getRPMName($dep['name'], $dep['channel'], null, $type);
                 if (empty($package)) {
                     continue;
                 }
                 if (isset($dep['conflicts']) && (isset($dep['min']) || isset($dep['max']))) {
                     $deprange = array();
                     if (isset($dep['min'])) {
                         $deprange[] = array($dep['min'], '>=');
                     }
                     if (isset($dep['max'])) {
                         $deprange[] = array($dep['max'], '<=');
                     }
                     if (isset($dep['exclude'])) {
                         if (!is_array($dep['exclude']) || !isset($dep['exclude'][0])) {
                             $dep['exclude'] = array($dep['exclude']);
                         }
                         if (count($deprange)) {
                             $excl = $dep['exclude'];
                             // change >= to > if excluding the min version
                             // change <= to < if excluding the max version
                             for ($i = 0; $i < count($excl); $i++) {
                                 if (isset($deprange[0]) && $excl[$i] == $deprange[0][0]) {
                                     $deprange[0][1] = '<';
                                     unset($dep['exclude'][$i]);
                                 }
                                 if (isset($deprange[1]) && $excl[$i] == $deprange[1][0]) {
                                     $deprange[1][1] = '>';
                                     unset($dep['exclude'][$i]);
                                 }
                             }
                         }
                         if (count($dep['exclude'])) {
                             $dep['exclude'] = array_values($dep['exclude']);
                             $newdeprange = array();
                             // remove excludes that are outside the existing range
                             for ($i = 0; $i < count($dep['exclude']); $i++) {
                                 if ($dep['exclude'][$i] < $dep['min'] || $dep['exclude'][$i] > $dep['max']) {
                                     unset($dep['exclude'][$i]);
                                 }
                             }
                             $dep['exclude'] = array_values($dep['exclude']);
                             usort($dep['exclude'], 'version_compare');
                             // take the remaining excludes and
                             // split the dependency into sub-ranges
                             $lastmin = $deprange[0];
                             for ($i = 0; $i < count($dep['exclude']) - 1; $i++) {
                                 $newdeprange[] = '(' . $package . " {$lastmin[1]} {$lastmin[0]} and " . $package . ' < ' . $dep['exclude'][$i] . ')';
                                 $lastmin = array($dep['exclude'][$i], '>');
                             }
                             if (isset($dep['max'])) {
                                 $newdeprange[] = '(' . $package . " {$lastmin[1]} {$lastmin[0]} and " . $package . ' < ' . $dep['max'] . ')';
                             }
                             $conflicts[] = implode(' or ', $deprange);
                         } else {
                             $conflicts[] = $package . " {$deprange[0][1]} {$deprange[0][0]}" . (isset($deprange[1]) ? " and {$package} {$deprange[1][1]} {$deprange[1][0]}" : '');
                         }
                     }
                     continue;
                 }
                 if (!isset($dep['min']) && !isset($dep['max']) && !isset($dep['exclude'])) {
                     if (isset($dep['conflicts'])) {
                         $conflicts[] = $package;
                     } else {
                         $requires[$package] = $package;
                     }
                 } else {
                     if (isset($dep['min'])) {
                         $requires[$package] = $package . ' >= ' . $dep['min'];
                     }
                     if (isset($dep['max'])) {
                         $requires[$package] = $package . ' <= ' . $dep['max'];
                     }
                     if (isset($dep['exclude'])) {
                         $ex = $dep['exclude'];
                         if (!is_array($ex)) {
                             $ex = array($ex);
                         }
                         foreach ($ex as $ver) {
                             $conflicts[] = $package . ' = ' . $ver;
                         }
                     }
                 }
             }
             require_once 'Archive/Tar.php';
             $tar = new Archive_Tar($pf->getArchiveFile());
             $tar->pushErrorHandling(PEAR_ERROR_RETURN);
             $a = $tar->extractInString('package2.xml');
             $tar->popErrorHandling();
             if ($a === null || PEAR::isError($a)) {
                 $this->_output['package2xml'] = '';
                 // this doesn't have a package.xml version 1.0
                 $requires[$this->_output['pear_rpm_name']] = $this->_output['pear_rpm_name'] . ' >= ' . $deps['required']['pearinstaller']['min'];
             }
             if (count($requires)) {
                 $this->_output['extra_headers'] .= $this->_formatRpmHeader('Requires', implode(', ', $requires)) . "\n";
             }
             if (count($conflicts)) {
                 $this->_output['extra_headers'] .= $this->_formatRpmHeader('Conflicts', implode(', ', $conflicts)) . "\n";
             }
         }
     }
 }
示例#16
0
 /**
  * Confirm release upload
  *
  * @param string Package name
  * @param string Package version
  * @param string Package state
  * @param string Release notes
  * @param string md5
  * @param int    Package id from database
  * @param string package contents
  * @static
  * @return string  the file name of the upload or PEAR_Error object if problems
  */
 static function confirmUpload($package, $version, $state, $relnotes, $md5sum, $package_id, $file, $pkg_info = false, $packagexml = false, $compatible = false)
 {
     require_once 'PEAR/Common.php';
     global $dbh, $auth_user, $_PEAR_Common_dependency_types, $_PEAR_Common_dependency_relations;
     if (!$pkg_info) {
         require_once 'Archive/Tar.php';
         $tar = new Archive_Tar($file);
         $oldpackagexml = $tar->extractInString('package.xml');
         if (null === ($packagexml = $tar->extractInString('package2.xml'))) {
             if ($oldpackagexml === null) {
                 return PEAR::raiseError('Archive uploaded does not appear to contain a package.xml!');
             }
             $packagexml = $oldpackagexml;
         }
         $compatible = $oldpackagexml != $packagexml ? true : false;
     }
     // Update releases table
     $query = "INSERT INTO releases (id,package,version,state,doneby," . "releasedate,releasenotes) VALUES(?,?,?,?,?,NOW(),?)";
     $sth = $dbh->prepare($query);
     $release_id = $dbh->nextId('releases');
     $dbh->execute($sth, array($release_id, $package_id, $version, $state, $auth_user->handle, $relnotes));
     // Update files table
     $query = "INSERT INTO files " . "(id,package,`release`,md5sum,basename,fullpath,packagexml) " . "VALUES(?,?,?,?,?,?,?)";
     $sth = $dbh->prepare($query);
     $file_id = $dbh->nextId("files");
     $ok = $dbh->execute($sth, array($file_id, $package_id, $release_id, $md5sum, basename($file), $file, $packagexml));
     /*
      * Code duplication with deps error
      * Should be droped soon or later using transaction
      * (and add mysql4 as a pe(ar|cl)web requirement)
      */
     if (PEAR::isError($ok)) {
         $dbh->query("DELETE FROM releases WHERE id = {$release_id}");
         @unlink($file);
         return $ok;
     }
     // Update dependency table
     $query = "INSERT INTO deps " . "(package, `release`, type, relation, version, name, optional) " . "VALUES (?,?,?,?,?,?,?)";
     $sth = $dbh->prepare($query);
     if (!$pkg_info) {
         require_once 'PEAR/PackageFile.php';
         require_once 'PEAR/Config.php';
         $config = PEAR_Config::singleton();
         $pf = new PEAR_PackageFile($config);
         $pkg_info = $pf->fromXmlString($packagexml, PEAR_VALIDATE_DOWNLOADING, $compatible ? 'package2.xml' : 'package.xml');
     }
     $deps = $pkg_info->getDeps(true);
     // get the package2.xml actual content
     $storedeps = $pkg_info->getDeps();
     // get the BC-compatible content
     $pearused = false;
     if (isset($deps['required']['package'])) {
         if (!isset($deps['required']['package'][0])) {
             $deps['required']['package'] = array($deps['required']['package']);
         }
         foreach ($deps['required']['package'] as $pkgdep) {
             if ($pkgdep['channel'] == 'pear.php.net' && strtolower($pkgdep['name']) == 'pear') {
                 $pearused = true;
             }
         }
     }
     if (is_array($storedeps)) {
         foreach ($storedeps as $dep) {
             $prob = array();
             if (empty($dep['type']) || !in_array($dep['type'], $_PEAR_Common_dependency_types)) {
                 $prob[] = 'type';
             }
             if (empty($dep['name'])) {
                 /*
                  * NOTE from pajoye in ver 1.166:
                  * This works for now.
                  * This would require a 'cleaner' InfoFromXXX
                  * which may return a defined set of data using
                  * default values if required.
                  */
                 if (strtolower($dep['type']) == 'php') {
                     $dep['name'] = 'PHP';
                 } else {
                     $prob[] = 'name';
                 }
             } elseif (strtolower($dep['name']) == 'pear') {
                 if (!$pearused && $compatible) {
                     // there is no need for a PEAR dependency here
                     continue;
                 }
                 if (!$pearused && !$compatible) {
                     $dep['name'] = 'PEAR Installer';
                 }
             }
             if (empty($dep['rel']) || !in_array($dep['rel'], $_PEAR_Common_dependency_relations)) {
                 $prob[] = 'rel';
             }
             if (empty($dep['optional'])) {
                 $optional = 0;
             } else {
                 if ($dep['optional'] != strtolower($dep['optional'])) {
                     $prob[] = 'optional';
                 }
                 $optional = $dep['optional'] == 'yes' ? 1 : 0;
             }
             if (count($prob)) {
                 $res = PEAR::raiseError('The following attribute(s) ' . 'were missing or need proper values: ' . implode(', ', $prob));
             } else {
                 $res = $dbh->execute($sth, array($package_id, $release_id, $dep['type'], $dep['rel'], @$dep['version'], $dep['name'], $optional));
             }
             if (PEAR::isError($res)) {
                 $dbh->query('DELETE FROM deps WHERE `release` = ' . $release_id);
                 $dbh->query('DELETE FROM releases WHERE id = ' . $release_id);
                 @unlink($file);
                 return $res;
             }
         }
     }
     include_once 'pear-database-package.php';
     $n = package::info($package, 'name');
     if (!in_array($n, array('pearweb', 'pearweb_phars'), true)) {
         // Add release archive file to API documentation queue
         $query = "INSERT INTO apidoc_queue (filename, queued) " . "VALUES ('" . $file . "', NOW())";
         // Don't abort the release if something goes wrong.
         $dbh->pushErrorHandling(PEAR_ERROR_RETURN);
         $sth = $dbh->query($query);
         $dbh->popErrorHandling();
     }
     // Update Cache
     include_once 'pear-rest.php';
     $pear_rest = new pearweb_Channel_REST_Generator(PEAR_REST_PATH, $dbh);
     $pear_rest->saveAllReleasesREST($package);
     $pear_rest->saveReleaseREST($file, $packagexml, $pkg_info, $auth_user->handle, $release_id);
     $pear_rest->savePackagesCategoryREST(package::info($package, 'category'));
     return $file;
 }
示例#17
0
{
    return substr($str, 0, strlen($str) - strlen($sub));
}
function endsWith($str, $sub)
{
    return substr($str, strlen($str) - strlen($sub)) === $sub;
}
$options = array(XML_UNSERIALIZER_OPTION_COMPLEXTYPE => 'array', XML_UNSERIALIZER_OPTION_ATTRIBUTE_KEY => array('icon' => 'name', 'condition' => 'code'), XML_UNSERIALIZER_OPTION_ATTRIBUTES_PARSE => false, XML_UNSERIALIZER_OPTION_ATTRIBUTES_ARRAYKEY => false, XML_UNSERIALIZER_OPTION_FORCE_ENUM => array('format'));
$unserializer =& new XML_Unserializer($options);
$WIicon_packs = array();
$WIicon_dir = @dir(WIicondir);
if ($WIicon_dir) {
    while (($file = $WIicon_dir->read()) !== false) {
        if (is_file(WIicondir . $file) && endsWith($file, '.ipk')) {
            $tar = new Archive_Tar(WIicondir . $file);
            $xml = $tar->extractInString('meta.xml');
            $status = $unserializer->unserialize($xml, false);
            if (PEAR::isError($status)) {
                echo $file . ' is an invalid or corrupt Icon Pack';
            } else {
                $WIicon_packs[subchop($file, '.ipk')] = $unserializer->getUnserializedData();
            }
        }
    }
}
foreach ($WIicon_packs as $name => $iconpack) {
    $type = $iconpack['formats']['format'][0];
    echo '<div style="float: left;"><h1>' . $name . '</h1>';
    echo '<table>';
    foreach ($iconpack['icons'] as $icon => $night) {
        $url = WIdirWeb . '/ipkfile.php?pack=' . $name . '&amp;icon=' . $icon . '&amp;type=' . $type;
示例#18
0
function createPatch($updatecache = false)
{
    include_once "Lib/Archive/Tar.php";
    include_once 'Lib/Text/Diff.php';
    include_once 'Lib/Text/Diff/Renderer/unified.php';
    $start = microtime(true);
    $tar_object = new Archive_Tar(_bmoddir . "Data/Cache.tar");
    $tar_object->setErrorHandling(PEAR_ERROR_PRINT);
    $tardata = $tar_object->listContent();
    $working = checkDir2("");
    $fmerged = array_merge($tardata, $working);
    $tarf_db = reIndexByFile($tardata);
    $work_db = reIndexByFile($working);
    $workidx = indexFilename($working);
    $tar_idx = indexFilename($tardata);
    $f_names = array_unique(array_merge($workidx, $tar_idx));
    $out = "";
    foreach ($f_names as $file) {
        //speed optimization
        if ($tarf_db[$file] && $work_db[$file] && $tarf_db[$file]["mtime"] == $work_db[$file]["mtime"] && $updatecache != true) {
            continue;
        }
        if ($tarf_db[$file]) {
            $fts1 = $tarf_db[$file]["mtime"];
            $fdata = $tar_object->extractInString($file);
            $lines1 = explode("\n", $fdata);
            //$lines1 = file("Data/$file");
            if (substr($fdata, -1, 1) == "\n") {
                //$lines1[] = "";
            }
        } else {
            $fts1 = 0;
            $lines1 = array();
        }
        if ($work_db[$file]) {
            $fts2 = $work_db[$file]["mtime"];
            //$lines2 = file(_bpatdir."$file");
            $filetext = file_get_contents(_bmoddir . _bpatdir . "{$file}");
            $lines2 = explode("\n", $filetext);
        } else {
            $fts2 = 0;
            $lines2 = array();
            $filetext = "";
        }
        if (array_search($file, $workidx) === false && array_search($file, $tar_idx) !== false) {
            //delted file
            $out .= renderHeader($file, $fts1, $fts2);
            $out .= "@@ -0,0 @@\n\n";
            continue;
        }
        if (array_search($file, $workidx) !== false && array_search($file, $tar_idx) === false) {
            //added file
        }
        if ($filetext == $fdata) {
            continue;
        }
        $diff = new Text_Diff('auto', array($lines1, $lines2));
        $renderer = new Text_Diff_Renderer_unified();
        $render = $renderer->render($diff);
        if ($render != "") {
            $out .= renderHeader($file, $fts1, $fts2);
            //get ts to work!
            $out .= $render . "\n";
            if (substr($filetext, -1, 1) != "\n") {
                $out .= "\\ No newline at end of file\n\n";
            }
        }
    }
    if ($updatecache == true) {
        $tar_object->create(array());
        foreach ($f_names as $file) {
            $tar_object->addString($file, file_get_contents(_bmoddir . _bpatdir . "{$file}"));
        }
    }
    return array(microtime(true) - $start, $out, count($addlist));
}
示例#19
0
 function _fromUrl($param, $saveparam = '')
 {
     if (!is_array($param) && preg_match('#^(http|https|ftp)://#', $param)) {
         $options = $this->_downloader->getOptions();
         $this->_type = 'url';
         $callback = $this->_downloader->ui ? array(&$this->_downloader, '_downloadCallback') : null;
         $this->_downloader->pushErrorHandling(PEAR_ERROR_RETURN);
         if (PEAR::isError($dir = $this->_downloader->getDownloadDir())) {
             $this->_downloader->popErrorHandling();
             return $dir;
         }
         $this->_downloader->log(3, 'Downloading "' . $param . '"');
         $file = $this->_downloader->downloadHttp($param, $this->_downloader->ui, $dir, $callback, null, false, $this->getChannel());
         $this->_downloader->popErrorHandling();
         if (PEAR::isError($file)) {
             if (!empty($saveparam)) {
                 $saveparam = ", cannot download \"{$saveparam}\"";
             }
             $err = PEAR::raiseError('Could not download from "' . $param . '"' . $saveparam . ' (' . $file->getMessage() . ')');
             return $err;
         }
         if ($this->_rawpackagefile) {
             require_once 'Archive/Tar.php';
             $tar = new Archive_Tar($file);
             $packagexml = $tar->extractInString('package2.xml');
             if (!$packagexml) {
                 $packagexml = $tar->extractInString('package.xml');
             }
             if (str_replace(array("\n", "\r"), array('', ''), $packagexml) != str_replace(array("\n", "\r"), array('', ''), $this->_rawpackagefile)) {
                 if ($this->getChannel() != 'pear.php.net') {
                     return PEAR::raiseError('CRITICAL ERROR: package.xml downloaded does ' . 'not match value returned from xml-rpc');
                 }
                 // be more lax for the existing PEAR packages that have not-ok
                 // characters in their package.xml
                 $this->_downloader->log(0, 'CRITICAL WARNING: The "' . $this->getPackage() . '" package has invalid characters in its ' . 'package.xml.  The next version of PEAR may not be able to install ' . 'this package for security reasons.  Please open a bug report at ' . 'http://pear.php.net/package/' . $this->getPackage() . '/bugs');
             }
         }
         // whew, download worked!
         if (isset($options['downloadonly'])) {
             $pkg =& $this->getPackagefileObject($this->_config, $this->_downloader->debug);
         } else {
             $dir = $this->_downloader->getDownloadDir();
             if (PEAR::isError($dir)) {
                 return $dir;
             }
             $pkg =& $this->getPackagefileObject($this->_config, $this->_downloader->debug, $dir);
         }
         PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
         $pf =& $pkg->fromAnyFile($file, PEAR_VALIDATE_INSTALLING);
         PEAR::popErrorHandling();
         if (PEAR::isError($pf)) {
             if (is_array($pf->getUserInfo())) {
                 foreach ($pf->getUserInfo() as $err) {
                     if (is_array($err)) {
                         $err = $err['message'];
                     }
                     if (!isset($options['soft'])) {
                         $this->_downloader->log(0, "Validation Error: {$err}");
                     }
                 }
             }
             if (!isset($options['soft'])) {
                 $this->_downloader->log(0, $pf->getMessage());
             }
             ///FIXME need to pass back some error code that we can use to match with to cancel all further operations
             /// At least stop all deps of this package from being installed
             $out = $saveparam ? $saveparam : $param;
             $err = PEAR::raiseError('Download of "' . $out . '" succeeded, but it is not a valid package archive');
             $this->_valid = false;
             return $err;
         }
         $this->_packagefile =& $pf;
         $this->setGroup('default');
         // install the default dependency group
         return $this->_valid = true;
     }
     return $this->_valid = false;
 }
示例#20
0
 /**
  * (non-PHPdoc)
  * @see lib/Faett/Core/Interfaces/Faett_Core_Interfaces_Service#packageFile($package)
  */
 public function packageFile($package)
 {
     // initialize the archive
     $tar = new Archive_Tar($package);
     // try to load the content of the package2.xml file
     $contents = $tar->extractInString($packageFileName = 'package2.xml');
     // if not available, try to load from package.xml file
     if (!$contents) {
         $contents = $tar->extractInString($packageFileName = 'package.xml');
     }
     // initialize the parser for the package file and parse it
     $pkg = new PEAR_PackageFile_Parser_v2();
     $pkg->setConfig($this->getConfig());
     $pf = $pkg->parse($contents, $packageFileName);
     // check if errors occurs and throw an exception if necessary
     if (PEAR::isError($pf)) {
         throw Faett_Core_Exceptions_InvalidPackageFileException::create($pf->getMessage());
     }
     // validate the package
     if (!$pf->validate()) {
         // initialize the string for the errors and warnings
         $errors = '';
         // concatenate the message
         foreach ($pf->getValidationWarnings() as $warning) {
             $errors .= PHP_EOL . ucfirst($warning['level']) . ': ' . $warning['message'];
         }
         // throw an exception with the warnings
         throw Faett_Core_Exceptions_InvalidPackageFileException::create($errors);
     }
     // return the package file
     return $pf;
 }
示例#21
0
 /**
  *
  * Extract theme from archive
  * @throws Exception
  * @param string $source_path archive path
  *
  * @return waTheme
  */
 public static function extract($source_path)
 {
     $autoload = waAutoload::getInstance();
     $autoload->add('Archive_Tar', 'wa-installer/lib/vendors/PEAR/Tar.php');
     $autoload->add('PEAR', 'wa-installer/lib/vendors/PEAR/PEAR.php');
     if (class_exists('Archive_Tar')) {
         try {
             $tar_object = new Archive_Tar($source_path, true);
             $files = $tar_object->listContent();
             if (!$files) {
                 self::throwArchiveException('INVALID_OR_EMPTY_ARCHIVE');
             }
             //search theme info
             $theme_check_files = array(self::PATH);
             $theme_files_map = array();
             $info = false;
             $pattern = "/(\\/|^)" . wa_make_pattern(self::PATH) . "\$/";
             foreach ($files as $file) {
                 if (preg_match($pattern, $file['filename'])) {
                     $info = $tar_object->extractInString($file['filename']);
                     break;
                 }
             }
             if (!$info) {
                 self::throwThemeException('MISSING_THEME_XML');
             }
             $xml = @simplexml_load_string($info);
             $app_id = (string) $xml['app'];
             $id = (string) $xml['id'];
             if (!$app_id) {
                 self::throwThemeException('MISSING_APP_ID');
             } elseif (!$id) {
                 self::throwThemeException('MISSING_THEME_ID');
             } else {
                 if ($app_info = wa()->getAppInfo($app_id)) {
                     //TODO check theme support
                 } else {
                     $message = sprintf(_w('Theme “%s” is for app “%s”, which is not installed in your Webasyst. Install the app, and upload theme once again.'), $id, $app_id);
                     throw new waException($message);
                 }
             }
             $wa_path = "wa-apps/{$app_id}/themes/{$id}";
             $wa_pattern = wa_make_pattern($wa_path);
             $file = reset($files);
             if (preg_match("@^{$wa_pattern}(/|\$)@", $file['filename'])) {
                 $extract_path = $wa_path;
                 $extract_pattern = $wa_pattern;
             } else {
                 $extract_path = $id;
                 $extract_pattern = wa_make_pattern($id);
                 if (!preg_match("@^{$extract_pattern}(/|\$)@", $file['filename'])) {
                     $extract_path = '';
                     $extract_pattern = false;
                 }
             }
             foreach ($files as $file) {
                 if ($extract_pattern && !preg_match("@^{$extract_pattern}(/|\$)@", $file['filename'])) {
                     self::throwThemeException('UNEXPECTED_FILE_PATH', "{$file['filename']}. Expect files in [{$extract_path}] directory");
                 } elseif (preg_match('@\\.(php\\d*|pl)@', $file['filename'], $matches)) {
                     self::throwThemeException('UNEXPECTED_FILE_TYPE', $file['filename']);
                 }
             }
             self::verify($id);
             self::protect($app_id);
             $target_path = wa()->getDataPath("themes/{$id}", true, $app_id, false);
             waFiles::delete($target_path);
             if ($extract_path && !$tar_object->extractModify($target_path, $extract_path)) {
                 self::throwArchiveException('INTERNAL_ARCHIVE_ERROR');
             } elseif (!$tar_object->extract($target_path)) {
                 self::throwArchiveException('INTERNAL_ARCHIVE_ERROR');
             }
             $instance = new self($id, $app_id);
             $instance->check();
         } catch (Exception $ex) {
             if (isset($target_path) && $target_path) {
                 waFiles::delete($target_path, true);
             }
             throw $ex;
         }
     } else {
         self::throwArchiveException('UNSUPPORTED_ARCHIVE_TYPE');
     }
     return $instance;
 }
示例#22
0
 function archive2app__process($values)
 {
     require_once 'Archive/Tar.php';
     if (preg_match('/\\.gz$/', $_FILES['archive']['name'])) {
         $compression = 'gz';
     } else {
         $compression = null;
     }
     $archive = new Archive_Tar($_FILES['archive']['tmp_name'], $compression);
     $files = $archive->listContent();
     foreach ($files as $file) {
         if (!preg_match('/(\\.ini)|(\\.php)$/', $file['filename'])) {
             continue;
         }
         $content = $archive->extractInString($file['filename']);
         $content = str_replace(array('%%DATAFACE_URL%%', '%%DATAFACE_PATH%%', '%%MYSQL_USER%%', '%%MYSQL_PASSWORD%%', '%%MYSQL_HOST%%', '%%MYSQL_DATABASE_NAME%%'), array(addslashes(dirname($_SERVER['PHP_SELF'])), addslashes(dirname(__FILE__)), addslashes($values['mysql_user']), addslashes($values['mysql_password']), addslashes(DB_HOST), addslashes($values['database_name'])), $content);
         $archive->addString($file['filename'], $content);
     }
     $root = $files[0]['filename'];
     $install = $archive->extractInString($root . 'install/install.sql');
     $res = mysql_select_db($values['database_name'], db());
     if (!$res) {
         $dbname = str_replace('`', '', $values['database_name']);
         $res = mysql_query("create database `" . addslashes($dbname) . "`", db());
         if (!$res) {
             return PEAR::raiseError("Failed to create database '{$dbname}'");
         }
         $res = mysql_select_db($dbname);
         if (!$res) {
             return PEAR::raiseError("Problem selecting database {$dbname}.");
         }
     }
     if ($install) {
         $installFile = tempnam(null, 'install.sql');
         file_put_contents($installFile, $install);
         $file = file($installFile);
         $queries = array();
         $ctr = 0;
         foreach ($file as $line) {
             if (isComment($line)) {
                 continue;
             }
             $queries[$ctr] .= $line;
             $trimmed = trim($line);
             if ($trimmed[strlen($trimmed) - 1] == ';') {
                 $ctr++;
             }
         }
         //$file = implode("",$out);
         foreach ($queries as $query) {
             $res = @mysql_query($query, $db);
             if (!$res) {
                 $my_errs[] = mysql_error($db);
             }
         }
     }
     switch ($values['install_type']) {
         case 'ftp_install':
             //echo 'here';
             require_once 'install/FTPExtractor.class.php';
             $extractor = new FTPExtractor($archive);
             $res = $extractor->connect($values['ftp_host'], $values['ftp_username'], $values['ftp_password']);
             if (PEAR::isError($res)) {
                 die($res->getMessage());
             }
             $res = $extractor->extract($values['ftp_path'], '/');
             //if ( PEAR::isError($res) ){
             //	die($res->getMessage());
             //}
             $context = array();
             if (PEAR::isError($res)) {
                 $context['result'] = 'Error: ' . $res->getMessage();
             } else {
                 $context = $res;
             }
             include 'install' . DIRECTORY_SEPARATOR . 'archive2app-results.inc.php';
             exit;
         default:
             // download_tarball
             $tarpath = $_FILES['archive']['tmp_name'];
             if ($compression == 'gz') {
                 $mimetype = 'application/x-gzip';
             } else {
                 $mimetype = 'application/x-tar';
             }
             header('Content-type: ' . $mimetype);
             header('Content-Disposition: attachment; filename="' . basename($_FILES['archive']['name']) . '.tar.gz"');
             echo file_get_contents($tarpath);
             exit;
     }
 }
 public function manageAction()
 {
     require_once 'PEAR.php';
     require_once 'Archive/Tar.php';
     // Get built packages
     $builtPackages = array();
     $builtPackageFiles = array();
     foreach (scandir($this->_outputPath) as $file) {
         $path = $this->_outputPath . '/' . $file;
         if (!is_file($path)) {
             continue;
         }
         if (substr($file, -4) !== '.tar') {
             continue;
         }
         // Read package.json
         $archive = new Archive_Tar($path);
         $string = $archive->extractInString('package.json');
         if ($string) {
             $package = new Engine_Package_Manifest();
             $parser = Engine_Package_Manifest_Parser::factory('package.json');
             $package->fromArray($parser->fromString($string));
         } else {
             $package = null;
         }
         $builtPackages[] = $package;
         $builtPackageFiles[] = $path;
     }
     $this->view->packages = $builtPackages;
     $this->view->packageFiles = $builtPackageFiles;
 }
示例#24
0
文件: v1.php 项目: michabbb/pear-core
 /**
  * Get the contents of a file listed within the package.xml
  * @param string
  * @return string
  */
 function getFileContents($file)
 {
     if ($this->_archiveFile == $this->_packageFile) {
         // unpacked
         $dir = dirname($this->_packageFile);
         $file = $dir . DIRECTORY_SEPARATOR . $file;
         $file = str_replace(array('/', '\\'), array(DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR), $file);
         if (file_exists($file) && is_readable($file)) {
             return implode('', file($file));
         }
     } else {
         // tgz
         if (!class_exists('Archive_Tar')) {
             require_once 'Archive/Tar.php';
         }
         $tar = new Archive_Tar($this->_archiveFile);
         $tar->pushErrorHandling(PEAR_ERROR_RETURN);
         if ($file != 'package.xml' && $file != 'package2.xml') {
             $file = $this->getPackage() . '-' . $this->getVersion() . '/' . $file;
         }
         $file = $tar->extractInString($file);
         $tar->popErrorHandling();
         if (PEAR::isError($file)) {
             return PEAR::raiseError("Cannot locate file '{$file}' in archive");
         }
         return $file;
     }
 }
示例#25
0
 function get_icon_packs()
 {
     $options = array(XML_UNSERIALIZER_OPTION_COMPLEXTYPE => 'array', XML_UNSERIALIZER_OPTION_ATTRIBUTE_KEY => array('icon' => 'name', 'condition' => 'code'), XML_UNSERIALIZER_OPTION_ATTRIBUTES_PARSE => false, XML_UNSERIALIZER_OPTION_ATTRIBUTES_ARRAYKEY => false, XML_UNSERIALIZER_OPTION_FORCE_ENUM => array('format'));
     $unserializer =& new XML_Unserializer($options);
     $WIicon_packs = array();
     $WIicon_dir = @dir(WIicondir);
     if ($WIicon_dir) {
         while (($file = $WIicon_dir->read()) !== false) {
             if (is_file(WIicondir . $file) && $this->endsWith($file, '.ipk')) {
                 $tar = new Archive_Tar(WIicondir . $file);
                 $xml = $tar->extractInString('meta.xml');
                 $status = $unserializer->unserialize($xml, false);
                 $ipkName = $this->subchop($file, '.ipk');
                 if (PEAR::isError($status)) {
                     $this->status[] = $this->gmtime() . ' icon pack ' . $ipkName . ' is invalid.';
                 } else {
                     $this->status[] = $this->gmtime() . ' icon pack ' . $ipkName . ' is valid.';
                     $WIicon_packs[$ipkName] = $unserializer->getUnserializedData();
                 }
             }
         }
     }
     return $WIicon_packs;
 }