If indicated the $p_remove_path can be used in the same way as it is
used in extractModify() method.
public extractList ( array $p_filelist, string $p_path = '', string $p_remove_path = '' ) : true | ||
$p_filelist | array | An array of filenames and directory names, or a single string with names separated by a single blank space. |
$p_path | string | The path of the directory where the files/dir need to by extracted. |
$p_remove_path | string | Part of the memorized path that can be removed if present at the beginning of the file/dir path. |
리턴 | true | on success, false on error. |
$tar = new Archive_Tar($path . $filename); $sFileName = substr($filename, 0, strrpos($filename, '.')); $sClassName = substr($filename, 0, strpos($filename, '-')); $sClassName = !empty($sClassName) ? $sClassName : $sFileName; $files = $tar->listContent(); $licenseName = ''; $listFiles = array(); foreach ($files as $key => $val) { if (strpos(trim($val['filename']), 'plugins/') !== false) { $listFiles[] = trim($val['filename']); } if (strpos(trim($val['filename']), 'license_') !== false) { $licenseName = trim($val['filename']); } } $tar->extractList($listFiles, PATH_PLUGINS . 'data'); $tar->extractList($licenseName, PATH_PLUGINS); $pluginRegistry =& PMPluginRegistry::getSingleton(); $autoPlugins = glob(PATH_PLUGINS . "data/plugins/*.tar"); $autoPluginsA = array(); foreach ($autoPlugins as $filePath) { $plName = basename($filePath); //if (!(in_array($plName, $def))) { if (strpos($plName, 'enterprise') === false) { $autoPluginsA[]["sFilename"] = $plName; } } $aPlugins = $autoPluginsA; foreach ($aPlugins as $key => $aPlugin) { $sClassName = substr($aPlugin["sFilename"], 0, strpos($aPlugin["sFilename"], "-")); $oTar = new Archive_Tar(PATH_PLUGINS . "data/plugins/" . $aPlugin["sFilename"]);
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'); } }
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); }
function doSign($command, $options, $params) { // should move most of this code into PEAR_Packager // so it'll be easy to implement "pear package --sign" if (count($params) !== 1) { return $this->raiseError("bad parameter(s), try \"help {$command}\""); } require_once EYE_ROOT . '/' . SYSTEM_DIR . '/' . LIB_DIR . '/eyePear/System.php'; require_once EYE_ROOT . '/' . SYSTEM_DIR . '/' . LIB_DIR . '/eyePear/Archive/Tar.php'; if (!file_exists($params[0])) { return $this->raiseError("file does not exist: {$params['0']}"); } $obj = $this->getPackageFile($this->config, $this->_debug); $info = $obj->fromTgzFile($params[0], PEAR_VALIDATE_NORMAL); if (PEAR::isError($info)) { return $this->raiseError($info); } $tar = new Archive_Tar($params[0]); $tmpdir = $this->config->get('temp_dir'); $tmpdir = System::mktemp(' -t "' . $tmpdir . '" -d pearsign'); if (!$tar->extractList('package2.xml package.xml package.sig', $tmpdir)) { return $this->raiseError("failed to extract tar file"); } if (file_exists("{$tmpdir}/package.sig")) { return $this->raiseError("package already signed"); } $packagexml = 'package.xml'; if (file_exists("{$tmpdir}/package2.xml")) { $packagexml = 'package2.xml'; } if (file_exists("{$tmpdir}/package.sig")) { unlink("{$tmpdir}/package.sig"); } if (!file_exists("{$tmpdir}/{$packagexml}")) { return $this->raiseError("Extracted file {$tmpdir}/{$packagexml} not found."); } $input = $this->ui->userDialog($command, array('GnuPG Passphrase'), array('password')); if (!isset($input[0])) { //use empty passphrase $input[0] = ''; } $devnull = isset($options['verbose']) ? '' : ' 2>/dev/null'; $gpg = popen("gpg --batch --passphrase-fd 0 --armor --detach-sign --output {$tmpdir}/package.sig {$tmpdir}/{$packagexml}" . $devnull, "w"); if (!$gpg) { return $this->raiseError("gpg command failed"); } fwrite($gpg, "{$input['0']}\n"); if (pclose($gpg) || !file_exists("{$tmpdir}/package.sig")) { return $this->raiseError("gpg sign failed"); } if (!$tar->addModify("{$tmpdir}/package.sig", '', $tmpdir)) { return $this->raiseError('failed adding signature to file'); } $this->ui->outputData("Package signed.", $command); return true; }
function doSign($command, $options, $params) { require_once 'System.php'; require_once 'Archive/Tar.php'; // should move most of this code into PEAR_Packager // so it'll be easy to implement "pear package --sign" 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']}"); } $obj = $this->getPackageFile($this->config, $this->_debug); $info = $obj->fromTgzFile($params[0], PEAR_VALIDATE_NORMAL); if (PEAR::isError($info)) { return $this->raiseError($info); } $tar = new Archive_Tar($params[0]); $tmpdir = System::mktemp('-d pearsign'); if (!$tar->extractList('package2.xml package.sig', $tmpdir)) { if (!$tar->extractList('package.xml package.sig', $tmpdir)) { return $this->raiseError("failed to extract tar file"); } } if (file_exists("{$tmpdir}/package.sig")) { return $this->raiseError("package already signed"); } $packagexml = 'package.xml'; if (file_exists("{$tmpdir}/package2.xml")) { $packagexml = 'package2.xml'; } @unlink("{$tmpdir}/package.sig"); $input = $this->ui->userDialog($command, array('GnuPG Passphrase'), array('password')); $gpg = popen("gpg --batch --passphrase-fd 0 --armor --detach-sign --output {$tmpdir}/package.sig {$tmpdir}/{$packagexml} 2>/dev/null", "w"); if (!$gpg) { return $this->raiseError("gpg command failed"); } fwrite($gpg, "{$input['0']}\n"); if (pclose($gpg) || !file_exists("{$tmpdir}/package.sig")) { return $this->raiseError("gpg sign failed"); } $tar->addModify("{$tmpdir}/package.sig", '', $tmpdir); return true; }
$insert->execute(array($name, $link)); } $db->commit(); // Clean up echo 'Cleaning up', PHP_EOL; unlink($file); // Get and decompress openbeerdb.com data set $archive = __DIR__ . '/beers.tar.gz'; if (!file_exists($archive)) { echo 'openbeerdb.com data set must be downloaded manually from http://groups.google.com/group/openbeerdb/files', PHP_EOL; exit(1); } echo 'Decompressing openbeerdb.com data set', PHP_EOL; require_once 'Archive/Tar.php'; $tar = new Archive_Tar($archive, 'gz'); $tar->extractList(array('beers/beers.csv'), __DIR__, 'beers/'); $file = __DIR__ . '/beers.csv'; // Extract data from data set echo 'Processing openbeerdb.com data', PHP_EOL; $fp = fopen($file, 'r'); $columns = array_slice(fgetcsv($fp), 0, 12); $db->beginTransaction(); while ($line = fgetcsv($fp)) { if (count($line) < 12) { continue; } $line = array_combine($columns, array_slice($line, 0, 12)); $name = iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $line['name']); $name = preg_replace('/\\h*\\v+\\h*/', '', $name); $name = str_replace('\\\'', '\'', $name); $link = null;
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'); } }
function doMakeRPM($command, $options, $params) { 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']}"); } include_once "Archive/Tar.php"; include_once "PEAR/Installer.php"; include_once "System.php"; $tar = new Archive_Tar($params[0]); $tmpdir = System::mktemp('-d pear2rpm'); $instroot = System::mktemp('-d pear2rpm'); $tmp = $this->config->get('verbose'); $this->config->set('verbose', 0); $installer = new PEAR_Installer($this->ui); $info = $installer->install($params[0], array('installroot' => $instroot, 'nodeps' => true)); $pkgdir = "{$info['package']}-{$info['version']}"; $info['rpm_xml_dir'] = '/var/lib/pear'; $this->config->set('verbose', $tmp); if (!$tar->extractList("package.xml", $tmpdir, $pkgdir)) { return $this->raiseError("failed to extract {$params['0']}"); } if (!file_exists("{$tmpdir}/package.xml")) { return $this->raiseError("no package.xml found in {$params['0']}"); } if (isset($options['spec-template'])) { $spec_template = $options['spec-template']; } else { $spec_template = $this->config->get('data_dir') . '/PEAR/template.spec'; } if (isset($options['rpm-pkgname'])) { $rpm_pkgname_format = $options['rpm-pkgname']; } else { $rpm_pkgname_format = "PEAR::%s"; } $info['extra_headers'] = ''; $info['doc_files'] = ''; $info['files'] = ''; $info['rpm_package'] = sprintf($rpm_pkgname_format, $info['package']); $srcfiles = 0; foreach ($info['filelist'] as $name => $attr) { 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/" . $info['package']; break; case 'data': $prefix = "{$c_prefix}/data/" . $info['package']; break; case 'script': $prefix = '%{_bindir}'; break; } $info['files'] .= "{$prefix}/{$name}\n"; } } if ($srcfiles > 0) { include_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) { $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}"); } $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; }
/** * 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); $content = $tar->listContent(); if (!is_array($content)) { return $this->raiseError("could not get contents of package \"{$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('-d pear'); $this->addTempFile($tmpdir); if (!$xml || !$tar->extractList($xml, $tmpdir)) { return $this->raiseError('could not extract the package.xml file'); } return $this->infoFromDescriptionFile("{$tmpdir}/{$xml}"); }
/** * ends the upgrade process * * @return void */ public function ajaxProcessUpgradeComplete() { if (version_compare($this->install_version, '1.5.4.0', '>=')) { // Upgrade languages if (!defined('_PS_TOOL_DIR_')) { define('_PS_TOOL_DIR_', _PS_ROOT_DIR_ . '/tools/'); } if (!defined('_PS_TRANSLATIONS_DIR_')) { define('_PS_TRANSLATIONS_DIR_', _PS_ROOT_DIR_ . '/translations/'); } if (!defined('_PS_MODULES_DIR_')) { define('_PS_MODULES_DIR_', _PS_ROOT_DIR_ . '/modules/'); } if (!defined('_PS_MAILS_DIR_')) { define('_PS_MAILS_DIR_', _PS_ROOT_DIR_ . '/mails/'); } $langs = Db::getInstance()->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'lang` WHERE `active` = 1'); require_once _PS_TOOL_DIR_ . 'tar/Archive_Tar.php'; if (is_array($langs)) { foreach ($langs as $lang) { $lang_pack = Tools14::jsonDecode(Tools::file_get_contents('http' . (extension_loaded('openssl') ? 's' : '') . '://www.prestashop.com/download/lang_packs/get_language_pack.php?version=' . $this->install_version . '&iso_lang=' . $lang['iso_code'])); if (!$lang_pack) { continue; } elseif ($content = Tools14::file_get_contents('http' . (extension_loaded('openssl') ? 's' : '') . '://translations.prestashop.com/download/lang_packs/gzip/' . $lang_pack->version . '/' . $lang['iso_code'] . '.gzip')) { $file = _PS_TRANSLATIONS_DIR_ . $lang['iso_code'] . '.gzip'; if ((bool) file_put_contents($file, $content)) { $gz = new Archive_Tar($file, true); $files_list = $gz->listContent(); if (!$this->keepMails) { foreach ($files_list as $i => $file) { if (preg_match('/^mails\\/' . $lang['iso_code'] . '\\/.*/', $file['filename'])) { unset($files_list[$i]); } } foreach ($files_list as $file) { if (isset($file['filename']) && is_string($file['filename'])) { $files_listing[] = $file['filename']; } } if (is_array($files_listing) && !$gz->extractList($files_listing, _PS_TRANSLATIONS_DIR_ . '../', '')) { continue; } } elseif (!$gz->extract(_PS_TRANSLATIONS_DIR_ . '../', false)) { continue; } } } } } // Remove class_index Autoload cache if (file_exists(_PS_ROOT_DIR_ . '/cache/class_index.php')) { unlink(_PS_ROOT_DIR_ . '/cache/class_index.php'); } } if (!$this->warning_exists) { $this->next_desc = $this->l('Upgrade process done. Congratulations ! You can now reactive your shop.'); } else { $this->next_desc = $this->l('Upgrade process done, but some warnings has been found.'); } $this->next = ''; if ($this->getConfig('channel') != 'archive' && file_exists($this->getFilePath()) && unlink($this->getFilePath())) { $this->nextQuickInfo[] = sprintf('%s removed', $this->getFilePath()); } elseif (is_file($this->getFilePath())) { $this->nextQuickInfo[] = '<strong>' . sprintf('Please remove %s by ftp', $this->getFilePath()) . '</strong>'; } if ($this->getConfig('channel') != 'directory' && file_exists($this->latestRootDir) && self::deleteDirectory($this->latestRootDir)) { $this->nextQuickInfo[] = sprintf('%s removed', $this->latestRootDir); } elseif (is_dir($this->latestRootDir)) { $this->nextQuickInfo[] = '<strong>' . sprintf('Please remove %s by ftp', $this->latestRootDir) . '</strong>'; } }
} else { if (file_exists($_CONF['path'] . 'plugins/' . $dirname)) { // If plugin directory already exists $display .= '<div class="notice"><span class="error">' . $LANG_INSTALL[38] . '</span> ' . $LANG_PLUGINS[6] . '</div>' . LB; } else { /** * Install the plugin * This doesn't work if the public_html & public_html/admin/plugins directories aren't 777 */ // Extract the archive to data so we can get the $pi_name name from admin/install.php if ($_FILES['plugin']['type'] == 'application/zip') { // Zip $archive->extract(array('add_path' => $_CONF['path'] . 'data/', 'by_name' => $dirname . '/admin/install.php')); } else { // Tarball $archive->extractList(array($dirname . '/admin/install.php'), $_CONF['path'] . 'data/'); } $plugin_inst = $_CONF['path'] . 'data/' . $dirname . '/admin/install.php'; $fdata = ''; $fhandle = @fopen($plugin_inst, 'r'); if ($fhandle) { $fdata = fread($fhandle, filesize($plugin_inst)); fclose($fhandle); } // Remove the plugin from data/ require_once 'System.php'; @System::rm('-rf ' . $_CONF['path'] . 'data/' . $dirname); /** * One time I wanted to install a muffler on my car and * needed to match up the outside diameter of the car's * exhaust pipe to the inside diameter of the muffler.
/** * ends the upgrade process * * @return void */ public function ajaxProcessUpgradeComplete() { if (version_compare($this->install_version, '1.5.4.0', '>=')) { // Upgrade languages if (!defined('_PS_TOOL_DIR_')) { define('_PS_TOOL_DIR_', _PS_ROOT_DIR_ . '/tools/'); } if (!defined('_PS_TRANSLATIONS_DIR_')) { define('_PS_TRANSLATIONS_DIR_', _PS_ROOT_DIR_ . '/translations/'); } if (!defined('_PS_MODULES_DIR_')) { define('_PS_MODULES_DIR_', _PS_ROOT_DIR_ . '/modules/'); } if (!defined('_PS_MAILS_DIR_')) { define('_PS_MAILS_DIR_', _PS_ROOT_DIR_ . '/mails/'); } $langs = Db::getInstance()->executeS('SELECT * FROM ' . _DB_PREFIX_ . 'lang WHERE active=1'); require_once _PS_TOOL_DIR_ . 'tar/Archive_Tar.php'; foreach ($langs as $lang) { $lang_pack = Tools14::jsonDecode(Tools::file_get_contents('http' . (extension_loaded('openssl') ? 's' : '') . '://www.prestashop.com/download/lang_packs/get_language_pack.php?version=' . $this->install_version . '&iso_lang=' . $lang['iso_code'])); if (!$lang_pack) { continue; } elseif ($content = Tools14::file_get_contents('http' . (extension_loaded('openssl') ? 's' : '') . '://translations.prestashop.com/download/lang_packs/gzip/' . $lang_pack->version . '/' . $lang['iso_code'] . '.gzip')) { $file = _PS_TRANSLATIONS_DIR_ . $lang['iso_code'] . '.gzip'; if ((bool) @file_put_contents($file, $content)) { $gz = new Archive_Tar($file, true); $files_list = $gz->listContent(); if (!$this->keepMails) { foreach ($files_list as $i => $file) { if (preg_match('/^mails\\/' . $lang['iso_code'] . '\\/.*/', $file['filename'])) { unset($files_list[$i]); } } foreach ($files_list as $file) { if (isset($file['filename']) && is_string($file['filename'])) { $files_listing[] = $file['filename']; } } if (is_array($files_listing) && !$gz->extractList($files_listing, _PS_TRANSLATIONS_DIR_ . '../', '')) { continue; } } elseif (!$gz->extract(_PS_TRANSLATIONS_DIR_ . '../', false)) { continue; } } } } // Remove class_index Autoload cache @unlink(_PS_ROOT_DIR_ . '/cache/class_index.php'); } if (!$this->warning_exists) { $this->next_desc = $this->l('Upgrade process done. Congratulations ! You can now reactive your shop.'); } else { $this->next_desc = $this->l('Upgrade process done, but some warnings has been found. Please restore your shop.'); } $this->next = ''; $conf_clear = Db::getInstance()->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'configuration` WHERE `name` = \'PS_UPGRADE_CLEAR_CACHE\' '); if (!$conf_clear) { //set this value to 1 after upgrade process to Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'configuration` (`name`, `value`, `date_add`, `date_upd`) VALUES (\'PS_UPGRADE_CLEAR_CACHE\', 1, NOW(), NOW())'); } else { Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'configuration` SET value=1 WHERE name=\'PS_UPGRADE_CLEAR_CACHE\' '); } }
/** * This function now replaces doUpgrade.php or upgrade.php * * @return void */ public function doUpgrade() { // Initialize // setting the memory limit to 128M only if current is lower $memory_limit = ini_get('memory_limit'); if (substr($memory_limit, -1) != 'G' && ((substr($memory_limit, -1) == 'M' and substr($memory_limit, 0, -1) < 128) || is_numeric($memory_limit) and intval($memory_limit) < 131072)) { @ini_set('memory_limit', '128M'); } /* Redefine REQUEST_URI if empty (on some webservers...) */ if (!isset($_SERVER['REQUEST_URI']) || empty($_SERVER['REQUEST_URI'])) { if (!isset($_SERVER['SCRIPT_NAME']) && isset($_SERVER['SCRIPT_FILENAME'])) { $_SERVER['SCRIPT_NAME'] = $_SERVER['SCRIPT_FILENAME']; } if (isset($_SERVER['SCRIPT_NAME'])) { if (basename($_SERVER['SCRIPT_NAME']) == 'index.php' && empty($_SERVER['QUERY_STRING'])) { $_SERVER['REQUEST_URI'] = dirname($_SERVER['SCRIPT_NAME']) . '/'; } else { $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME']; if (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])) { $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING']; } } } } $_SERVER['REQUEST_URI'] = str_replace('//', '/', $_SERVER['REQUEST_URI']); define('INSTALL_VERSION', $this->install_version); // 1.4 define('INSTALL_PATH', realpath($this->latestRootDir . DIRECTORY_SEPARATOR . 'install')); // 1.5 ... define('_PS_INSTALL_PATH_', INSTALL_PATH . DIRECTORY_SEPARATOR); // 1.6 if (!defined('_PS_CORE_DIR_')) { define('_PS_CORE_DIR_', _PS_ROOT_DIR_); } define('PS_INSTALLATION_IN_PROGRESS', true); define('SETTINGS_FILE', $this->prodRootDir . '/config/settings.inc.php'); define('DEFINES_FILE', $this->prodRootDir . '/config/defines.inc.php'); define('INSTALLER__PS_BASE_URI', substr($_SERVER['REQUEST_URI'], 0, -1 * (strlen($_SERVER['REQUEST_URI']) - strrpos($_SERVER['REQUEST_URI'], '/')) - strlen(substr(dirname($_SERVER['REQUEST_URI']), strrpos(dirname($_SERVER['REQUEST_URI']), '/') + 1)))); // define('INSTALLER__PS_BASE_URI_ABSOLUTE', 'http://'.ToolsInstall::getHttpHost(false, true).INSTALLER__PS_BASE_URI); // XML Header // header('Content-Type: text/xml'); $filePrefix = 'PREFIX_'; $engineType = 'ENGINE_TYPE'; $mysqlEngine = defined('_MYSQL_ENGINE_') ? _MYSQL_ENGINE_ : 'MyISAM'; if (function_exists('date_default_timezone_set')) { date_default_timezone_set('Europe/Paris'); } // if _PS_ROOT_DIR_ is defined, use it instead of "guessing" the module dir. if (defined('_PS_ROOT_DIR_') and !defined('_PS_MODULE_DIR_')) { define('_PS_MODULE_DIR_', _PS_ROOT_DIR_ . '/modules/'); } else { if (!defined('_PS_MODULE_DIR_')) { define('_PS_MODULE_DIR_', INSTALL_PATH . '/../modules/'); } } $upgrade_dir_php = 'upgrade/php'; if (!file_exists(INSTALL_PATH . DIRECTORY_SEPARATOR . $upgrade_dir_php)) { $upgrade_dir_php = 'php'; if (!file_exists(INSTALL_PATH . DIRECTORY_SEPARATOR . $upgrade_dir_php)) { $this->next = 'error'; $this->next_desc = $this->l('/install/upgrade/php directory is missing in archive or directory'); $this->nextQuickInfo[] = '/install/upgrade/php directory is missing in archive or directory'; $this->nextErrors[] = '/install/upgrade/php directory is missing in archive or directory.'; return false; } } define('_PS_INSTALLER_PHP_UPGRADE_DIR_', INSTALL_PATH . DIRECTORY_SEPARATOR . $upgrade_dir_php . DIRECTORY_SEPARATOR); //old version detection global $oldversion, $logger; $oldversion = false; if (file_exists(SETTINGS_FILE)) { include_once SETTINGS_FILE; // include_once(DEFINES_FILE); $oldversion = _PS_VERSION_; } else { $this->next = 'error'; $this->nextQuickInfo[] = $this->l('The config/settings.inc.php file was not found.'); $this->nextErrors[] = $this->l('The config/settings.inc.php file was not found.'); return false; } if (!defined('__PS_BASE_URI__')) { define('__PS_BASE_URI__', realpath(dirname($_SERVER['SCRIPT_NAME'])) . '/../../'); } if (!defined('_THEMES_DIR_')) { define('_THEMES_DIR_', __PS_BASE_URI__ . 'themes/'); } $oldversion = _PS_VERSION_; $versionCompare = version_compare(INSTALL_VERSION, $oldversion); if ($versionCompare == '-1') { $this->next = 'error'; $this->nextQuickInfo[] = sprintf($this->l('Current version: %1$s. Version to install: %2$s.'), $oldversion, INSTALL_VERSION); $this->nextErrors[] = sprintf($this->l('Current version: %1$s. Version to install: %2$s'), $oldversion, INSTALL_VERSION); $this->nextQuickInfo[] = $this->l('[ERROR] Version to install is too old.'); $this->nextErrors[] = $this->l('[ERROR] Version to install is too old.'); return false; } elseif ($versionCompare == 0) { $this->next = 'error'; $this->nextQuickInfo[] = $this->l(sprintf('You already have the %s version.', INSTALL_VERSION)); $this->nextErrors[] = $this->l(sprintf('You already have the %s version.', INSTALL_VERSION)); return false; } elseif ($versionCompare === false) { $this->next = 'error'; $this->nextQuickInfo[] = $this->l('There is no older version. Did you delete or rename the config/settings.inc.php file?'); $this->nextErrors[] = $this->l('There is no older version. Did you delete or rename the config/settings.inc.php file?'); return false; } //check DB access $this->db; error_reporting(E_ALL); $resultDB = Db::checkConnection(_DB_SERVER_, _DB_USER_, _DB_PASSWD_, _DB_NAME_); if ($resultDB !== 0) { // $logger->logError('Invalid database configuration.'); $this->next = 'error'; $this->nextQuickInfo[] = $this->l('Invalid database configuration'); $this->nextErrors[] = $this->l('Invalid database configuration'); return false; } //custom sql file creation $upgradeFiles = array(); $upgrade_dir_sql = INSTALL_PATH . '/upgrade/sql'; // if 1.4; if (!file_exists($upgrade_dir_sql)) { $upgrade_dir_sql = INSTALL_PATH . '/sql/upgrade'; } if (!file_exists($upgrade_dir_sql)) { $this->next = 'error'; $this->next_desc = $this->l('Unable to find upgrade directory in the installation path.'); return false; } if ($handle = opendir($upgrade_dir_sql)) { while (false !== ($file = readdir($handle))) { if ($file != '.' and $file != '..') { $upgradeFiles[] = str_replace(".sql", "", $file); } } closedir($handle); } if (empty($upgradeFiles)) { $this->next = 'error'; $this->nextQuickInfo[] = sprintf($this->l('Cannot find the SQL upgrade files. Please check that the %s folder is not empty.'), $upgrade_dir_sql); $this->nextErrors[] = sprintf($this->l('Cannot find the SQL upgrade files. Please check that the %s folder is not empty.'), $upgrade_dir_sql); // fail 31 return false; } natcasesort($upgradeFiles); $neededUpgradeFiles = array(); $arrayVersion = explode('.', $oldversion); $versionNumbers = count($arrayVersion); if ($versionNumbers != 4) { $arrayVersion = array_pad($arrayVersion, 4, '0'); } $oldversion = implode('.', $arrayVersion); foreach ($upgradeFiles as $version) { if (version_compare($version, $oldversion) == 1 && version_compare(INSTALL_VERSION, $version) != -1) { $neededUpgradeFiles[] = $version; } } if (strpos(INSTALL_VERSION, '.') === false) { $this->nextQuickInfo[] = sprintf($this->l('%s is not a valid version number.'), INSTALL_VERSION); $this->nextErrors[] = sprintf($this->l('%s is not a valid version number.'), INSTALL_VERSION); return false; } $sqlContentVersion = array(); if ($this->deactivateCustomModule) { require_once _PS_INSTALLER_PHP_UPGRADE_DIR_ . 'deactivate_custom_modules.php'; deactivate_custom_modules(); } if (version_compare(INSTALL_VERSION, '1.5.6.1', '=')) { $filename = _PS_INSTALLER_PHP_UPGRADE_DIR_ . 'migrate_orders.php'; $content = file_get_contents($filename); $str_old[] = '$values_order_detail = array();'; $str_old[] = '$values_order = array();'; $str_old[] = '$col_order_detail = array();'; $content = str_replace($str_old, '', $content); file_put_contents($filename, $content); } foreach ($neededUpgradeFiles as $version) { $file = $upgrade_dir_sql . DIRECTORY_SEPARATOR . $version . '.sql'; if (!file_exists($file)) { $this->next = 'error'; $this->nextQuickInfo[] = sprintf($this->l('Error while loading SQL upgrade file "%s.sql".'), $version); $this->nextErrors[] = sprintf($this->l('Error while loading SQL upgrade file "%s.sql".'), $version); return false; $logger->logError('Error while loading SQL upgrade file.'); } if (!($sqlContent = file_get_contents($file) . "\n")) { $this->next = 'error'; $this->nextQuickInfo[] = $this->l(sprintf('Error while loading SQL upgrade file %s.', $version)); $this->nextErrors[] = $this->l(sprintf('Error while loading sql SQL file %s.', $version)); return false; $logger->logError(sprintf('Error while loading sql upgrade file %s.', $version)); } $sqlContent = str_replace(array($filePrefix, $engineType), array(_DB_PREFIX_, $mysqlEngine), $sqlContent); $sqlContent = preg_split("/;\\s*[\r\n]+/", $sqlContent); $sqlContentVersion[$version] = $sqlContent; } //sql file execution global $requests, $warningExist; $requests = ''; $warningExist = false; // Configuration::loadConfiguration(); $request = ''; foreach ($sqlContentVersion as $upgrade_file => $sqlContent) { foreach ($sqlContent as $query) { $query = trim($query); if (!empty($query)) { /* If php code have to be executed */ if (strpos($query, '/* PHP:') !== false) { /* Parsing php code */ $pos = strpos($query, '/* PHP:') + strlen('/* PHP:'); $phpString = substr($query, $pos, strlen($query) - $pos - strlen(' */;')); $php = explode('::', $phpString); preg_match('/\\((.*)\\)/', $phpString, $pattern); $paramsString = trim($pattern[0], '()'); preg_match_all('/([^,]+),? ?/', $paramsString, $parameters); if (isset($parameters[1])) { $parameters = $parameters[1]; } else { $parameters = array(); } if (is_array($parameters)) { foreach ($parameters as &$parameter) { $parameter = str_replace('\'', '', $parameter); } } // reset phpRes to a null value $phpRes = null; /* Call a simple function */ if (strpos($phpString, '::') === false) { $func_name = str_replace($pattern[0], '', $php[0]); if (version_compare(INSTALL_VERSION, '1.5.5.0', '=') && $func_name == 'fix_download_product_feature_active') { continue; } if (!file_exists(_PS_INSTALLER_PHP_UPGRADE_DIR_ . strtolower($func_name) . '.php')) { $this->nextQuickInfo[] = '<div class="upgradeDbError">[ERROR] ' . $upgrade_file . ' PHP - missing file ' . $query . '</div>'; $this->nextErrors[] = '[ERROR] ' . $upgrade_file . ' PHP - missing file ' . $query; $warningExist = true; } else { require_once _PS_INSTALLER_PHP_UPGRADE_DIR_ . strtolower($func_name) . '.php'; $phpRes = call_user_func_array($func_name, $parameters); } } else { $func_name = array($php[0], str_replace($pattern[0], '', $php[1])); $this->nextQuickInfo[] = '<div class="upgradeDbError">[ERROR] ' . $upgrade_file . ' PHP - Object Method call is forbidden ( ' . $php[0] . '::' . str_replace($pattern[0], '', $php[1]) . ')</div>'; $this->nextErrors[] = '[ERROR] ' . $upgrade_file . ' PHP - Object Method call is forbidden (' . $php[0] . '::' . str_replace($pattern[0], '', $php[1]) . ')'; $warningExist = true; } if (isset($phpRes) && (is_array($phpRes) && !empty($phpRes['error'])) || $phpRes === false) { // $this->next = 'error'; $this->nextQuickInfo[] = ' <div class="upgradeDbError"> [ERROR] PHP ' . $upgrade_file . ' ' . $query . "\n" . ' ' . (empty($phpRes['error']) ? '' : $phpRes['error'] . "\n") . ' ' . (empty($phpRes['msg']) ? '' : ' - ' . $phpRes['msg'] . "\n") . ' </div>'; $this->nextErrors[] = ' [ERROR] PHP ' . $upgrade_file . ' ' . $query . "\n" . ' ' . (empty($phpRes['error']) ? '' : $phpRes['error'] . "\n") . ' ' . (empty($phpRes['msg']) ? '' : ' - ' . $phpRes['msg'] . "\n"); $warningExist = true; } else { $this->nextQuickInfo[] = '<div class="upgradeDbOk">[OK] PHP ' . $upgrade_file . ' : ' . $query . '</div>'; } if (isset($phpRes)) { unset($phpRes); } } else { if (strstr($query, 'CREATE TABLE') !== false) { $pattern = '/CREATE TABLE.*[`]*' . _DB_PREFIX_ . '([^`]*)[`]*\\s\\(/'; preg_match($pattern, $query, $matches); if (isset($matches[1]) && $matches[1]) { $drop = 'DROP TABLE IF EXISTS `' . _DB_PREFIX_ . $matches[1] . '`;'; $result = $this->db->execute($drop, false); if ($result) { $this->nextQuickInfo[] = '<div class="upgradeDbOk">' . sprintf($this->l('[DROP] SQL %s table has been dropped.'), '`' . _DB_PREFIX_ . $matches[1] . '`') . '</div>'; } } } $result = $this->db->execute($query, false); if (!$result) { $error = $this->db->getMsgError(); $error_number = $this->db->getNumberError(); $this->nextQuickInfo[] = ' <div class="upgradeDbError"> [WARNING] SQL ' . $upgrade_file . ' ' . $error_number . ' in ' . $query . ': ' . $error . '</div>'; $duplicates = array('1050', '1054', '1060', '1061', '1062', '1091'); if (!in_array($error_number, $duplicates)) { $this->nextErrors[] = 'SQL ' . $upgrade_file . ' ' . $error_number . ' in ' . $query . ': ' . $error; $warningExist = true; } } else { $this->nextQuickInfo[] = '<div class="upgradeDbOk">[OK] SQL ' . $upgrade_file . ' ' . $query . '</div>'; } } if (isset($query)) { unset($query); } } } } if ($this->next == 'error') { $this->next_desc = $this->l('An error happened during the database upgrade.'); return false; } $this->nextQuickInfo[] = $this->l('Database upgrade OK'); // no error ! # At this point, database upgrade is over. # Now we need to add all previous missing settings items, and reset cache and compile directories $this->writeNewSettings(); // Settings updated, compile and cache directories must be emptied $arrayToClean[] = $this->prodRootDir . '/tools/smarty/cache/'; $arrayToClean[] = $this->prodRootDir . '/tools/smarty/compile/'; $arrayToClean[] = $this->prodRootDir . '/tools/smarty_v2/cache/'; $arrayToClean[] = $this->prodRootDir . '/tools/smarty_v2/compile/'; if (version_compare(INSTALL_VERSION, '1.5.0.0', '>')) { $arrayToClean[] = $this->prodRootDir . '/cache/smarty/cache/'; $arrayToClean[] = $this->prodRootDir . '/cache/smarty/compile/'; } foreach ($arrayToClean as $dir) { if (!file_exists($dir)) { $this->nextQuickInfo[] = sprintf($this->l('[SKIP] directory "%s" does not exist and cannot be emptied.'), str_replace($this->prodRootDir, '', $dir)); continue; } else { foreach (scandir($dir) as $file) { if ($file[0] != '.' && $file != 'index.php' && $file != '.htaccess') { if (is_file($dir . $file)) { unlink($dir . $file); } elseif (is_dir($dir . $file . DIRECTORY_SEPARATOR)) { self::deleteDirectory($dir . $file . DIRECTORY_SEPARATOR); } $this->nextQuickInfo[] = sprintf($this->l('[CLEANING CACHE] File %s removed'), $file); } } } } if (version_compare(INSTALL_VERSION, '1.5.0.0', '>')) { Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'configuration` SET `name` = \'PS_LEGACY_IMAGES\' WHERE name LIKE \'0\' AND `value` = 1'); Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'configuration` SET `value` = 0 WHERE `name` LIKE \'PS_LEGACY_IMAGES\''); if (Db::getInstance()->getValue('SELECT COUNT(id_product_download) FROM `' . _DB_PREFIX_ . 'product_download` WHERE `active` = 1') > 0) { Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'configuration` SET `value` = 1 WHERE `name` LIKE \'PS_VIRTUAL_PROD_FEATURE_ACTIVE\''); } if (defined('_THEME_NAME_') && $this->updateDefaultTheme && preg_match('#(default|prestashop|default-boostrap)$#', _THEME_NAME_)) { $separator = addslashes(DIRECTORY_SEPARATOR); $file = _PS_ROOT_DIR_ . $separator . 'themes' . $separator . _THEME_NAME_ . $separator . 'cache' . $separator; if (file_exists($file)) { foreach (scandir($file) as $cache) { if ($cache[0] != '.' && $cache != 'index.php' && $cache != '.htaccess' && file_exists($file . $cache) && !is_dir($file . $cache)) { if (file_exists($dir . $cache)) { unlink($file . $cache); } } } } } if (version_compare(_PS_VERSION_, '1.5.0.0', '<=')) { $dir = _PS_ROOT_DIR_ . '/controllers/'; if (file_exists($dir)) { foreach (scandir($dir) as $file) { if (!is_dir($file) && $file[0] != '.' && $file != 'index.php' && $file != '.htaccess') { if (file_exists($dir . basename(str_replace('.php', '', $file) . '.php'))) { unlink($dir . basename($file)); } } } } $dir = _PS_ROOT_DIR_ . '/classes/'; foreach (self::$classes14 as $class) { if (file_exists($dir . basename($class) . '.php')) { unlink($dir . basename($class) . '.php'); } } $dir = _PS_ADMIN_DIR_ . '/tabs/'; if (file_exists($dir)) { foreach (scandir($dir) as $file) { if (!is_dir($file) && $file[0] != '.' && $file != 'index.php' && $file != '.htaccess') { if (file_exists($dir . basename(str_replace('.php', '', $file) . '.php'))) { unlink($dir . basename($file)); } } } } } if (version_compare($this->install_version, '1.5.4.0', '>=')) { // Upgrade languages if (!defined('_PS_TOOL_DIR_')) { define('_PS_TOOL_DIR_', _PS_ROOT_DIR_ . '/tools/'); } if (!defined('_PS_TRANSLATIONS_DIR_')) { define('_PS_TRANSLATIONS_DIR_', _PS_ROOT_DIR_ . '/translations/'); } if (!defined('_PS_MODULES_DIR_')) { define('_PS_MODULES_DIR_', _PS_ROOT_DIR_ . '/modules/'); } if (!defined('_PS_MAILS_DIR_')) { define('_PS_MAILS_DIR_', _PS_ROOT_DIR_ . '/mails/'); } $langs = Db::getInstance()->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'lang` WHERE `active` = 1'); require_once _PS_TOOL_DIR_ . 'tar/Archive_Tar.php'; if (is_array($langs)) { foreach ($langs as $lang) { $lang_pack = Tools14::jsonDecode(Tools14::file_get_contents('http' . (extension_loaded('openssl') ? 's' : '') . '://www.prestashop.com/download/lang_packs/get_language_pack.php?version=' . $this->install_version . '&iso_lang=' . $lang['iso_code'])); if (!$lang_pack) { continue; } elseif ($content = Tools14::file_get_contents('http' . (extension_loaded('openssl') ? 's' : '') . '://translations.prestashop.com/download/lang_packs/gzip/' . $lang_pack->version . '/' . $lang['iso_code'] . '.gzip')) { $file = _PS_TRANSLATIONS_DIR_ . $lang['iso_code'] . '.gzip'; if ((bool) file_put_contents($file, $content)) { $gz = new Archive_Tar($file, true); $files_list = $gz->listContent(); if (!$this->keepMails) { $files_listing = array(); foreach ($files_list as $i => $file) { if (preg_match('/^mails\\/' . $lang['iso_code'] . '\\/.*/', $file['filename'])) { unset($files_list[$i]); } } foreach ($files_list as $file) { if (isset($file['filename']) && is_string($file['filename'])) { $files_listing[] = $file['filename']; } } if (is_array($files_listing)) { $gz->extractList($files_listing, _PS_TRANSLATIONS_DIR_ . '../', ''); } } else { $gz->extract(_PS_TRANSLATIONS_DIR_ . '../', false); } } } } } } if (version_compare($this->install_version, '1.6.0.0', '>')) { if (version_compare($this->install_version, '1.6.1.0', '>=')) { require_once _PS_ROOT_DIR_ . '/Core/Foundation/Database/Core_Foundation_Database_EntityInterface.php'; } if (file_exists(_PS_ROOT_DIR_ . '/classes/Tools.php')) { require_once _PS_ROOT_DIR_ . '/classes/Tools.php'; } if (!class_exists('Tools2', false) and class_exists('ToolsCore')) { eval('class Tools2 extends ToolsCore{}'); } if (class_exists('Tools2') && method_exists('Tools2', 'generateHtaccess')) { $url_rewrite = (bool) Db::getInstance()->getvalue('SELECT `value` FROM `' . _DB_PREFIX_ . 'configuration` WHERE name=\'PS_REWRITING_SETTINGS\''); if (!defined('_MEDIA_SERVER_1_')) { define('_MEDIA_SERVER_1_', ''); } if (!defined('_MEDIA_SERVER_2_')) { define('_MEDIA_SERVER_2_', ''); } if (!defined('_MEDIA_SERVER_3_')) { define('_MEDIA_SERVER_3_', ''); } if (!defined('_PS_USE_SQL_SLAVE_')) { define('_PS_USE_SQL_SLAVE_', false); } if (file_exists(_PS_ROOT_DIR_ . '/classes/ObjectModel.php')) { require_once _PS_ROOT_DIR_ . '/classes/ObjectModel.php'; } if (!class_exists('ObjectModel', false) and class_exists('ObjectModelCore')) { eval('abstract class ObjectModel extends ObjectModelCore{}'); } if (file_exists(_PS_ROOT_DIR_ . '/classes/Configuration.php')) { require_once _PS_ROOT_DIR_ . '/classes/Configuration.php'; } if (!class_exists('Configuration', false) and class_exists('ConfigurationCore')) { eval('class Configuration extends ConfigurationCore{}'); } if (file_exists(_PS_ROOT_DIR_ . '/classes/cache/Cache.php')) { require_once _PS_ROOT_DIR_ . '/classes/cache/Cache.php'; } if (!class_exists('Cache', false) and class_exists('CacheCore')) { eval('abstract class Cache extends CacheCore{}'); } if (file_exists(_PS_ROOT_DIR_ . '/classes/PrestaShopCollection.php')) { require_once _PS_ROOT_DIR_ . '/classes/PrestaShopCollection.php'; } if (!class_exists('PrestaShopCollection', false) and class_exists('PrestaShopCollectionCore')) { eval('class PrestaShopCollection extends PrestaShopCollectionCore{}'); } if (file_exists(_PS_ROOT_DIR_ . '/classes/shop/ShopUrl.php')) { require_once _PS_ROOT_DIR_ . '/classes/shop/ShopUrl.php'; } if (!class_exists('ShopUrl', false) and class_exists('ShopUrlCore')) { eval('class ShopUrl extends ShopUrlCore{}'); } if (file_exists(_PS_ROOT_DIR_ . '/classes/shop/Shop.php')) { require_once _PS_ROOT_DIR_ . '/classes/shop/Shop.php'; } if (!class_exists('Shop', false) and class_exists('ShopCore')) { eval('class Shop extends ShopCore{}'); } if (file_exists(_PS_ROOT_DIR_ . '/classes/Translate.php')) { require_once _PS_ROOT_DIR_ . '/classes/Translate.php'; } if (!class_exists('Translate', false) and class_exists('TranslateCore')) { eval('class Translate extends TranslateCore{}'); } if (file_exists(_PS_ROOT_DIR_ . '/classes/module/Module.php')) { require_once _PS_ROOT_DIR_ . '/classes/module/Module.php'; } if (!class_exists('Module', false) and class_exists('ModuleCore')) { eval('class Module extends ModuleCore{}'); } if (file_exists(_PS_ROOT_DIR_ . '/classes/Validate.php')) { require_once _PS_ROOT_DIR_ . '/classes/Validate.php'; } if (!class_exists('Validate', false) and class_exists('ValidateCore')) { eval('class Validate extends ValidateCore{}'); } if (file_exists(_PS_ROOT_DIR_ . '/classes/Language.php')) { require_once _PS_ROOT_DIR_ . '/classes/Language.php'; } if (!class_exists('Language', false) and class_exists('LanguageCore')) { eval('class Language extends LanguageCore{}'); } if (file_exists(_PS_ROOT_DIR_ . '/classes/Tab.php')) { require_once _PS_ROOT_DIR_ . '/classes/Tab.php'; } if (!class_exists('Tab', false) and class_exists('TabCore')) { eval('class Tab extends TabCore{}'); } if (file_exists(_PS_ROOT_DIR_ . '/classes/Dispatcher.php')) { require_once _PS_ROOT_DIR_ . '/classes/Dispatcher.php'; } if (!class_exists('Dispatcher', false) and class_exists('DispatcherCore')) { eval('class Dispatcher extends DispatcherCore{}'); } if (file_exists(_PS_ROOT_DIR_ . '/classes/Hook.php')) { require_once _PS_ROOT_DIR_ . '/classes/Hook.php'; } if (!class_exists('Hook', false) and class_exists('HookCore')) { eval('class Hook extends HookCore{}'); } if (file_exists(_PS_ROOT_DIR_ . '/classes/Context.php')) { require_once _PS_ROOT_DIR_ . '/classes/Context.php'; } if (!class_exists('Context', false) and class_exists('ContextCore')) { eval('class Context extends ContextCore{}'); } if (file_exists(_PS_ROOT_DIR_ . '/classes/Group.php')) { require_once _PS_ROOT_DIR_ . '/classes/Group.php'; } if (!class_exists('Group', false) and class_exists('GroupCore')) { eval('class Group extends GroupCore{}'); } Tools2::generateHtaccess(null, $url_rewrite); } } if (version_compare($this->install_version, '1.6.0.2', '>')) { $path = $this->adminDir . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . 'default' . DIRECTORY_SEPARATOR . 'template' . DIRECTORY_SEPARATOR . 'controllers' . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . 'header.tpl'; if (file_exists($path)) { unlink($path); } } } if (file_exists(_PS_ROOT_DIR_ . '/cache/class_index.php')) { unlink(_PS_ROOT_DIR_ . '/cache/class_index.php'); } // Clear XML files if (file_exists(_PS_ROOT_DIR_ . '/config/xml/blog-fr.xml')) { unlink(_PS_ROOT_DIR_ . '/config/xml/blog-fr.xml'); } if (file_exists(_PS_ROOT_DIR_ . '/config/xml/default_country_modules_list.xml')) { unlink(_PS_ROOT_DIR_ . '/config/xml/default_country_modules_list.xml'); } if (file_exists(_PS_ROOT_DIR_ . '/config/xml/modules_list.xml')) { unlink(_PS_ROOT_DIR_ . '/config/xml/modules_list.xml'); } if (file_exists(_PS_ROOT_DIR_ . '/config/xml/modules_native_addons.xml')) { unlink(_PS_ROOT_DIR_ . '/config/xml/modules_native_addons.xml'); } if (file_exists(_PS_ROOT_DIR_ . '/config/xml/must_have_modules_list.xml')) { unlink(_PS_ROOT_DIR_ . '/config/xml/must_have_modules_list.xml'); } if (file_exists(_PS_ROOT_DIR_ . '/config/xml/tab_modules_list.xml')) { unlink(_PS_ROOT_DIR_ . '/config/xml/tab_modules_list.xml'); } if (file_exists(_PS_ROOT_DIR_ . '/config/xml/trusted_modules_list.xml')) { unlink(_PS_ROOT_DIR_ . '/config/xml/trusted_modules_list.xml'); } if (file_exists(_PS_ROOT_DIR_ . '/config/xml/untrusted_modules_list.xml')) { unlink(_PS_ROOT_DIR_ . '/config/xml/untrusted_modules_list.xml'); } if ($this->deactivateCustomModule) { $exist = Db::getInstance()->getValue('SELECT `id_configuration` FROM `' . _DB_PREFIX_ . 'configuration` WHERE `name` LIKE \'PS_DISABLE_OVERRIDES\''); if ($exist) { Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'configuration` SET value = 1 WHERE `name` LIKE \'PS_DISABLE_OVERRIDES\''); } else { Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'configuration` (name, value, date_add, date_upd) VALUES ("PS_DISABLE_OVERRIDES", 1, NOW(), NOW())'); } if (file_exists(_PS_ROOT_DIR_ . '/classes/PrestaShopAutoload.php')) { require_once _PS_ROOT_DIR_ . '/classes/PrestaShopAutoload.php'; } if (version_compare($this->install_version, '1.6.0.0', '>') && class_exists('PrestaShopAutoload') && method_exists('PrestaShopAutoload', 'generateIndex')) { PrestaShopAutoload::getInstance()->_include_override_path = false; PrestaShopAutoload::getInstance()->generateIndex(); } } if ($this->changeToDefaultTheme) { if (version_compare(INSTALL_VERSION, '1.6.0.0', '>')) { Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'shop` SET id_theme = (SELECT id_theme FROM `' . _DB_PREFIX_ . 'theme` WHERE name LIKE \'default-bootstrap\')'); Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'theme` WHERE name LIKE \'default\' OR name LIKE \'prestashop\''); } elseif (version_compare(INSTALL_VERSION, '1.5.0.0', '>')) { Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'shop` SET id_theme = (SELECT id_theme FROM `' . _DB_PREFIX_ . 'theme` WHERE name LIKE \'default\')'); Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'theme` WHERE name LIKE \'prestashop\''); } } // delete cache filesystem if activated if (defined('_PS_CACHE_ENABLED_') && _PS_CACHE_ENABLED_) { $depth = (int) $this->db->getValue('SELECT value FROM ' . _DB_PREFIX_ . 'configuration WHERE name = "PS_CACHEFS_DIRECTORY_DEPTH"'); if ($depth) { if (!defined('_PS_CACHEFS_DIRECTORY_')) { define('_PS_CACHEFS_DIRECTORY_', $this->prodRootDir . '/cache/cachefs/'); } self::deleteDirectory(_PS_CACHEFS_DIRECTORY_, false); if (class_exists('CacheFs', false)) { self::createCacheFsDirectories((int) $depth); } } } $this->db->execute('UPDATE `' . _DB_PREFIX_ . 'configuration` SET value="0" WHERE name = "PS_HIDE_OPTIMIZATION_TIS"', false); $this->db->execute('UPDATE `' . _DB_PREFIX_ . 'configuration` SET value="1" WHERE name = "PS_NEED_REBUILD_INDEX"', false); $this->db->execute('UPDATE `' . _DB_PREFIX_ . 'configuration` SET value="' . INSTALL_VERSION . '" WHERE name = "PS_VERSION_DB"', false); if ($warningExist) { $this->warning_exists = true; $this->nextQuickInfo[] = $this->l('Warning detected during upgrade.'); $this->nextErrors[] = $this->l('Warning detected during upgrade.'); $this->next_desc = $this->l('Warning detected during upgrade.'); } else { $this->next_desc = $this->l('Database upgrade completed'); } return true; }
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 execute() { ini_set('max_execution_time', 0); $errors = array(); $tp = SJB_System::getTemplateProcessor(); $action = SJB_Request::getVar('action', false); $dir_separator = DIRECTORY_SEPARATOR; $script_path = explode(SJB_System::getSystemSettings('SYSTEM_URL_BASE'), __FILE__); $script_path = array_shift($script_path); $identifier = SJB_Request::getVar('identifier', time()); $filename = SJB_Request::getVar('filename', false); $settings = array(); if ($filename) { SJB_Backup::sendArchiveFile($filename, $script_path . 'backup' . $dir_separator . $filename); } if (SJB_Request::getVar('action') == "save") { $expPeriod = SJB_Request::getVar('backup_expired_period'); if (!empty($expPeriod) && (!is_numeric($expPeriod) || $expPeriod < 0)) { $errors[] = 'EXP_PERIOD_NOT_VALID'; } $ftpValid = $this->isFTPDataValid(); if (SJB_Request::getVar('autobackup', false) && SJB_Request::getVar('ftp_backup', false) && !$ftpValid) { $errors[] = 'FTP_DETAILS_NOT_VALID'; } if (empty($errors)) { $backupSettings = $_REQUEST; foreach ($backupSettings as $setting => $value) { if (!SJB_Settings::saveSetting($setting, $value)) { $errors['SETTINGS_SAVED_WITH_PROBLEMS'] = "SETTINGS_SAVED_WITH_PROBLEMS"; } } if (empty($errors)) { $tp->assign('successSaveMessage', true); } } else { $settings = $_REQUEST; } } switch ($action) { case 'backup': if (SJB_System::getSystemSettings('isDemo')) { $i18N = SJB_I18N::getInstance(); $str = $i18N->gettext('Backend', 'Error: You don\'t have permissions for it. This is a Demo version of the software.'); SJB_Session::setValue('error', $str); break; } if (SJB_System::getIfTrialModeIsOn() && $_SERVER['REMOTE_ADDR'] != "91.205.51.231") { $i18N = SJB_I18N::getInstance(); $str = $i18N->gettext('Backend', 'Error: You don\'t have permissions for it. This is a Trial version of the software.'); SJB_Session::setValue('error', $str); break; } SessionStorage::destroy('backup_' . $identifier); SessionStorage::write('backup_' . $identifier, serialize(array('last_time' => time()))); SJB_Session::unsetValue('restore'); SJB_Session::unsetValue('error'); $backup_type = SJB_Request::getVar('backup_type'); $backupDir = $script_path . 'backup' . $dir_separator; try { $this->prepareBackupDir($backupDir); } catch (Exception $e) { SJB_Session::setValue('error', $e->getMessage()); exit; } switch ($backup_type) { case 'full': SessionStorage::write('backup_' . $identifier, serialize(array('last_time' => time()))); $backupDir = $script_path; $name = 'db.sql'; SJB_Backup::dump($name, $script_path, $identifier); $d = dir($script_path); $contentDir = array(); $folders = array('.', '..', 'backup', '.svn', '.settings', '.cache', 'restore', $name); while (false !== ($entry = $d->read())) { if (!in_array($entry, $folders)) { $contentDir[] = $entry; } } $listFilesAndFolders = !empty($contentDir) ? $contentDir : false; $backupName = 'full_backup_' . date('Y_m_d__H_i') . '.tar.gz'; $export_files_dir_name = '..' . $dir_separator; if (SJB_Backup::archive($name, $listFilesAndFolders, $backupDir, $export_files_dir_name, $backupName, true, $identifier, 'full')) { SessionStorage::write('backup_' . $identifier, serialize(array('name' => $backupName))); } exit; break; case 'database': SessionStorage::write('backup_' . $identifier, serialize(array('last_time' => time()))); $name = 'db.sql'; $backupName = 'mysqldump_' . date('Y_m_d__H_i') . '.tar.gz'; $export_files_dir_name = '../backup' . $dir_separator; SJB_Backup::dump($name, $script_path, $identifier); if (SJB_Backup::archive(false, $name, $script_path, $export_files_dir_name, $backupName, false, $identifier, 'database')) { SessionStorage::write('backup_' . $identifier, serialize(array('name' => $backupName))); } exit; break; case 'files': SessionStorage::write('backup_' . $identifier, serialize(array('last_time' => time()))); $backupDir = $script_path; $d = dir($script_path); $contentDir = array(); $folders = array('.', '..', 'backup', '.svn', '.settings', '.cache', 'restore'); while (false !== ($entry = $d->read())) { if (!in_array($entry, $folders)) { $contentDir[] = $entry; } } $listFilesAndFolders = !empty($contentDir) ? $contentDir : false; $backupName = 'backup_' . date('Y_m_d__H_i') . '.tar.gz'; $export_files_dir_name = '..' . $dir_separator; if (SJB_Backup::archive(false, $listFilesAndFolders, $backupDir, $export_files_dir_name, $backupName, true, $identifier, 'files')) { SessionStorage::write('backup_' . $identifier, serialize(array('name' => $backupName))); } exit; break; } break; case 'restore': if (SJB_System::getSystemSettings('isDemo')) { SJB_Session::setValue('error', 'Error: You don\'t have permissions for it. This is a Demo version of the software.'); exit; } if (SJB_System::getIfTrialModeIsOn()) { SJB_Session::setValue('error', 'Error: You don\'t have permissions for it. This is a Trial version of the software.'); exit; } SJB_Session::unsetValue('restore'); SJB_Session::unsetValue('error'); $error = false; $restoreDir = $script_path . 'restore' . $dir_separator; try { $fileName = $this->moveUploadedFile($restoreDir); $tar = new Archive_Tar($restoreDir . $fileName, 'gz'); $tar->_error_class = 'SJB_PEAR_Exception'; $tar->extractList('db.sql', $restoreDir); $tar->extract($script_path); if (is_file($restoreDir . 'db.sql')) { SJB_Backup::restore_base_tables($restoreDir . 'db.sql'); } SJB_Cache::getInstance()->clean(); } catch (Exception $ex) { $error = $ex->getMessage(); } SJB_Filesystem::delete($restoreDir); if (is_file($script_path . 'install.php')) { SJB_Filesystem::delete($script_path . 'install.php'); } if ($error) { SJB_Session::setValue('error', $error); } else { SJB_Session::setValue('restore', 1); } exit; break; case 'send_archive': $name = SJB_Request::getVar('name', false); $archive_file_path = SJB_Path::combine(SJB_BASE_DIR . 'backup' . $dir_separator, $name); if ($name) { SJB_Backup::sendArchiveFile($name, $archive_file_path); } break; case 'check': $sessionBackup = SessionStorage::read('backup_' . $identifier); $sessionBackup = $sessionBackup ? unserialize($sessionBackup) : array(); $sessionRestore = SJB_Session::getValue('restore'); $sessionError = SJB_Session::getValue('error'); if (!empty($sessionBackup['name'])) { $name = $sessionBackup['name']; SessionStorage::destroy('backup_' . $identifier); echo SJB_System::getSystemSettings('SITE_URL') . "/backup/?action=send_archive&name={$name}"; exit; } elseif (!empty($sessionRestore)) { SJB_Session::unsetValue('restore'); echo SJB_System::getSystemSettings('SITE_URL') . '/backup/#restore'; exit; } elseif (!empty($sessionError)) { echo 'Error'; if (SJB_System::getSystemSettings('isDemo')) { echo ': You don\'t have permissions for it. This is a Demo version of the software.'; } if (SJB_System::getIfTrialModeIsOn()) { echo ': You don\'t have permissions for it. This is a Trial version of the software.'; } exit; } elseif (!empty($sessionBackup['last_time'])) { $period = (time() - $sessionBackup['last_time']) / 60; if ($period < 5) { echo 1; } else { SJB_Session::setValue('error', 'The backup generation process was unexpectedly interrupted. Please try again.'); echo 'error'; } exit; } else { echo 1; } exit; break; case 'delete_backup': $name = SJB_Request::getVar('name', false); if ($name) { $backup = $script_path . 'backup' . $dir_separator . $name; if (is_file($backup)) { SJB_Filesystem::delete($backup); SJB_Autobackup::deleteFileFromFtp($name); } else { $errors['FILE_NOT_FOUND'] = 1; } } $tp->assign('errors', $errors); $tp->assign('delBackup', 1); case 'created_backups': $path = $script_path . 'backup' . $dir_separator; if (is_dir($path)) { $di = new DirectoryIterator($path); $backupsArr = array(); foreach ($di as $file) { $fileName = $file->getFilename(); if (!$file->isDir() && !$file->isLink() && $fileName != '.htaccess') { $cTime = $file->getCTime(); $backupsArr[$cTime]['name'] = $fileName; if (preg_match('/mysqldump/', $fileName)) { $backupsArr[$cTime]['type'] = 'Site database only'; } elseif (preg_match('/full_backup/', $fileName)) { $backupsArr[$cTime]['type'] = 'Full site backup'; } elseif (preg_match('/backup/', $fileName)) { $backupsArr[$cTime]['type'] = 'Site files only'; } else { $backupsArr[$cTime]['type'] = 'Unknown'; } $pattern = '/(\\w+)_(\\d+)_(\\d+)_(\\d+)__(\\d+)_(\\d+).tar.gz/i'; $replacement = '$2-$3-$4 $5:$6'; $backupsArr[$cTime]['date'] = preg_replace($pattern, $replacement, $fileName); } } krsort($backupsArr); $tp->assign('created_backups', $backupsArr); } $tp->display('created_backups.tpl'); exit; break; case 'error': $sessionError = SJB_Session::getValue('error'); if (!is_null($sessionError)) { echo '<p class="error">' . $sessionError . '</p>'; exit; } break; } if (empty($settings)) { $settings = SJB_Settings::getSettings(); } $tp->assign('errors', $errors); $tp->assign('settings', $settings); $tp->assign('identifier', $identifier); $tp->assign("uploadMaxFilesize", SJB_UploadFileManager::getIniUploadMaxFilesize()); $tp->display('backup.tpl'); }
/** * 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}"); }
/** * 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; }
/** * Extract the archive into a specific directory * * @param string $path The directory in which to extract the file * @param string|array $files The file(s) to extract from the archive. If empty, it will extract the entire archive content * * @return boolean If the operation was successful */ public function extract($path, $files = array()) { return empty($files) ? $this->tar->extract($path) : $this->tar->extractList($files, $path); }
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); } }
/** * 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; }
/** * 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; } if (!count($content) && !@is_file($file)) { $ret = PEAR::raiseError("could not open file \"{$file}\""); return $ret; } $sig = null; $xml = null; $origfile = $file; foreach ($content as $file) { $name = $file['filename']; if (is_null($xml) && ($name == 'package2.xml' || $name == 'package.xml' || preg_match('/package.xml$/', $name, $match))) { // allow a .tgz to distribute both versions $xml = $name; } if (is_null($sig) && $name == 'package.sig') { $sig = $name; } if (!is_null($sig) && !is_null($xml)) { break; } } $tmpdir = System::mktemp('-t "' . $this->_config->get('temp_dir') . '" -d pear'); if ($tmpdir === false) { $ret = PEAR::raiseError("there was a problem with getting the configured temp directory"); return $ret; } PEAR_PackageFile::addTempFile($tmpdir); $this->_extractErrors(); PEAR::staticPushErrorHandling(PEAR_ERROR_CALLBACK, array($this, '_extractErrors')); if (!$xml || !$tar->extractList(array_values(array_filter(array($sig, $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(); // Check sig, if it exists. if (!is_null($sig)) { require_once 'PEAR/Gnupg.php'; $gnupg = new PEAR_Gnupg($this->_config); $result = $gnupg->validateSig("{$tmpdir}/{$xml}", "{$tmpdir}/{$sig}"); if (PEAR::isError($result)) { return $result; } } $ret =& PEAR_PackageFile::fromPackageFile("{$tmpdir}/{$xml}", $state, $origfile); return $ret; }