listContent() public method

{{{ listContent()
public listContent ( )
Ejemplo n.º 1
0
 /**
  * Method to return a listing of the contents of an archived file
  *
  * @param  boolean $full
  * @return array
  */
 public function listFiles($full = false)
 {
     $files = array();
     $list = $this->archive->listContent();
     if (!$full) {
         foreach ($list as $file) {
             $files[] = $file['filename'];
         }
     } else {
         $files = $list;
     }
     return $files;
 }
 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);
     }
 }
Ejemplo n.º 3
0
function extractSource($tarfile, $target_dir, $modes)
{
    $tar = new Archive_Tar($tarfile);
    $root_folders = array();
    foreach ($tar->listContent() as $value) {
        if (substr($value["filename"], -1) == "/" && substr_count($value["filename"], "/") == 1) {
            $root_folders[] = $value["filename"];
        }
    }
    if (count($root_folders) > 1) {
        echo "Error: too much root folders found.";
    }
    $root_folder = $root_folders[0];
    $extract_list = array();
    foreach ($tar->listContent() as $value) {
        if (substr($value["filename"], 0, strlen($root_folder)) == $root_folder && strlen($value["filename"]) > strlen($root_folder)) {
            $extract_list[] = $value["filename"];
        }
    }
    $tar->extractList($extract_list, $target_dir, $root_folder, true);
    chmod_r($target_dir, $modes);
}
Ejemplo n.º 4
0
 /**
  * Decompress a tar archive of a site.
  * 
  * @param string $archivePath
  * @param string $decompressDir
  * @return void
  * @access public
  * @since 3/14/08
  */
 public function decompressArchive($archivePath, $decompressDir)
 {
     if (!file_exists($archivePath)) {
         throw new Exception("Archive, '" . basename($archivePath) . "' does not exist.");
     }
     if (!is_readable($archivePath)) {
         throw new Exception("Archive, '" . basename($archivePath) . "' is not readable.");
     }
     // Decompress the archive into our temp-dir
     $archive = new Archive_Tar($archivePath);
     // Check for a containing directory and strip it if needed.
     $content = @$archive->listContent();
     if (!is_array($content) || !count($content)) {
         throw new Exception("Invalid Segue archive. '" . basename($archivePath) . "' is not a valid GZIPed Tar archive.");
     }
     $containerName = null;
     // 			printpre($content);
     if ($content[0]['typeflag'] == 5) {
         $containerName = trim($content[0]['filename'], '/') . '/';
         for ($i = 1; $i < count($content); $i++) {
             // if one of the files isn't in the container, then we don't have a container of all
             if (strpos($content[$i]['filename'], $containerName) === false) {
                 $containerName = null;
                 break;
             }
         }
     }
     // 			printpre($containerName);
     $decompressResult = @$archive->extractModify($decompressDir, $containerName);
     if (!$decompressResult) {
         throw new Exception("Could not decompress Segue archive: '" . basename($archivePath) . "' size, " . ByteSize::withValue(filesize($archivePath))->asString() . ".");
     }
     if (!file_exists($decompressDir . "/site.xml")) {
         throw new Exception("Invalid Segue archive. 'site.xml' was not found in '" . implode("', '", scandir($decompressDir)) . "'.");
     }
 }
Ejemplo n.º 5
0
 public static function getBackupInfo($filename)
 {
     G::LoadThirdParty('pear/Archive', 'Tar');
     $backup = new Archive_Tar($filename);
     //Get a temporary directory in the upgrade directory
     $tempDirectory = PATH_DATA . "upgrade/" . basename(tempnam(__FILE__, ''));
     mkdir($tempDirectory);
     $metafiles = array();
     foreach ($backup->listContent() as $backupFile) {
         $filename = $backupFile["filename"];
         if (strpos($filename, "/") === false && substr_compare($filename, ".meta", -5, 5, true) === 0) {
             if (!$backup->extractList(array($filename), $tempDirectory)) {
                 throw new Exception("Could not extract backup");
             }
             $metafiles[] = "{$tempDirectory}/{$filename}";
         }
     }
     CLI::logging("Found " . count($metafiles) . " workspace(s) in backup\n");
     foreach ($metafiles as $metafile) {
         $data = file_get_contents($metafile);
         $workspaceData = G::json_decode($data);
         CLI::logging("\n");
         workspaceTools::printInfo((array) $workspaceData);
     }
     G::rm_dir($tempDirectory);
 }
 public function submitAddLang()
 {
     global $currentIndex;
     $arr_import_lang = explode('|', Tools::getValue('params_import_language'));
     /* 0 = Language ISO code, 1 = PS version */
     if (Validate::isLangIsoCode($arr_import_lang[0])) {
         if ($content = Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/gzip/' . $arr_import_lang[1] . '/' . $arr_import_lang[0] . '.gzip', false, @stream_context_create(array('http' => array('method' => 'GET', 'timeout' => 5))))) {
             $file = _PS_TRANSLATIONS_DIR_ . $arr_import_lang[0] . '.gzip';
             if (file_put_contents($file, $content)) {
                 $gz = new Archive_Tar($file, true);
                 $files_list = $gz->listContent();
                 if ($gz->extract(_PS_TRANSLATIONS_DIR_ . '../', false)) {
                     $this->checkAndAddMailsFiles($arr_import_lang[0], $files_list);
                     if (!Language::checkAndAddLanguage($arr_import_lang[0])) {
                         $conf = 20;
                     }
                     if (!unlink($file)) {
                         $this->_errors[] = Tools::displayError('Cannot delete archive');
                     }
                     Tools::redirectAdmin($currentIndex . '&conf=' . (isset($conf) ? $conf : '15') . '&token=' . $this->token);
                 }
                 $this->_errors[] = Tools::displayError('Archive cannot be extracted.');
                 if (!unlink($file)) {
                     $this->_errors[] = Tools::displayError('Cannot delete archive');
                 }
             } else {
                 $this->_errors[] = Tools::displayError('Server does not have permissions for writing.');
             }
         } else {
             $this->_errors[] = Tools::displayError('Language not found');
         }
     } else {
         $this->_errors[] = Tools::displayError('Invalid parameter');
     }
 }
Ejemplo n.º 7
0
 /**
  * Install a plugin archive. If pluginName is specified, the archive will
  * only be installed if it contains this plugin.
  *
  * @return bool true if enabled, false otherwise
  */
 function installPluginArchive($filename, $pluginName)
 {
     G::LoadThirdParty("pear/Archive", "Tar");
     $tar = new Archive_Tar($filename);
     $files = $tar->listContent();
     $plugins = array();
     $namePlugin = array();
     foreach ($files as $f) {
         //if (preg_match("/^([\w\.]*).ini$/", $f["filename"], $matches)) {
         if (preg_match("/^(.*pluginConfig)\\.ini\$/", $f["filename"], $matches)) {
             $plugins[] = $matches[1];
         }
         if (preg_match("/^.*({$pluginName})\\.php\$/", $f["filename"], $matches)) {
             $namePlugin[] = $matches[1];
         }
     }
     if (count($plugins) > 1) {
         throw new Exception("Multiple plugins in one archive are not supported currently");
     }
     //if (isset($pluginName) && !in_array($pluginName, $plugins)) {
     if (isset($pluginName) && !in_array($pluginName, $namePlugin)) {
         throw new Exception("Plugin '{$pluginName}' not found in archive");
     }
     //$pluginName = $plugins[0];
     $pluginFile = "{$pluginName}.php";
     /*
     $oldPluginStatus = $this->getStatusPlugin($pluginFile);
     
     if ($pluginStatus != 0) {
       $oldDetails = $this->getPluginDetails($pluginFile);
       $oldVersion = $oldDetails->iVersion;
     } else {
       $oldDetails = NULL;
       $oldVersion = NULL;
     }
     */
     //$pluginIni = $tar->extractInString("$pluginName.ini");
     //$pluginConfig = parse_ini_string($pluginIni);
     /*
     if (!empty($oClass->aDependences)) {
       foreach ($oClass->aDependences as $aDependence) {
         if (file_exists(PATH_PLUGINS . $aDependence['sClassName'] . '.php')) {
           require_once PATH_PLUGINS . $aDependence['sClassName'] . '.php';
           if (!$oPluginRegistry->getPluginDetails($aDependence['sClassName'] . '.php')) {
             throw new Exception('This plugin needs "' . $aDependence['sClassName'] . '" plugin');
           }
         }
         else {
           throw new Exception('This plugin needs "' . $aDependence['sClassName'] . '" plugin');
         }
       }
     }
     unset($oClass);
     if ($fVersionOld > $fVersionNew) {
       throw new Exception('A recent version of this plugin was already installed.');
     }
     */
     $res = $tar->extract(PATH_PLUGINS);
     if (!file_exists(PATH_PLUGINS . $pluginFile)) {
         throw new Exception("File \"{$pluginFile}\" doesn't exist");
     }
     require_once PATH_PLUGINS . $pluginFile;
     $details = $this->getPluginDetails($pluginFile);
     $this->installPlugin($details->sNamespace);
     $this->setupPlugins();
     $this->enablePlugin($details->sNamespace);
     $this->save();
 }
Ejemplo n.º 8
0
}
if (count(explode('.', $BASE_VERSION)) < 3) {
    I2CE::raiseError("Bad version {$BASE_VERSION}");
}
I2CE::raiseError("Base version is {$BASE_VERSION}");
$BASE_VERSION_SHORT = implode('.', array_slice(explode('.', $BASE_VERSION), 0, 2));
$BASE_VERSION_SHORT_NEXT = array_slice(explode('.', $BASE_VERSION), 0, 2);
$BASE_VERSION_SHORT_NEXT[1]++;
$BASE_VERSION_SHORT_NEXT = implode('.', $BASE_VERSION_SHORT_NEXT);
if (!$booleans['read_po_files']) {
    I2CE::raiseError("Using archive: " . realpath($archive));
    $tar = new Archive_Tar($archive);
    $tar->setErrorHandling(PEAR_ERROR_CALLBACK, array('I2CE', 'raiseError'));
    $tar_files = array();
    $tar_dirs = array();
    $files = $tar->listContent();
    foreach ($files as $data) {
        if (!array_key_exists('filename', $data)) {
            continue;
        }
        if ($data['typeflag'] == 5) {
            $tar_dirs[] = $data['filename'];
        } else {
            if ($data['typeflag'] == 0) {
                $tar_files[] = $data['filename'];
            }
        }
    }
    if ($locales == false) {
        $locales = array();
        foreach ($tar_dirs as $dir) {
    case 'bz2':
        $compression = 'bz2';
    case 'tar':
        $compression = null;
        break;
    default:
        echo "Could not determine archive type for {$archive_file}";
}
$tar = new Archive_Tar($archive_file, $compression);
if (!$tar->create(array())) {
    usage("Could not create tar {$archive_file}");
}
$glob = preg_replace('/(\\*|\\?|\\[)/', '[$1]', $translations_dir . DIRECTORY_SEPARATOR) . '*.pot';
foreach (glob($glob) as $file) {
    if (!$tar->addModify($file, 'translations/' . basename($file, '.pot'), $translations_dir)) {
        usage("Could not add {$base}");
    }
}
echo "Created {$archive_file} with:\n";
$contents = $tar->listContent();
foreach ($contents as $content) {
    echo "\t{$content['filename']}\n";
}
echo "Upload translations by browsing to:\n\t";
echo 'https://translations.edge.launchpad.net/' . $module . '/trunk/+translations-upload' . "\n";
# Local Variables:
# mode: php
# c-default-style: "bsd"
# indent-tabs-mode: nil
# c-basic-offset: 4
# End:
Ejemplo n.º 10
0
 /**
  * Returns information about a package file.  Expects the name of
  * a gzipped tar file as input.
  *
  * @param string  $file  name of .tgz file
  *
  * @return array  array with package information
  *
  * @access public
  *
  */
 function infoFromTgzFile($file)
 {
     if (!@is_file($file)) {
         return $this->raiseError("could not open file \"{$file}\"");
     }
     $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)) {
         $file = realpath($file);
         return $this->raiseError("Could not get contents of package \"{$file}\"" . '. Invalid tgz file.');
     }
     $xml = null;
     foreach ($content as $file) {
         $name = $file['filename'];
         if ($name == 'package.xml') {
             $xml = $name;
             break;
         } elseif (ereg('package.xml$', $name, $match)) {
             $xml = $match[0];
             break;
         }
     }
     $tmpdir = System::mkTemp(array('-d', 'pear'));
     $this->addTempFile($tmpdir);
     if (!$xml || !$tar->extractList(array($xml), $tmpdir)) {
         return $this->raiseError('could not extract the package.xml file');
     }
     return $this->infoFromDescriptionFile("{$tmpdir}/{$xml}");
 }
Ejemplo n.º 11
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));
}
Ejemplo n.º 12
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;
 }
Ejemplo n.º 13
0
 protected function _installLanguages($xml, $install_mode = false)
 {
     $attributes = array();
     if (isset($xml->languages->language)) {
         foreach ($xml->languages->language as $data) {
             $attributes = $data->attributes();
             if (Language::getIdByIso($attributes['iso_code'])) {
                 continue;
             }
             $native_lang = Language::getLanguages();
             $native_iso_code = array();
             foreach ($native_lang as $lang) {
                 $native_iso_code[] = $lang['iso_code'];
             }
             // if we are not in an installation context or if the pack is not available in the local directory
             if (!$install_mode || !in_array((string) $attributes['iso_code'], $native_iso_code)) {
                 $errno = 0;
                 $errstr = '';
                 if (!@fsockopen('api.prestashop.com', 80, $errno, $errstr, 5)) {
                     $this->_errors[] = Tools::displayError('Archive cannot be downloaded from prestashop.com.');
                 } elseif (!($lang_pack = Tools::jsonDecode(Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/get_language_pack.php?version=' . _PS_VERSION_ . '&iso_lang=' . $attributes['iso_code'])))) {
                     $this->_errors[] = Tools::displayError('Error occurred when language was checked according to your Prestashop version.');
                 } elseif ($content = Tools::file_get_contents('http://translations.prestashop.com/download/lang_packs/gzip/' . $lang_pack->version . '/' . $attributes['iso_code'] . '.gzip')) {
                     $file = _PS_TRANSLATIONS_DIR_ . $attributes['iso_code'] . '.gzip';
                     if (file_put_contents($file, $content)) {
                         $gz = new Archive_Tar($file, true);
                         $files_list = $gz->listContent();
                         if (!$gz->extract(_PS_TRANSLATIONS_DIR_ . '../', false)) {
                             $this->_errors[] = Tools::displayError('Cannot decompress the translation file for the following language: ') . (string) $attributes['iso_code'];
                             return false;
                         } else {
                             AdminTranslationsController::checkAndAddMailsFiles($attributes['iso_code'], $files_list);
                             AdminTranslationsController::addNewTabs($attributes['iso_code'], $files_list);
                         }
                         if (!Language::checkAndAddLanguage((string) $attributes['iso_code'])) {
                             $this->_errors[] = Tools::displayError('An error occurred while creating the language: ') . (string) $attributes['iso_code'];
                             return false;
                         }
                         @unlink($file);
                     } else {
                         $this->_errors[] = Tools::displayError('Server does not have permissions for writing.');
                     }
                 }
             }
         }
     }
     // change the default language if there is only one language in the localization pack
     if (!count($this->_errors) && $install_mode && isset($attributes['iso_code']) && count($xml->languages->language) == 1) {
         $this->iso_code_lang = $attributes['iso_code'];
     }
     return true;
 }
Ejemplo n.º 14
0
 function _doTAR($upfile, $path)
 {
     // get validator object
     $validate = get_validator('upload');
     // check file exists, ask overwrite ... todo
     // get required pear-class
     require_once "Archive/Tar.php";
     //
     $tar = new Archive_Tar($upfile);
     $dir = $this->upload_dir . $path;
     $dir = substr($dir, 0, strlen($dir) - 1);
     $tarfiles = array();
     if (($v_list = $tar->listContent()) != 0) {
         $max = count($v_list);
         // get a list of files to extract regadring the restrictions on filenames and directories
         // since we can not rename file while extracting, all filenames may not include special chars
         // and the trouble_chars that are set in the configuration
         // aborts the extraction if a invalid directory name is in the tar-file
         for ($i = 0; $i < $max; $i++) {
             $name = $v_list[$i]['filename'];
             if (empty($v_list[$i]['typeflag'])) {
                 // compressed file
                 if ($validate->filename($tar_name, $this->cfg_cms['trouble_chars'])) {
                     $tarfiles[] = $name;
                 } else {
                     $this->error_files[] = $name;
                 }
             } else {
                 // directory
                 if (!$validate->filepath($tar_name, true, $this->cfg_cms['trouble_chars'])) {
                     $this->errno = '1422';
                     return;
                 }
                 $tarfiles[] = $name;
             }
         }
         $tar->extractList($tarfiles, $dir);
     }
 }
Ejemplo n.º 15
0
 /**
  * Get list of files in the bundle
  *
  * @return array
  */
 public function getFiles()
 {
     $tar = new BundleArchive($this->getInputFile());
     return $tar->listContent();
 }
Ejemplo n.º 16
0
/**
* Unpack a db backup file, if necessary
*
* Note: This requires a minimal PEAR setup (incl. Tar and Zip classes) and a
*       way to set the PEAR include path. But if that doesn't work on your
*       setup, then chances are you won't get Geeklog up and running anyway ...
*
* @param    string  $backup_path    path to the "backups" directory
* @param    string  $backup_file    backup file name
* @param    ref     $display        reference to HTML string (for error msg)
* @return   mixed                   file name of unpacked file or false: error
*
*/
function INST_unpackFile($backup_path, $backup_file, &$display)
{
    global $_CONF, $LANG_MIGRATE;
    $unpacked_file = $backup_file;
    $type = '';
    if (preg_match('/\\.zip$/i', $backup_file)) {
        $type = 'zip';
    } elseif (preg_match('/\\.tar.gz$/i', $backup_file) || preg_match('/\\.tgz$/i', $backup_file)) {
        $type = 'tar';
    }
    if (empty($type)) {
        // not packed
        return $backup_file;
    }
    $include_path = get_include_path();
    if (set_include_path($_CONF['path'] . 'system/pear/' . PATH_SEPARATOR . $include_path) === false) {
        // couldn't set PEAR path - can't handle compressed backups
        $display .= INST_getAlertMsg($LANG_MIGRATE[39]);
        return false;
    }
    if ($type == 'zip') {
        require_once 'Archive/Zip.php';
        $archive = new Archive_Zip($backup_path . $backup_file);
    } else {
        require_once 'Archive/Tar.php';
        $archive = new Archive_Tar($backup_path . $backup_file);
    }
    // we're going to extract the first .sql file we find in the archive
    $found_sql_file = false;
    $files = $archive->listContent();
    foreach ($files as $file) {
        if (!isset($file['folder']) || !$file['folder']) {
            if (preg_match('/\\.sql$/', $file['filename'])) {
                $dirname = preg_replace('/\\/.*$/', '', $file['filename']);
                $found_sql_file = true;
                break;
            }
        }
    }
    if (!$found_sql_file) {
        // no .sql file found in archive
        $display .= INST_getAlertMsg(sprintf($LANG_MIGRATE[40], $backup_file));
        return false;
    }
    if ($dirname == $file['filename']) {
        $dirname = '';
        // no directory
    }
    if (empty($dirname)) {
        $unpacked_file = $file['filename'];
    } else {
        $unpacked_file = substr($file['filename'], strlen($dirname) + 1);
    }
    $success = false;
    if ($type == 'zip') {
        $result = $archive->extract(array('add_path' => $backup_path, 'by_name' => array($file['filename']), 'remove_path' => $dirname));
        if (is_array($result)) {
            $success = true;
        }
    } else {
        $result = $archive->extractList(array($file['filename']), $backup_path, $dirname);
        $success = $result;
    }
    if (!$success || !file_exists($backup_path . $unpacked_file)) {
        // error unpacking file
        $display .= INST_getAlertMsg(sprintf($LANG_MIGRATE[41], $unpacked_file));
        return false;
    }
    unset($archive);
    return $unpacked_file;
}
Ejemplo n.º 17
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);
}
Ejemplo n.º 18
0
 public function submitAddLang()
 {
     $arr_import_lang = explode('|', Tools::getValue('params_import_language'));
     /* 0 = Language ISO code, 1 = PS version */
     if (Validate::isLangIsoCode($arr_import_lang[0])) {
         $array_stream_context = @stream_context_create(array('http' => array('method' => 'GET', 'timeout' => 10)));
         $content = Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/gzip/' . $arr_import_lang[1] . '/' . Tools::strtolower($arr_import_lang[0]) . '.gzip', false, $array_stream_context);
         if ($content) {
             $file = _PS_TRANSLATIONS_DIR_ . $arr_import_lang[0] . '.gzip';
             if ((bool) @file_put_contents($file, $content)) {
                 $gz = new \Archive_Tar($file, true);
                 if (_PS_MODE_DEV_) {
                     $gz->setErrorHandling(PEAR_ERROR_TRIGGER, E_USER_WARNING);
                 }
                 $files_list = AdminTranslationsController::filterTranslationFiles($gz->listContent());
                 if ($error = $gz->extractList(AdminTranslationsController::filesListToPaths($files_list), _PS_TRANSLATIONS_DIR_ . '../')) {
                     if (is_object($error) && !empty($error->message)) {
                         $this->errors[] = $this->trans('The archive cannot be extracted.', array(), 'Admin.International.Notification') . ' ' . $error->message;
                     } else {
                         if (!Language::checkAndAddLanguage($arr_import_lang[0])) {
                             $conf = 20;
                         } else {
                             // Reset cache
                             Language::loadLanguages();
                             // Clear smarty modules cache
                             Tools::clearCache();
                             AdminTranslationsController::checkAndAddMailsFiles($arr_import_lang[0], $files_list);
                             if ($tab_errors = AdminTranslationsController::addNewTabs($arr_import_lang[0], $files_list)) {
                                 $this->errors += $tab_errors;
                             }
                         }
                         if (!unlink($file)) {
                             $this->errors[] = sprintf($this->trans('Cannot delete the archive %s.', array(), 'Admin.International.Notification'), $file);
                         }
                         //fetch cldr datas for the new imported locale
                         $languageCode = explode('-', Language::getLanguageCodeByIso($arr_import_lang[0]));
                         $cldrUpdate = new Update(_PS_TRANSLATIONS_DIR_);
                         $cldrUpdate->fetchLocale($languageCode[0] . '-' . Tools::strtoupper($languageCode[1]));
                         $this->redirect(false, isset($conf) ? $conf : '15');
                     }
                 } else {
                     $this->errors[] = sprintf($this->trans('Cannot decompress the translation file for the following language: %s', array(), 'Admin.International.Notification'), $arr_import_lang[0]);
                     $checks = array();
                     foreach ($files_list as $f) {
                         if (isset($f['filename'])) {
                             if (is_file(_PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . $f['filename']) && !is_writable(_PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . $f['filename'])) {
                                 $checks[] = dirname($f['filename']);
                             } elseif (is_dir(_PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . $f['filename']) && !is_writable(_PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . dirname($f['filename']))) {
                                 $checks[] = dirname($f['filename']);
                             }
                         }
                     }
                     $checks = array_unique($checks);
                     foreach ($checks as $check) {
                         $this->errors[] = sprintf($this->trans('Please check rights for folder and files in %s', array(), 'Admin.Notifications.Error'), $check);
                     }
                     if (!unlink($file)) {
                         $this->errors[] = sprintf($this->trans('Cannot delete the archive %s.', array(), 'Admin.International.Notification'), $file);
                     }
                 }
             } else {
                 $this->errors[] = $this->trans('The server does not have permissions for writing.', array(), 'Admin.Notifications.Error') . ' ' . sprintf($this->trans('Please check rights for %s', array(), 'Admin.Notifications.Error'), dirname($file));
             }
         } else {
             $this->errors[] = $this->trans('Language not found.', array(), 'Admin.International.Notification');
         }
     } else {
         $this->errors[] = $this->trans('Invalid parameter.', array(), 'Admin.Notifications.Error');
     }
 }
Ejemplo n.º 19
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']);
     }
 }
Ejemplo n.º 20
0
 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;
 }
 /**
  *
  * 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;
 }
Ejemplo n.º 22
0
 public static function is_tar($path)
 {
     require_once 'Archive/Tar.php';
     if (!($tar = new Archive_Tar($path))) {
         return false;
     }
     $list = $tar->listContent();
     if (empty($list)) {
         return false;
     }
     switch ($tar->_compress_type) {
         case 'gz':
             return 'application/x-gzip';
         case 'bz2':
             return 'application/x-bzip2';
         case 'none':
             return 'application/x-tar';
     }
     return false;
 }
Ejemplo n.º 23
0
 /**
  * setInputFilePost
  *
  * @access private
  * @return void
  */
 private function setInputFilePost()
 {
     $bCli = php_sapi_name() == 'cli';
     // ArrayNested->off()
     if ($bCli and $this->mPreInputFiles == STDIN) {
         $mInputFiles = array(STDIN);
     } else {
         $mInputFiles = array();
         foreach ($this->mPreInputFiles as $sPath) {
             $mInputFiles = array_merge($mInputFiles, PHP_Beautifier_Common::getFilesByGlob($sPath, $this->bRecursive));
         }
     }
     // now, we create stream references for compressed files....
     foreach ($mInputFiles as $sFile) {
         // First, tar files
         if (!($bCli and $sFile == STDIN) and preg_match("/(.tgz|\\.tar\\.gz|\\.tar\\.bz2|\\.tar)\$/", $sFile, $aMatch)) {
             if (strpos($aMatch[1], 'gz') !== false) {
                 $sCompress = 'gz';
             } elseif (strpos($aMatch[1], 'bz2') !== false) {
                 $sCompress = 'bz2';
             } elseif (strpos($aMatch[1], 'tar') !== false) {
                 $sCompress = false;
             }
             $oTar = new Archive_Tar($sFile, $sCompress);
             foreach ($oTar->listContent() as $aInput) {
                 if (empty($aInput['typeflag'])) {
                     $this->mInputFiles[] = 'tarz://' . $sFile . '#' . $aInput['filename'];
                 }
             }
         } else {
             $this->mInputFiles[] = $sFile;
         }
     }
     if (!$this->mInputFiles) {
         throw new Exception("Can't match any file");
     }
     return true;
     // ArrayNested->on()
 }
Ejemplo n.º 24
0
 public function submitAddLang()
 {
     $arr_import_lang = explode('|', Tools::getValue('params_import_language'));
     /* 0 = Language ISO code, 1 = PS version */
     if (Validate::isLangIsoCode($arr_import_lang[0])) {
         $array_stream_context = @stream_context_create(array('http' => array('method' => 'GET', 'timeout' => 10)));
         $content = Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/gzip/' . $arr_import_lang[1] . '/' . Tools::strtolower($arr_import_lang[0]) . '.gzip', false, $array_stream_context);
         if ($content) {
             $file = _PS_TRANSLATIONS_DIR_ . $arr_import_lang[0] . '.gzip';
             if ((bool) @file_put_contents($file, $content)) {
                 require_once _PS_TOOL_DIR_ . '/tar/Archive_Tar.php';
                 $gz = new Archive_Tar($file, true);
                 $files_list = AdminTranslationsController::filterTranslationFiles($gz->listContent());
                 if ($error = $gz->extractList(AdminTranslationsController::filesListToPaths($files_list), _PS_TRANSLATIONS_DIR_ . '../')) {
                     if (is_object($error) && !empty($error->message)) {
                         $this->errors[] = Tools::displayError('The archive cannot be extracted.') . ' ' . $error->message;
                     } else {
                         if (!Language::checkAndAddLanguage($arr_import_lang[0])) {
                             $conf = 20;
                         } else {
                             // Reset cache
                             Language::loadLanguages();
                             // Clear smarty modules cache
                             Tools::clearCache();
                             AdminTranslationsController::checkAndAddMailsFiles($arr_import_lang[0], $files_list);
                             if ($tab_errors = AdminTranslationsController::addNewTabs($arr_import_lang[0], $files_list)) {
                                 $this->errors += $tab_errors;
                             }
                         }
                         if (!unlink($file)) {
                             $this->errors[] = sprintf(Tools::displayError('Cannot delete the archive %s.'), $file);
                         }
                         $this->redirect(false, isset($conf) ? $conf : '15');
                     }
                 } elseif (!unlink($file)) {
                     $this->errors[] = sprintf(Tools::displayError('Cannot delete the archive %s.'), $file);
                 }
             } else {
                 $this->errors[] = Tools::displayError('The server does not have permissions for writing.') . ' ' . sprintf(Tools::displayError('Please check rights for %s'), dirname($file));
             }
         } else {
             $this->errors[] = Tools::displayError('Language not found.');
         }
     } else {
         $this->errors[] = Tools::displayError('Invalid parameter');
     }
 }
Ejemplo n.º 25
0
function importSkin()
{
    try {
        if (!isset($_FILES['uploadedFile'])) {
            throw new Exception(G::LoadTranslation('ID_SKIN_FILE_REQUIRED'));
        }
        $uploadedInstances = count($_FILES['uploadedFile']['name']);
        $sw_error = false;
        $sw_error_exists = isset($_FILES['uploadedFile']['error']);
        $emptyInstances = 0;
        $quequeUpload = array();
        // upload files & check for errors
        $tmp = $_FILES['uploadedFile']['tmp_name'];
        $items = stripslashes($_FILES['uploadedFile']['name']);
        if ($sw_error_exists) {
            $up_err = $_FILES['uploadedFile']['error'];
        } else {
            $up_err = file_exists($tmp) ? 0 : 4;
        }
        if ($items == "" || $up_err == 4) {
            throw new Exception(G::LoadTranslation('ID_SKIN_FILE_REQUIRED'));
        }
        if ($up_err == 1 || $up_err == 2) {
            throw new Exception(G::LoadTranslation('ID_FILE_TOO_BIG'));
            //$errors[$i]='miscfilesize';
        }
        if ($up_err == 3) {
            throw new Exception(G::LoadTranslation('ID_ERROR_UPLOAD_FILE_CONTACT_ADMINISTRATOR'));
            //$errors[$i]='miscfilepart';
        }
        if (!@is_uploaded_file($tmp)) {
            throw new Exception(G::LoadTranslation('ID_ERROR_UPLOAD_FILE_CONTACT_ADMINISTRATOR'));
            //$errors[$i]='uploadfile';
        }
        $fileInfo = pathinfo($items);
        $validType = array('tar', 'gz');
        if (!in_array($fileInfo['extension'], $validType)) {
            throw new Exception(G::LoadTranslation('ID_FILE_UPLOAD_INCORRECT_EXTENSION'));
            //$errors[$i]='wrongtype';
        }
        $filename = $items;
        $tempPath = PATH_CUSTOM_SKINS . '.tmp' . PATH_SEP;
        G::verifyPath($tempPath, true);
        $tempName = $tmp;
        G::uploadFile($tempName, $tempPath, $filename);
        G::LoadThirdParty('pear/Archive', 'Tar');
        $tar = new Archive_Tar($tempPath . $filename);
        $aFiles = $tar->listContent();
        $swConfigFile = false;
        foreach ($aFiles as $key => $val) {
            if (basename($val['filename']) == 'config.xml') {
                $skinName = dirname($val['filename']);
                $skinArray = explode("/", $skinName);
                if (count($skinArray) == 1) {
                    $swConfigFile = true;
                }
            }
        }
        if (!$swConfigFile) {
            @unlink(PATH_CUSTOM_SKINS . '.tmp' . PATH_SEP . $filename);
            throw new Exception(G::LoadTranslation('ID_SKIN_CONFIGURATION_MISSING'));
        }
        if (is_dir(PATH_CUSTOM_SKINS . $skinName)) {
            if (isset($_REQUEST['overwrite_files']) && $_REQUEST['overwrite_files'] == 'on') {
                G::rm_dir(PATH_CUSTOM_SKINS . $skinName, false);
            } else {
                throw new Exception(G::LoadTranslation('ID_SKIN_ALREADY_EXISTS'));
            }
        }
        $res = $tar->extract(PATH_CUSTOM_SKINS);
        if (!$res) {
            throw new Exception(G::LoadTranslation('ID_SKIN_ERROR_EXTRACTING'));
        }
        $configFileOriginal = PATH_CUSTOM_SKINS . $skinName . PATH_SEP . 'config.xml';
        $configFileFinal = PATH_CUSTOM_SKINS . $skinName . PATH_SEP . 'config.xml';
        $xmlConfiguration = file_get_contents($configFileOriginal);
        $workspace = $_REQUEST['workspace'] == 'global' ? '' : SYS_SYS;
        $xmlConfigurationObj = G::xmlParser($xmlConfiguration);
        $skinInformationArray = $xmlConfigurationObj->result["skinConfiguration"]["__CONTENT__"]["information"]["__CONTENT__"];
        if (isset($skinInformationArray["workspace"]["__VALUE__"])) {
            $workspace = $workspace != "" && !empty($skinInformationArray["workspace"]["__VALUE__"]) ? $skinInformationArray["workspace"]["__VALUE__"] . "|" . $workspace : $workspace;
            $xmlConfiguration = preg_replace("/(<workspace>)(.*)(<\\/workspace>)/i", "<workspace>" . $workspace . "</workspace><!-- \$2 -->", $xmlConfiguration);
        } else {
            $xmlConfiguration = preg_replace("/(<name>)(.*)(<\\/name>)/i", "<name>" . $skinName . "</name><!-- \$2 -->\n<workspace>" . $workspace . "</workspace>", $xmlConfiguration);
        }
        file_put_contents($configFileFinal, $xmlConfiguration);
        //Delete Temporal
        @unlink(PATH_CUSTOM_SKINS . '.tmp' . PATH_SEP . $filename);
        $response['success'] = true;
        $response['message'] = G::LoadTranslation('ID_SKIN_SUCCESSFUL_IMPORTED');
        G::auditLog("ImportSkin", "Skin Name: " . $skinName);
        print_r(G::json_encode($response));
    } catch (Exception $e) {
        $response['success'] = false;
        $response['message'] = $e->getMessage();
        $response['error'] = $e->getMessage();
        print_r(G::json_encode($response));
    }
}
 /**
  * uploadモードのパラメーター検証を行う.
  *
  * @param  SC_FormParam $objFormParam SC_FormParamのインスタンス
  * @param  SC_UploadFile_Ex $objUpFile    SC_UploadFileのインスタンス
  * @return array  エラー情報を格納した連想配列, エラーが無ければ(多分)nullを返す
  */
 public function lfCheckError(&$objFormParam, &$objUpFile)
 {
     $arrErr = $objFormParam->checkError();
     $template_code = $objFormParam->getValue('template_code');
     // 同名のフォルダが存在する場合はエラー
     if (file_exists(USER_TEMPLATE_REALDIR . $template_code) && $template_code != "") {
         $arrErr['template_code'] = '※ 同名のファイルがすでに存在します。<br/>';
     }
     // 登録不可の文字列チェック
     $arrIgnoreCode = array('admin', MOBILE_DEFAULT_TEMPLATE_NAME, SMARTPHONE_DEFAULT_TEMPLATE_NAME, DEFAULT_TEMPLATE_NAME);
     if (in_array($template_code, $arrIgnoreCode)) {
         $arrErr['template_code'] = '※ このテンプレートコードは使用できません。<br/>';
     }
     // DBにすでに登録されていないかチェック
     $objQuery =& SC_Query_Ex::getSingletonInstance();
     $exists = $objQuery->exists('dtb_templates', 'template_code = ?', array($template_code));
     if ($exists) {
         $arrErr['template_code'] = '※ すでに登録されているテンプレートコードです。<br/>';
     }
     /*
      * ファイル形式チェック
      * ファイルが壊れていることも考慮して, 展開可能かチェックする.
      */
     $tar = new Archive_Tar($_FILES['template_file']['tmp_name'], true);
     $arrArchive = $tar->listContent();
     if (!is_array($arrArchive)) {
         $arrErr['template_file'] = '※ テンプレートファイルが解凍できません。許可されている形式は、tar/tar.gzです。<br />';
     } else {
         $make_temp_error = $objUpFile->makeTempFile('template_file', false);
         if (!SC_Utils_Ex::isBlank($make_temp_error)) {
             $arrErr['template_file'] = $make_temp_error;
         }
     }
     return $arrErr;
 }
Ejemplo n.º 27
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;
     }
 }
Ejemplo n.º 28
0
 /**
  * アーカイブ内に指定のファイルが存在するかを判定します.
  *
  * @param  Archive_Tar $tar_obj
  * @param  string      $file_path 判定するファイルパス
  * @return boolean
  */
 public function checkContainsFile($tar_obj, $file_path)
 {
     // ファイル一覧を取得
     $arrayFile = $tar_obj->listContent();
     foreach ($arrayFile as $value) {
         if ($value['filename'] === $file_path) {
             return true;
         }
     }
     return false;
 }
Ejemplo n.º 29
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;
 }
Ejemplo n.º 30
0
function upload_scenarios()
{
    if (!array_key_exists('upload', $_FILES) || $_FILES['upload']['error']['filename']) {
        return false;
    } else {
        $file = $_FILES['upload']['tmp_name'];
    }
    // Define the PEAR installation path
    ini_set('include_path', MAX_PATH . '/lib/pear');
    require_once MAX_PATH . '/lib/pear/Archive/Tar.php';
    $oTar = new Archive_Tar("{$file}");
    $tmpdir = getcwd();
    chdir(SIM_PATH);
    $aResult = $oTar->listContent();
    $oTar->extract();
    chdir($tmpdir);
    unlink($_FILES['upload']['tmp_name']);
    return $aResult;
}