Initial commit

This commit is contained in:
2019-11-20 07:44:43 +01:00
commit 5bf49c4a81
41188 changed files with 5459177 additions and 0 deletions

View File

@@ -0,0 +1,90 @@
<?php
/*
* 2007-2019 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2019 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\AutoUpgrade\UpgradeTools;
use PrestaShop\Module\AutoUpgrade\UpgradeContainer;
use PrestaShop\Module\AutoUpgrade\Log\LoggerInterface;
class CacheCleaner
{
/**
* @var UpgradeContainer
*/
private $container;
/**
* @var LoggerInterface
*/
private $logger;
public function __construct(UpgradeContainer $container, LoggerInterface $logger)
{
$this->container = $container;
$this->logger = $logger;
}
public function cleanFolders()
{
$dirsToClean = array(
$this->container->getProperty(UpgradeContainer::PS_ROOT_PATH) . '/app/cache/',
$this->container->getProperty(UpgradeContainer::PS_ROOT_PATH) . '/cache/smarty/cache/',
$this->container->getProperty(UpgradeContainer::PS_ROOT_PATH) . '/cache/smarty/compile/',
$this->container->getProperty(UpgradeContainer::PS_ROOT_PATH) . '/var/cache/',
);
$defaultThemeNames = array(
'default',
'prestashop',
'default-boostrap',
'classic',
);
if (defined('_THEME_NAME_') && $this->container->getUpgradeConfiguration()->shouldUpdateDefaultTheme() && in_array(_THEME_NAME_, $defaultThemeNames)) {
$dirsToClean[] = $this->container->getProperty(UpgradeContainer::PS_ROOT_PATH) . '/themes/' . _THEME_NAME_ . '/cache/';
}
foreach ($dirsToClean as $dir) {
if (!file_exists($dir)) {
$this->logger->debug($this->container->getTranslator()->trans('[SKIP] directory "%s" does not exist and cannot be emptied.', array(str_replace($this->container->getProperty(UpgradeContainer::PS_ROOT_PATH), '', $dir)), 'Modules.Autoupgrade.Admin'));
continue;
}
foreach (scandir($dir) as $file) {
if ($file[0] === '.' || $file === 'index.php') {
continue;
}
// ToDo: Use Filesystem instead ?
if (is_file($dir . $file)) {
unlink($dir . $file);
} elseif (is_dir($dir . $file . DIRECTORY_SEPARATOR)) {
FilesystemAdapter::deleteDirectory($dir . $file . DIRECTORY_SEPARATOR);
}
$this->logger->debug($this->container->getTranslator()->trans('[CLEANING CACHE] File %s removed', array($file), 'Modules.Autoupgrade.Admin'));
}
}
}
}

View File

@@ -0,0 +1,691 @@
<?php
/*
* 2007-2018 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\AutoUpgrade\UpgradeTools\CoreUpgrader;
use PrestaShop\Module\AutoUpgrade\UpgradeContainer;
use PrestaShop\Module\AutoUpgrade\UpgradeException;
use PrestaShop\Module\AutoUpgrade\UpgradeTools\ThemeAdapter;
use PrestaShop\Module\AutoUpgrade\Log\LoggerInterface;
/**
* Class used to modify the core of PrestaShop, on the files are copied on the filesystem.
* It will run subtasks such as database upgrade, language upgrade etc.
*/
abstract class CoreUpgrader
{
/**
* @var UpgradeContainer
*/
protected $container;
/**
* @var \Db
*/
protected $db;
/**
* @var LoggerInterface
*/
protected $logger;
/**
* Version PrestaShop is upgraded to.
*
* @var string
*/
protected $destinationUpgradeVersion;
/**
* Path to the temporary install folder, where upgrade files can be found
*
* @var string
*/
protected $pathToInstallFolder;
/**
* Path to the folder containing PHP upgrade files
*
* @var string
*/
protected $pathToPhpUpgradeScripts;
public function __construct(UpgradeContainer $container, LoggerInterface $logger)
{
$this->container = $container;
$this->logger = $logger;
}
public function doUpgrade()
{
$this->initConstants();
$oldversion = $this->getPreUpgradeVersion();
$this->checkVersionIsNewer($oldversion);
//check DB access
error_reporting(E_ALL);
$resultDB = \Db::checkConnection(_DB_SERVER_, _DB_USER_, _DB_PASSWD_, _DB_NAME_);
if ($resultDB !== 0) {
throw new UpgradeException($this->container->getTranslator()->trans('Invalid database configuration', array(), 'Modules.Autoupgrade.Admin'));
}
if ($this->container->getUpgradeConfiguration()->shouldDeactivateCustomModules()) {
$this->disableCustomModules();
}
$this->upgradeDb($oldversion);
// 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();
$this->runRecurrentQueries();
$this->logger->debug($this->container->getTranslator()->trans('Database upgrade OK', array(), 'Modules.Autoupgrade.Admin')); // no error!
$this->upgradeLanguages();
$this->generateHtaccess();
$this->cleanXmlFiles();
if ($this->container->getUpgradeConfiguration()->shouldDeactivateCustomModules()) {
$this->disableOverrides();
}
$this->updateTheme();
$this->runCoreCacheClean();
if ($this->container->getState()->getWarningExists()) {
$this->logger->warning($this->container->getTranslator()->trans('Warning detected during upgrade.', array(), 'Modules.Autoupgrade.Admin'));
} else {
$this->logger->info($this->container->getTranslator()->trans('Database upgrade completed', array(), 'Modules.Autoupgrade.Admin'));
}
}
protected function initConstants()
{
// 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' && substr($memory_limit, 0, -1) < 512)
|| is_numeric($memory_limit) && ((int) $memory_limit < 131072))
) {
@ini_set('memory_limit', '512M');
}
// 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']);
$this->destinationUpgradeVersion = $this->container->getState()->getInstallVersion();
$this->pathToInstallFolder = realpath($this->container->getProperty(UpgradeContainer::LATEST_PATH) . DIRECTORY_SEPARATOR . 'install');
// Kept for backward compatbility (unknown consequences on old versions of PrestaShop)
define('INSTALL_VERSION', $this->destinationUpgradeVersion);
// 1.4
define('INSTALL_PATH', $this->pathToInstallFolder);
// 1.5 ...
if (!defined('_PS_CORE_DIR_')) {
define('_PS_CORE_DIR_', _PS_ROOT_DIR_);
}
define('PS_INSTALLATION_IN_PROGRESS', true);
define('SETTINGS_FILE_PHP', $this->container->getProperty(UpgradeContainer::PS_ROOT_PATH) . '/app/config/parameters.php');
define('SETTINGS_FILE_YML', $this->container->getProperty(UpgradeContainer::PS_ROOT_PATH) . '/app/config/parameters.yml');
define('DEFINES_FILE', $this->container->getProperty(UpgradeContainer::PS_ROOT_PATH) . '/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);
define('_PS_INSTALL_PATH_', $this->pathToInstallFolder . '/');
define('_PS_INSTALL_DATA_PATH_', _PS_INSTALL_PATH_ . 'data/');
define('_PS_INSTALL_CONTROLLERS_PATH_', _PS_INSTALL_PATH_ . 'controllers/');
define('_PS_INSTALL_MODELS_PATH_', _PS_INSTALL_PATH_ . 'models/');
define('_PS_INSTALL_LANGS_PATH_', _PS_INSTALL_PATH_ . 'langs/');
define('_PS_INSTALL_FIXTURES_PATH_', _PS_INSTALL_PATH_ . 'fixtures/');
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_') && !defined('_PS_MODULE_DIR_')) {
define('_PS_MODULE_DIR_', _PS_ROOT_DIR_ . '/modules/');
} elseif (!defined('_PS_MODULE_DIR_')) {
define('_PS_MODULE_DIR_', $this->pathToInstallFolder . '/../modules/');
}
$upgrade_dir_php = 'upgrade/php';
if (!file_exists($this->pathToInstallFolder . DIRECTORY_SEPARATOR . $upgrade_dir_php)) {
$upgrade_dir_php = 'php';
if (!file_exists($this->pathToInstallFolder . DIRECTORY_SEPARATOR . $upgrade_dir_php)) {
throw new UpgradeException($this->container->getTranslator()->trans('/install/upgrade/php directory is missing in archive or directory', array(), 'Modules.Autoupgrade.Admin'));
}
}
$this->pathToPhpUpgradeScripts = $this->pathToInstallFolder . DIRECTORY_SEPARATOR . $upgrade_dir_php . DIRECTORY_SEPARATOR;
define('_PS_INSTALLER_PHP_UPGRADE_DIR_', $this->pathToPhpUpgradeScripts);
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/');
}
if (file_exists($this->pathToInstallFolder . DIRECTORY_SEPARATOR . 'autoload.php')) {
require_once $this->pathToInstallFolder . DIRECTORY_SEPARATOR . 'autoload.php';
}
$this->db = \Db::getInstance();
}
protected function getPreUpgradeVersion()
{
return $this->normalizeVersion(\Configuration::get('PS_VERSION_DB'));
}
/**
* Add missing levels in version.
* Example: 1.7 will become 1.7.0.0.
*
* @param string $version
*
* @return string
*
* @internal public for tests
*/
public function normalizeVersion($version)
{
$arrayVersion = explode('.', $version);
if (count($arrayVersion) < 4) {
$arrayVersion = array_pad($arrayVersion, 4, '0');
}
return implode('.', $arrayVersion);
}
protected function checkVersionIsNewer($oldVersion)
{
if (strpos($this->destinationUpgradeVersion, '.') === false) {
throw new UpgradeException($this->container->getTranslator()->trans('%s is not a valid version number.', array($this->destinationUpgradeVersion), 'Modules.Autoupgrade.Admin'));
}
$versionCompare = version_compare($this->destinationUpgradeVersion, $oldVersion);
if ($versionCompare === -1) {
throw new UpgradeException(
$this->container->getTranslator()->trans('[ERROR] Version to install is too old.', array(), 'Modules.Autoupgrade.Admin')
. ' ' .
$this->container->getTranslator()->trans(
'Current version: %oldversion%. Version to install: %newversion%.',
array(
'%oldversion%' => $oldVersion,
'%newversion%' => $this->destinationUpgradeVersion,
),
'Modules.Autoupgrade.Admin'
));
} elseif ($versionCompare === 0) {
throw new UpgradeException($this->container->getTranslator()->trans('You already have the %s version.', array($this->destinationUpgradeVersion), 'Modules.Autoupgrade.Admin'));
}
}
/**
* Ask the core to disable the modules not coming from PrestaShop.
*/
protected function disableCustomModules()
{
$this->container->getModuleAdapter()->disableNonNativeModules($this->pathToPhpUpgradeScripts);
}
protected function upgradeDb($oldversion)
{
$upgrade_dir_sql = $this->pathToInstallFolder . '/upgrade/sql';
$sqlContentVersion = $this->applySqlParams(
$this->getUpgradeSqlFilesListToApply($upgrade_dir_sql, $oldversion));
foreach ($sqlContentVersion as $upgrade_file => $sqlContent) {
foreach ($sqlContent as $query) {
$this->runQuery($upgrade_file, $query);
}
}
}
protected function getUpgradeSqlFilesListToApply($upgrade_dir_sql, $oldversion)
{
if (!file_exists($upgrade_dir_sql)) {
throw new UpgradeException($this->container->getTranslator()->trans('Unable to find upgrade directory in the installation path.', array(), 'Modules.Autoupgrade.Admin'));
}
$upgradeFiles = $neededUpgradeFiles = array();
if ($handle = opendir($upgrade_dir_sql)) {
while (false !== ($file = readdir($handle))) {
if ($file[0] === '.') {
continue;
}
if (!is_readable($upgrade_dir_sql . DIRECTORY_SEPARATOR . $file)) {
throw new UpgradeException($this->container->getTranslator()->trans('Error while loading SQL upgrade file "%s".', array($file), 'Modules.Autoupgrade.Admin'));
}
$upgradeFiles[] = str_replace('.sql', '', $file);
}
closedir($handle);
}
if (empty($upgradeFiles)) {
throw new UpgradeException($this->container->getTranslator()->trans('Cannot find the SQL upgrade files. Please check that the %s folder is not empty.', array($upgrade_dir_sql), 'Modules.Autoupgrade.Admin'));
}
natcasesort($upgradeFiles);
foreach ($upgradeFiles as $version) {
if (version_compare($version, $oldversion) == 1 && version_compare($this->destinationUpgradeVersion, $version) != -1) {
$neededUpgradeFiles[$version] = $upgrade_dir_sql . DIRECTORY_SEPARATOR . $version . '.sql';
}
}
return $neededUpgradeFiles;
}
/**
* Replace some placeholders in the SQL upgrade files (prefix, engine...).
*
* @param array $sqlFiles
*
* @return array of SQL requests per version
*/
protected function applySqlParams(array $sqlFiles)
{
$search = array('PREFIX_', 'ENGINE_TYPE');
$replace = array(_DB_PREFIX_, (defined('_MYSQL_ENGINE_') ? _MYSQL_ENGINE_ : 'MyISAM'));
$sqlRequests = array();
foreach ($sqlFiles as $version => $file) {
$sqlContent = file_get_contents($file) . "\n";
$sqlContent = str_replace($search, $replace, $sqlContent);
$sqlContent = preg_split("/;\s*[\r\n]+/", $sqlContent);
$sqlRequests[$version] = $sqlContent;
}
return $sqlRequests;
}
/**
* ToDo, check to move this in a database class.
*
* @param string $upgrade_file File in which the request is stored (for logs)
* @param string $query
*/
protected function runQuery($upgrade_file, $query)
{
$query = trim($query);
if (empty($query)) {
return;
}
// If php code have to be executed
if (strpos($query, '/* PHP:') !== false) {
return $this->runPhpQuery($upgrade_file, $query);
}
$this->runSqlQuery($upgrade_file, $query);
}
protected function runPhpQuery($upgrade_file, $query)
{
// 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);
$parameters = (isset($parameters[1]) && is_array($parameters[1])) ?
$parameters[1] :
array();
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 (!file_exists($this->pathToPhpUpgradeScripts . strtolower($func_name) . '.php')) {
$this->logger->error('[ERROR] ' . $upgrade_file . ' PHP - missing file ' . $query);
$this->container->getState()->setWarningExists(true);
} else {
require_once $this->pathToPhpUpgradeScripts . strtolower($func_name) . '.php';
$phpRes = call_user_func_array($func_name, $parameters);
}
}
// Or an object method
else {
$func_name = array($php[0], str_replace($pattern[0], '', $php[1]));
$this->logger->error('[ERROR] ' . $upgrade_file . ' PHP - Object Method call is forbidden (' . $php[0] . '::' . str_replace($pattern[0], '', $php[1]) . ')');
$this->container->getState()->setWarningExists(true);
}
if (isset($phpRes) && (is_array($phpRes) && !empty($phpRes['error'])) || $phpRes === false) {
$this->logger->error('
[ERROR] PHP ' . $upgrade_file . ' ' . $query . "\n" . '
' . (empty($phpRes['error']) ? '' : $phpRes['error'] . "\n") . '
' . (empty($phpRes['msg']) ? '' : ' - ' . $phpRes['msg'] . "\n"));
$this->container->getState()->setWarningExists(true);
} else {
$this->logger->debug('<div class="upgradeDbOk">[OK] PHP ' . $upgrade_file . ' : ' . $query . '</div>');
}
}
protected function runSqlQuery($upgrade_file, $query)
{
if (strstr($query, 'CREATE TABLE') !== false) {
$pattern = '/CREATE TABLE.*[`]*' . _DB_PREFIX_ . '([^`]*)[`]*\s\(/';
preg_match($pattern, $query, $matches);
if (!empty($matches[1])) {
$drop = 'DROP TABLE IF EXISTS `' . _DB_PREFIX_ . $matches[1] . '`;';
if ($this->db->execute($drop, false)) {
$this->logger->debug('<div class="upgradeDbOk">' . $this->container->getTranslator()->trans('[DROP] SQL %s table has been dropped.', array('`' . _DB_PREFIX_ . $matches[1] . '`'), 'Modules.Autoupgrade.Admin') . '</div>');
}
}
}
if ($this->db->execute($query, false)) {
$this->logger->debug('<div class="upgradeDbOk">[OK] SQL ' . $upgrade_file . ' ' . $query . '</div>');
return;
}
$error = $this->db->getMsgError();
$error_number = $this->db->getNumberError();
$this->logger->warning('
<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->logger->error('SQL ' . $upgrade_file . ' ' . $error_number . ' in ' . $query . ': ' . $error);
$this->container->getState()->setWarningExists(true);
}
}
public function writeNewSettings()
{
// Do nothing
}
protected function runRecurrentQueries()
{
$this->db->execute('UPDATE `' . _DB_PREFIX_ . 'configuration` SET `name` = \'PS_LEGACY_IMAGES\' WHERE name LIKE \'0\' AND `value` = 1');
$this->db->execute('UPDATE `' . _DB_PREFIX_ . 'configuration` SET `value` = 0 WHERE `name` LIKE \'PS_LEGACY_IMAGES\'');
if ($this->db->getValue('SELECT COUNT(id_product_download) FROM `' . _DB_PREFIX_ . 'product_download` WHERE `active` = 1') > 0) {
$this->db->execute('UPDATE `' . _DB_PREFIX_ . 'configuration` SET `value` = 1 WHERE `name` LIKE \'PS_VIRTUAL_PROD_FEATURE_ACTIVE\'');
}
// Exported from the end of doUpgrade()
$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="' . $this->destinationUpgradeVersion . '" WHERE name = "PS_VERSION_DB"', false);
}
protected function upgradeLanguages()
{
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 = $this->db->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'lang` WHERE `active` = 1');
if (!is_array($langs)) {
return;
}
foreach ($langs as $lang) {
$this->upgradeLanguage($lang);
}
}
abstract protected function upgradeLanguage($lang);
protected function generateHtaccess()
{
$this->loadEntityInterface();
if (file_exists(_PS_ROOT_DIR_ . '/classes/Tools.php')) {
require_once _PS_ROOT_DIR_ . '/classes/Tools.php';
}
if (!class_exists('ToolsCore') || !method_exists('ToolsCore', 'generateHtaccess')) {
return;
}
$url_rewrite = (bool) $this->db->getvalue('SELECT `value` FROM `' . _DB_PREFIX_ . 'configuration` WHERE name=\'PS_REWRITING_SETTINGS\'');
if (!defined('_MEDIA_SERVER_1_')) {
define('_MEDIA_SERVER_1_', '');
}
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) && 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) && 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) && 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) && 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) && 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) && 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) && 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) && 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) && 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) && 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) && 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) && 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) && 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) && 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) && class_exists('GroupCore')) {
eval('class Group extends GroupCore{}');
}
\ToolsCore::generateHtaccess(null, $url_rewrite);
}
protected function loadEntityInterface()
{
require_once _PS_ROOT_DIR_ . '/src/Core/Foundation/Database/EntityInterface.php';
}
protected function cleanXmlFiles()
{
$files = array(
$this->container->getProperty(UpgradeContainer::PS_ADMIN_PATH) . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . 'default' . DIRECTORY_SEPARATOR . 'template' . DIRECTORY_SEPARATOR . 'controllers' . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . 'header.tpl',
_PS_ROOT_DIR_ . '/app/cache/dev/class_index.php',
_PS_ROOT_DIR_ . '/app/cache/prod/class_index.php',
_PS_ROOT_DIR_ . '/cache/class_index.php',
_PS_ROOT_DIR_ . '/config/xml/blog-fr.xml',
_PS_ROOT_DIR_ . '/config/xml/default_country_modules_list.xml',
_PS_ROOT_DIR_ . '/config/xml/modules_list.xml',
_PS_ROOT_DIR_ . '/config/xml/modules_native_addons.xml',
_PS_ROOT_DIR_ . '/config/xml/must_have_modules_list.xml',
_PS_ROOT_DIR_ . '/config/xml/tab_modules_list.xml',
_PS_ROOT_DIR_ . '/config/xml/trusted_modules_list.xml',
_PS_ROOT_DIR_ . '/config/xml/untrusted_modules_list.xml',
_PS_ROOT_DIR_ . '/var/cache/dev/class_index.php',
_PS_ROOT_DIR_ . '/var/cache/prod/class_index.php',
);
foreach ($files as $path) {
if (file_exists($path)) {
unlink($path);
}
}
}
protected function disableOverrides()
{
$exist = $this->db->getValue('SELECT `id_configuration` FROM `' . _DB_PREFIX_ . 'configuration` WHERE `name` LIKE \'PS_DISABLE_OVERRIDES\'');
if ($exist) {
$this->db->execute('UPDATE `' . _DB_PREFIX_ . 'configuration` SET value = 1 WHERE `name` LIKE \'PS_DISABLE_OVERRIDES\'');
} else {
$this->db->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 (class_exists('PrestaShopAutoload') && method_exists('PrestaShopAutoload', 'generateIndex')) {
\PrestaShopAutoload::getInstance()->_include_override_path = false;
\PrestaShopAutoload::getInstance()->generateIndex();
}
}
protected function updateTheme()
{
$themeAdapter = new ThemeAdapter($this->db, $this->destinationUpgradeVersion);
$themeName = $themeAdapter->getDefaultTheme();
// The merchant can ask for keeping its current theme.
if (!$this->container->getUpgradeConfiguration()->shouldSwitchToDefaultTheme()) {
return;
}
$themeErrors = $themeAdapter->enableTheme($themeName);
if ($themeErrors !== true) {
throw new UpgradeException($themeErrors);
}
}
protected function runCoreCacheClean()
{
\Tools::clearCache();
}
}

View File

@@ -0,0 +1,186 @@
<?php
/*
* 2007-2018 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\AutoUpgrade\UpgradeTools\CoreUpgrader;
use PrestaShop\Module\AutoUpgrade\Tools14;
use PrestaShop\Module\AutoUpgrade\UpgradeContainer;
use PrestaShop\Module\AutoUpgrade\UpgradeException;
use PrestaShop\Module\AutoUpgrade\UpgradeTools\FilesystemAdapter;
use PrestaShop\Module\AutoUpgrade\UpgradeTools\SettingsFileWriter;
class CoreUpgrader16 extends CoreUpgrader
{
/**
* Complete path to the settings.inc.php
*
* @var string
*/
private $pathToSettingsFile;
/**
* Generate a new settings file.
*/
public function writeNewSettings()
{
if (!defined('_PS_CACHE_ENABLED_')) {
define('_PS_CACHE_ENABLED_', '0');
}
$caches = array('CacheMemcache', 'CacheApc', 'CacheFs', 'CacheMemcached',
'CacheXcache', );
$datas = array(
'_DB_SERVER_' => _DB_SERVER_,
'_DB_NAME_' => _DB_NAME_,
'_DB_USER_' => _DB_USER_,
'_DB_PASSWD_' => _DB_PASSWD_,
'_DB_PREFIX_' => _DB_PREFIX_,
'_MYSQL_ENGINE_' => _MYSQL_ENGINE_,
'_PS_CACHING_SYSTEM_' => ((defined('_PS_CACHING_SYSTEM_') && in_array(_PS_CACHING_SYSTEM_, $caches)) ? _PS_CACHING_SYSTEM_ : 'CacheMemcache'),
'_PS_CACHE_ENABLED_' => _PS_CACHE_ENABLED_,
'_COOKIE_KEY_' => _COOKIE_KEY_,
'_COOKIE_IV_' => _COOKIE_IV_,
'_PS_CREATION_DATE_' => defined('_PS_CREATION_DATE_') ? _PS_CREATION_DATE_ : date('Y-m-d'),
'_PS_VERSION_' => $this->destinationUpgradeVersion,
'_PS_DIRECTORY_' => __PS_BASE_URI__,
);
if (defined('_RIJNDAEL_KEY_') && defined('_RIJNDAEL_IV_')) {
$datas['_RIJNDAEL_KEY_'] = _RIJNDAEL_KEY_;
$datas['_RIJNDAEL_IV_'] = _RIJNDAEL_IV_;
} elseif (function_exists('openssl_encrypt')) {
$datas['_RIJNDAEL_KEY_'] = Tools14::passwdGen(32);
$datas['_RIJNDAEL_IV_'] = base64_encode(openssl_random_pseudo_bytes(openssl_cipher_iv_length('AES-128-CBC')));
} elseif (function_exists('mcrypt_encrypt')) {
$datas['_RIJNDAEL_KEY_'] = Tools14::passwdGen(mcrypt_get_key_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
$datas['_RIJNDAEL_IV_'] = base64_encode(mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND));
}
$writer = new SettingsFileWriter($this->container->getTranslator());
$writer->writeSettingsFile($this->pathToSettingsFile, $datas);
$this->logger->debug($this->container->getTranslator()->trans('Settings file updated', array(), 'Modules.Autoupgrade.Admin'));
}
protected function initConstants()
{
parent::initConstants();
$this->pathToSettingsFile = $this->container->getProperty(UpgradeContainer::PS_ROOT_PATH) . '/config/settings.inc.php';
// Kept for potential BC with old PS versions
define('SETTINGS_FILE', $this->pathToSettingsFile);
}
protected function getPreUpgradeVersion()
{
if (!file_exists($this->pathToSettingsFile)) {
throw new UpgradeException($this->container->getTranslator()->trans('The config/settings.inc.php file was not found.', array(), 'Modules.Autoupgrade.Admin'));
}
include_once $this->pathToSettingsFile;
return _PS_VERSION_;
}
protected function upgradeLanguage($lang)
{
require_once _PS_TOOL_DIR_ . 'tar/Archive_Tar.php';
$lang_pack = json_decode(Tools14::file_get_contents('http' . (extension_loaded('openssl')
? 's' : '') . '://www.prestashop.com/download/lang_packs/get_language_pack.php?version=' . $this->destinationUpgradeVersion . '&iso_lang=' . $lang['iso_code']));
if (!$lang_pack) {
return;
}
if ($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, 'gz');
$files_list = $gz->listContent();
if (!$this->container->getUpgradeConfiguration()->shouldKeepMails()) {
$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);
}
}
}
}
protected function loadEntityInterface()
{
require_once _PS_ROOT_DIR_ . '/Core/Foundation/Database/Core_Foundation_Database_EntityInterface.php';
}
protected function runCoreCacheClean()
{
parent::runCoreCacheClean();
// delete cache filesystem if activated
if (defined('_PS_CACHE_ENABLED_') && false != _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->container->getProperty(UpgradeContainer::PS_ROOT_PATH) . '/cache/cachefs/');
}
FilesystemAdapter::deleteDirectory(_PS_CACHEFS_DIRECTORY_, false);
if (class_exists('CacheFs', false)) {
$this->createCacheFsDirectories((int) $depth);
}
}
}
}
private function createCacheFsDirectories($level_depth, $directory = false)
{
if (!$directory) {
if (!defined('_PS_CACHEFS_DIRECTORY_')) {
define('_PS_CACHEFS_DIRECTORY_', $this->container->getProperty(UpgradeContainer::PS_ROOT_PATH) . '/cache/cachefs/');
}
$directory = _PS_CACHEFS_DIRECTORY_;
}
$chars = '0123456789abcdef';
for ($i = 0; $i < strlen($chars); ++$i) {
$new_dir = $directory . $chars[$i] . '/';
if (mkdir($new_dir, 0775) && chmod($new_dir, 0775) && $level_depth - 1 > 0) {
$this->createCacheFsDirectories($level_depth - 1, $new_dir);
}
}
}
}

View File

@@ -0,0 +1,115 @@
<?php
/*
* 2007-2018 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\AutoUpgrade\UpgradeTools\CoreUpgrader;
use PrestaShop\Module\AutoUpgrade\UpgradeException;
/**
* Class used to modify the core of PrestaShop, on the files are copied on the filesystem.
* It will run subtasks such as database upgrade, language upgrade etc.
*/
class CoreUpgrader17 extends CoreUpgrader
{
protected function initConstants()
{
parent::initConstants();
/*if (!file_exists(SETTINGS_FILE_PHP)) {
throw new UpgradeException($this->container->getTranslator()->trans('The app/config/parameters.php file was not found.', array(), 'Modules.Autoupgrade.Admin'));
}
if (!file_exists(SETTINGS_FILE_YML)) {
throw new UpgradeException($this->container->getTranslator()->trans('The app/config/parameters.yml file was not found.', array(), 'Modules.Autoupgrade.Admin'));
}*/
// Container may be needed to run upgrade scripts
$this->container->getSymfonyAdapter()->initAppKernel();
}
protected function upgradeDb($oldversion)
{
parent::upgradeDb($oldversion);
$commandResult = $this->container->getSymfonyAdapter()->runSchemaUpgradeCommand();
if (0 !== $commandResult['exitCode']) {
throw (new UpgradeException($this->container->getTranslator()->trans('Error upgrading Doctrine schema', array(), 'Modules.Autoupgrade.Admin')))
->setQuickInfos(explode("\n", $commandResult['output']));
}
}
protected function upgradeLanguage($lang)
{
$isoCode = $lang['iso_code'];
if (!\Validate::isLangIsoCode($isoCode)) {
return;
}
$errorsLanguage = array();
if (!\Language::downloadLanguagePack($isoCode, _PS_VERSION_, $errorsLanguage)) {
throw new UpgradeException(
$this->container->getTranslator()->trans(
'Download of the language pack %lang% failed. %details%',
[
'%lang%' => $isoCode,
'%details%' => implode('; ', $errorsLanguage),
],
'Modules.Autoupgrade.Admin'
)
);
}
$lang_pack = \Language::getLangDetails($isoCode);
\Language::installSfLanguagePack($lang_pack['locale'], $errorsLanguage);
if (!$this->container->getUpgradeConfiguration()->shouldKeepMails()) {
\Language::installEmailsLanguagePack($lang_pack, $errorsLanguage);
}
if (!empty($errorsLanguage)) {
throw new UpgradeException(
$this->container->getTranslator()->trans(
'Error while updating translations for lang %lang%. %details%',
[
'%lang%' => $isoCode,
'%details%' => implode('; ', $errorsLanguage),
],
'Modules.Autoupgrade.Admin'
)
);
}
\Language::loadLanguages();
// TODO: Update AdminTranslationsController::addNewTabs to install tabs translated
// CLDR has been updated on PS 1.7.6.0. From this version, updates are not needed anymore.
if (method_exists('\PrestaShop\PrestaShop\Core\Cldr\Update', 'fetchLocale')) {
$cldrUpdate = new \PrestaShop\PrestaShop\Core\Cldr\Update(_PS_TRANSLATIONS_DIR_);
$cldrUpdate->fetchLocale(\Language::getLocaleByIso($isoCode));
}
}
}

View File

@@ -0,0 +1,65 @@
<?php
/*
* 2007-2018 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\AutoUpgrade\UpgradeTools;
use Db;
class Database
{
private $db;
public function __construct(Db $db)
{
$this->db = $db;
}
public function getAllTables()
{
$tables = $this->db->executeS('SHOW TABLES LIKE "' . _DB_PREFIX_ . '%"', true, false);
$all_tables = array();
foreach ($tables as $v) {
$table = array_shift($v);
$all_tables[$table] = $table;
}
return $all_tables;
}
/**
* ToDo: Send tables list instead.
*/
public function cleanTablesAfterBackup(array $tablesToClean)
{
foreach ($tablesToClean as $table) {
$this->db->execute('DROP TABLE IF EXISTS `' . bqSql($table) . '`');
$this->db->execute('DROP VIEW IF EXISTS `' . bqSql($table) . '`');
}
$this->db->execute('SET FOREIGN_KEY_CHECKS=1');
}
}

View File

@@ -0,0 +1,150 @@
<?php
/*
* 2007-2018 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\AutoUpgrade\UpgradeTools;
use PrestaShop\Module\AutoUpgrade\Parameters\UpgradeConfiguration;
class FileFilter
{
/**
* @var UpgradeConfiguration
*/
protected $configuration;
/**
* @var string Autoupgrade sub directory*
*/
protected $autoupgradeDir;
public function __construct(UpgradeConfiguration $configuration, $autoupgradeDir = 'autoupgrade')
{
$this->configuration = $configuration;
$this->autoupgradeDir = $autoupgradeDir;
}
/**
* AdminSelfUpgrade::backupIgnoreAbsoluteFiles.
*
* @return array
*/
public function getFilesToIgnoreOnBackup()
{
// during backup, do not save
$backupIgnoreAbsoluteFiles = array(
'/app/cache',
'/cache/smarty/compile',
'/cache/smarty/cache',
'/cache/tcpdf',
'/cache/cachefs',
'/var/cache',
// do not care about the two autoupgrade dir we use;
'/modules/autoupgrade',
'/admin/autoupgrade',
);
if (!$this->configuration->shouldBackupImages()) {
$backupIgnoreAbsoluteFiles[] = '/img';
} else {
$backupIgnoreAbsoluteFiles[] = '/img/tmp';
}
return $backupIgnoreAbsoluteFiles;
}
/**
* AdminSelfUpgrade::restoreIgnoreAbsoluteFiles.
*
* @return array
*/
public function getFilesToIgnoreOnRestore()
{
$restoreIgnoreAbsoluteFiles = array(
'/app/config/parameters.php',
'/app/config/parameters.yml',
'/modules/autoupgrade',
'/admin/autoupgrade',
'.',
'..',
);
if (!$this->configuration->shouldBackupImages()) {
$restoreIgnoreAbsoluteFiles[] = '/img';
} else {
$restoreIgnoreAbsoluteFiles[] = '/img/tmp';
}
return $restoreIgnoreAbsoluteFiles;
}
/**
* AdminSelfUpgrade::excludeAbsoluteFilesFromUpgrade.
*
* @return array
*/
public function getFilesToIgnoreOnUpgrade()
{
// do not copy install, neither app/config/parameters.php in case it would be present
$excludeAbsoluteFilesFromUpgrade = array(
'/app/config/parameters.php',
'/app/config/parameters.yml',
'/install',
'/install-dev',
);
// this will exclude autoupgrade dir from admin, and autoupgrade from modules
// If set to false, we need to preserve the default themes
if (!$this->configuration->shouldUpdateDefaultTheme()) {
$excludeAbsoluteFilesFromUpgrade[] = '/themes/classic';
$excludeAbsoluteFilesFromUpgrade[] = '/themes/default-bootstrap';
}
return $excludeAbsoluteFilesFromUpgrade;
}
/**
* AdminSelfUpgrade::backupIgnoreFiles
* AdminSelfUpgrade::excludeFilesFromUpgrade
* AdminSelfUpgrade::restoreIgnoreFiles.
*
* These files are checked in every subfolder of the directory tree and can match
* several time, while the others are only matching a file from the project root.
*
* @return array
*/
public function getExcludeFiles()
{
return array(
'.',
'..',
'.svn',
'.git',
$this->autoupgradeDir,
);
}
}

View File

@@ -0,0 +1,257 @@
<?php
/*
* 2007-2018 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\AutoUpgrade\UpgradeTools;
use PrestaShop\Module\AutoUpgrade\Tools14;
class FilesystemAdapter
{
private $restoreFilesFilename;
private $fileFilter;
private $autoupgradeDir;
private $adminSubDir;
private $prodRootDir;
/**
* Somes elements to find in a folder.
* If one of them cannot be found, we can consider that the release is invalid.
*
* @var array
*/
private $releaseFileChecks = array(
'files' => array(
'index.php',
'config/defines.inc.php',
),
'folders' => array(
'classes',
'controllers',
),
);
public function __construct(FileFilter $fileFilter, $restoreFilesFilename,
$autoupgradeDir, $adminSubDir, $prodRootDir)
{
$this->fileFilter = $fileFilter;
$this->restoreFilesFilename = $restoreFilesFilename;
$this->autoupgradeDir = $autoupgradeDir;
$this->adminSubDir = $adminSubDir;
$this->prodRootDir = $prodRootDir;
}
/**
* Delete directory and subdirectories.
*
* @param string $dirname Directory name
*/
public static function deleteDirectory($dirname, $delete_self = true)
{
return Tools14::deleteDirectory($dirname, $delete_self);
}
public function listFilesInDir($dir, $way = 'backup', $list_directories = false)
{
$list = array();
$dir = rtrim($dir, '/') . DIRECTORY_SEPARATOR;
$allFiles = false;
if (is_dir($dir) && is_readable($dir)) {
$allFiles = scandir($dir);
}
if (!is_array($allFiles)) {
return $list;
}
foreach ($allFiles as $file) {
$fullPath = $dir . $file;
// skip broken symbolic links
if (is_link($fullPath) && !is_readable($fullPath)) {
continue;
}
if ($this->isFileSkipped($file, $fullPath, $way)) {
continue;
}
if (is_dir($fullPath)) {
$list = array_merge($list, $this->listFilesInDir($fullPath, $way, $list_directories));
if ($list_directories) {
$list[] = $fullPath;
}
} else {
$list[] = $fullPath;
}
}
return $list;
}
/**
* this function list all files that will be remove to retrieve the filesystem states before the upgrade.
*
* @return array of files to delete
*/
public function listFilesToRemove()
{
$prev_version = preg_match('#auto-backupfiles_V([0-9.]*)_#', $this->restoreFilesFilename, $matches);
if ($prev_version) {
$prev_version = $matches[1];
}
// if we can't find the diff file list corresponding to _PS_VERSION_ and prev_version,
// let's assume to remove every files
$toRemove = $this->listFilesInDir($this->prodRootDir, 'restore', true);
// if a file in "ToRemove" has been skipped during backup,
// just keep it
foreach ($toRemove as $key => $file) {
$filename = substr($file, strrpos($file, '/') + 1);
$toRemove[$key] = preg_replace('#^/admin#', $this->adminSubDir, $file);
// this is a really sensitive part, so we add an extra checks: preserve everything that contains "autoupgrade"
if ($this->isFileSkipped($filename, $file, 'backup') || strpos($file, $this->autoupgradeDir)) {
unset($toRemove[$key]);
}
}
return $toRemove;
}
/**
* Retrieve a list of sample files to be deleted from the release.
*
* @param array $directoryList
*
* @return array Files to remove from the release
*/
public function listSampleFilesFromArray(array $directoryList)
{
$res = array();
foreach ($directoryList as $directory) {
$res = array_merge($res, $this->listSampleFiles($directory['path'], $directory['filter']));
}
return $res;
}
/**
* listSampleFiles will make a recursive call to scandir() function
* and list all file which match to the $fileext suffixe (this can be an extension or whole filename).
*
* @param string $dir directory to look in
* @param string $fileext suffixe filename
*
* @return array of files
*/
public function listSampleFiles($dir, $fileext = '.jpg')
{
$res = array();
$dir = rtrim($dir, '/') . DIRECTORY_SEPARATOR;
$toDel = false;
if (is_dir($dir) && is_readable($dir)) {
$toDel = scandir($dir);
}
// copied (and kind of) adapted from AdminImages.php
if (is_array($toDel)) {
foreach ($toDel as $file) {
if ($file[0] != '.') {
if (preg_match('#' . preg_quote($fileext, '#') . '$#i', $file)) {
$res[] = $dir . $file;
} elseif (is_dir($dir . $file)) {
$res = array_merge($res, $this->listSampleFiles($dir . $file, $fileext));
}
}
}
}
return $res;
}
/**
* bool _skipFile : check whether a file is in backup or restore skip list.
*
* @param string $file : current file or directory name eg:'.svn' , 'settings.inc.php'
* @param string $fullpath : current file or directory fullpath eg:'/home/web/www/prestashop/app/config/parameters.php'
* @param string $way : 'backup' , 'upgrade'
* @param string $temporaryWorkspace : If needed, another folder than the shop root can be used (used for releases)
*/
public function isFileSkipped($file, $fullpath, $way = 'backup', $temporaryWorkspace = null)
{
$fullpath = str_replace('\\', '/', $fullpath); // wamp compliant
$rootpath = str_replace(
'\\',
'/',
(null !== $temporaryWorkspace) ? $temporaryWorkspace : $this->prodRootDir
);
if (in_array($file, $this->fileFilter->getExcludeFiles())) {
return true;
}
$ignoreList = array();
if ('backup' === $way) {
$ignoreList = $this->fileFilter->getFilesToIgnoreOnBackup();
} elseif ('restore' === $way) {
$ignoreList = $this->fileFilter->getFilesToIgnoreOnRestore();
} elseif ('upgrade' === $way) {
$ignoreList = $this->fileFilter->getFilesToIgnoreOnUpgrade();
}
foreach ($ignoreList as $path) {
$path = str_replace(DIRECTORY_SEPARATOR . 'admin', DIRECTORY_SEPARATOR . $this->adminSubDir, $path);
if ($fullpath === $rootpath . $path) {
return true;
}
}
// by default, don't skip
return false;
}
/**
* Check a directory has some files available in every release of PrestaShop.
*
* @param string $path Workspace to check
*
* @return bool
*/
public function isReleaseValid($path)
{
foreach ($this->releaseFileChecks as $type => $elements) {
foreach ($elements as $element) {
$fullPath = $path . DIRECTORY_SEPARATOR . $element;
if ('files' === $type && !is_file($fullPath)) {
return false;
}
if ('folders' === $type && !is_dir($fullPath)) {
return false;
}
}
}
return true;
}
}

View File

@@ -0,0 +1,202 @@
<?php
/*
* 2007-2018 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\AutoUpgrade\UpgradeTools;
use PrestaShop\Module\AutoUpgrade\Tools14;
use PrestaShop\Module\AutoUpgrade\UpgradeException;
use PrestaShop\Module\AutoUpgrade\ZipAction;
class ModuleAdapter
{
private $db;
private $translator;
// PS version to update
private $upgradeVersion;
private $modulesPath;
private $tempPath;
/**
* @var ZipAction
*/
private $zipAction;
/**
* @var SymfonyAdapter
*/
private $symfonyAdapter;
// Cached instance
private $moduleDataUpdater;
public function __construct($db, $translator, $modulesPath, $tempPath, $upgradeVersion, ZipAction $zipAction, SymfonyAdapter $symfonyAdapter)
{
$this->db = $db;
$this->translator = $translator;
$this->modulesPath = $modulesPath;
$this->tempPath = $tempPath;
$this->upgradeVersion = $upgradeVersion;
$this->zipAction = $zipAction;
$this->symfonyAdapter = $symfonyAdapter;
}
/**
* Available only from 1.7. Can't be called on PS 1.6.
*
* @return \PrestaShop\PrestaShop\Adapter\Module\ModuleDataUpdater
*/
public function getModuleDataUpdater()
{
if (null === $this->moduleDataUpdater) {
$this->moduleDataUpdater = $this->symfonyAdapter
->initAppKernel()
->getContainer()
->get('prestashop.core.module.updater');
}
return $this->moduleDataUpdater;
}
/**
* Upgrade action, disabling all modules not made by PrestaShop.
*
* It seems the 1.6 version of is the safest, as it does not actually load the modules.
*
* @param string $pathToUpgradeScripts Path to the PHP Upgrade scripts
*/
public function disableNonNativeModules($pathToUpgradeScripts)
{
require_once $pathToUpgradeScripts . 'deactivate_custom_modules.php';
deactivate_custom_modules();
}
/**
* list modules to upgrade and save them in a serialized array in $this->toUpgradeModuleList.
*
* @param array $modulesFromAddons Modules available on the marketplace for download
*
* @return array Module available on the local filesystem and on the marketplace
*/
public function listModulesToUpgrade(array $modulesFromAddons)
{
$list = array();
$dir = $this->modulesPath;
if (!is_dir($dir)) {
throw (new UpgradeException($this->translator->trans('[ERROR] %dir% does not exist or is not a directory.', array('%dir%' => $dir), 'Modules.Autoupgrade.Admin')))
->addQuickInfo($this->translator->trans('[ERROR] %s does not exist or is not a directory.', array($dir), 'Modules.Autoupgrade.Admin'))
->setSeverity(UpgradeException::SEVERITY_ERROR);
// $this->next_desc = $this->trans('Nothing has been extracted. It seems the unzip step has been skipped.', array(), 'Modules.Autoupgrade.Admin');
}
foreach (scandir($dir) as $module_name) {
if (is_file($dir . DIRECTORY_SEPARATOR . $module_name)) {
continue;
}
if (!is_file($dir . $module_name . DIRECTORY_SEPARATOR . $module_name . '.php')) {
continue;
}
$id_addons = array_search($module_name, $modulesFromAddons);
if (false !== $id_addons && $module_name !== 'autoupgrade') {
$list[] = array('id' => $id_addons, 'name' => $module_name);
}
}
return $list;
}
/**
* Upgrade module $name (identified by $id_module on addons server).
*
* @param int $id
* @param string $name
*/
public function upgradeModule($id, $name)
{
$zip_fullpath = $this->tempPath . DIRECTORY_SEPARATOR . $name . '.zip';
$addons_url = 'api.addons.prestashop.com';
$protocolsList = array('https://' => 443, 'http://' => 80);
if (!extension_loaded('openssl')) {
unset($protocolsList['https://']);
} else {
unset($protocolsList['http://']);
}
$postData = 'version=' . $this->upgradeVersion . '&method=module&id_module=' . (int) $id;
// Make the request
$opts = array(
'http' => array(
'method' => 'POST',
'content' => $postData,
'header' => 'Content-type: application/x-www-form-urlencoded',
'timeout' => 10,
),
);
$context = stream_context_create($opts);
foreach ($protocolsList as $protocol => $port) {
// file_get_contents can return false if https is not supported (or warning)
$content = Tools14::file_get_contents($protocol . $addons_url, false, $context);
if ($content == false || substr($content, 5) == '<?xml') {
continue;
}
if ($content === null) {
$msg = '<strong>' . $this->translator->trans('[ERROR] No response from Addons server.', array(), 'Modules.Autoupgrade.Admin') . '</strong>';
throw new UpgradeException($msg);
}
if (false === (bool) file_put_contents($zip_fullpath, $content)) {
$msg = '<strong>' . $this->translator->trans('[ERROR] Unable to write module %s\'s zip file in temporary directory.', array($name), 'Modules.Autoupgrade.Admin') . '</strong>';
throw new UpgradeException($msg);
}
if (filesize($zip_fullpath) <= 300) {
unlink($zip_fullpath);
}
// unzip in modules/[mod name] old files will be conserved
if (!$this->zipAction->extract($zip_fullpath, $this->modulesPath)) {
throw (new UpgradeException('<strong>' . $this->translator->trans('[WARNING] Error when trying to extract module %s.', array($name), 'Modules.Autoupgrade.Admin') . '</strong>'))
->setSeverity(UpgradeException::SEVERITY_WARNING);
}
if (file_exists($zip_fullpath)) {
unlink($zip_fullpath);
}
// Only 1.7 step
if (version_compare($this->upgradeVersion, '1.7.0.0', '>=')
&& !$this->getModuleDataUpdater()->upgrade($name)) {
throw (new UpgradeException('<strong>' . $this->translator->trans('[WARNING] Error when trying to upgrade module %s.', array($name), 'Modules.Autoupgrade.Admin') . '</strong>'))
->setSeverity(UpgradeException::SEVERITY_WARNING)
->setQuickInfos(\Module::getInstanceByName($name)->getErrors());
}
return;
}
}
}

View File

@@ -0,0 +1,89 @@
<?php
/*
* 2007-2018 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\AutoUpgrade\UpgradeTools;
use PrestaShop\Module\AutoUpgrade\UpgradeException;
use PrestaShop\Module\AutoUpgrade\Log\LoggerInterface;
use Symfony\Component\Filesystem\Filesystem;
use PrestaShop\Module\AutoUpgrade\LoggedEvent;
class SettingsFileWriter
{
private $translator;
public function __construct($translator)
{
$this->translator = $translator;
}
public function migrateSettingsFile(LoggerInterface $logger)
{
if (class_exists('\PrestaShopBundle\Install\Upgrade')) {
\PrestaShopBundle\Install\Upgrade::migrateSettingsFile(new LoggedEvent($logger));
}
}
/**
* @param string $filePath
* @param array $data
*
* @throws UpgradeException
*/
public function writeSettingsFile($filePath, $data)
{
if (!is_writable($filePath)) {
throw new UpgradeException($this->translator->trans('Error when opening settings.inc.php file in write mode', array(), 'Modules.Autoupgrade.Admin'));
}
// Create backup file
$filesystem = new Filesystem();
$filesystem->copy($filePath, $filePath . '.bck');
$fd = fopen($filePath, 'w');
fwrite($fd, '<?php' . PHP_EOL);
foreach ($data as $name => $value) {
if (false === fwrite($fd, "define('$name', '{$this->checkString($value)}');" . PHP_EOL)) {
throw new UpgradeException($this->translator->trans('Error when generating new settings.inc.php file.', array(), 'Modules.Autoupgrade.Admin'));
}
}
fclose($fd);
}
public function checkString($string)
{
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
if (!is_numeric($string)) {
$string = addslashes($string);
$string = str_replace(array("\n", "\r"), '', $string);
}
return $string;
}
}

View File

@@ -0,0 +1,79 @@
<?php
/*
* 2007-2018 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\AutoUpgrade\UpgradeTools;
/**
* TODO: Create a class for 1.7 env and another one for 1.6 ?
*/
class SymfonyAdapter
{
/**
* @var string Version on which PrestaShop is being upgraded
*/
private $destinationPsVersion;
public function __construct($destinationPsVersion)
{
$this->destinationPsVersion = $destinationPsVersion;
}
public function runSchemaUpgradeCommand()
{
if (version_compare($this->destinationPsVersion, '1.7.1.1', '>=')) {
$schemaUpgrade = new \PrestaShopBundle\Service\Database\Upgrade();
$outputCommand = 'prestashop:schema:update-without-foreign';
} else {
$schemaUpgrade = new \PrestaShopBundle\Service\Cache\Refresh();
$outputCommand = 'doctrine:schema:update';
}
$schemaUpgrade->addDoctrineSchemaUpdate();
$output = $schemaUpgrade->execute();
return $output[$outputCommand];
}
/**
* Return the AppKernel, after initialization
*
* @return \AppKernel
*/
public function initAppKernel()
{
global $kernel;
if (!$kernel instanceof \AppKernel) {
require_once _PS_ROOT_DIR_ . '/app/AppKernel.php';
$env = (true == _PS_MODE_DEV_) ? 'dev' : 'prod';
$kernel = new \AppKernel($env, _PS_MODE_DEV_);
$kernel->loadClassCache();
$kernel->boot();
}
return $kernel;
}
}

View File

@@ -0,0 +1,87 @@
<?php
/*
* 2007-2018 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\AutoUpgrade\UpgradeTools;
use PrestaShop\Module\AutoUpgrade\UpgradeContainer;
class TaskRepository
{
public static function get($step, UpgradeContainer $container)
{
switch ($step) {
// MISCELLANEOUS (upgrade configuration, checks etc.)
case 'checkFilesVersion':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Miscellaneous\CheckFilesVersion($container);
case 'compareReleases':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Miscellaneous\CompareReleases($container);
case 'getChannelInfo':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Miscellaneous\GetChannelInfo($container);
case 'updateConfig':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Miscellaneous\UpdateConfig($container);
// ROLLBACK
case 'noRollbackFound':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Rollback\NoRollbackFound($container);
case 'restoreDb':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Rollback\RestoreDb($container);
case 'restoreFiles':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Rollback\RestoreFiles($container);
case 'rollback':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Rollback\Rollback($container);
case 'rollbackComplete':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Rollback\RollbackComplete($container);
// UPGRADE
case 'backupDb':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Upgrade\BackupDb($container);
case 'backupFiles':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Upgrade\BackupFiles($container);
case 'cleanDatabase':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Upgrade\CleanDatabase($container);
case 'download':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Upgrade\Download($container);
case 'removeSamples':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Upgrade\RemoveSamples($container);
case 'upgradeComplete':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Upgrade\UpgradeComplete($container);
case 'upgradeDb':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Upgrade\UpgradeDb($container);
case 'upgradeFiles':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Upgrade\UpgradeFiles($container);
case 'upgradeModules':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Upgrade\UpgradeModules($container);
case 'upgradeNow':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Upgrade\UpgradeNow($container);
case 'unzip':
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\Upgrade\Unzip($container);
}
error_log('Unknown step ' . $step);
return new \PrestaShop\Module\AutoUpgrade\TaskRunner\NullTask($container);
}
}

View File

@@ -0,0 +1,106 @@
<?php
/*
* 2007-2018 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\AutoUpgrade\UpgradeTools;
class ThemeAdapter
{
private $db;
private $upgradeVersion;
public function __construct($db, $upgradeVersion)
{
$this->db = $db;
$this->upgradeVersion = $upgradeVersion;
}
/**
* Enable the given theme on the shop.
*
* @param string $themeName
*
* @return mixed
*/
public function enableTheme($themeName)
{
return version_compare($this->upgradeVersion, '1.7.0.0', '>=') ?
$this->enableTheme17($themeName) :
$this->enableTheme16($themeName);
}
/**
* Get the default theme name provided with PrestaShop.
*
* @return string
*/
public function getDefaultTheme()
{
return version_compare($this->upgradeVersion, '1.7.0.0', '>=') ?
'classic' : // 1.7
'default-bootstrap'; // 1.6
}
/**
* Backward compatibility function for theme enabling.
*
* @param string $themeName
*/
private function enableTheme16($themeName)
{
$this->db->execute('UPDATE `' . _DB_PREFIX_ . 'shop`
SET id_theme = (SELECT id_theme FROM `' . _DB_PREFIX_ . 'theme` WHERE name LIKE \'' . $themeName . '\')');
$this->db->execute('DELETE FROM `' . _DB_PREFIX_ . 'theme` WHERE name LIKE \'default\' OR name LIKE \'prestashop\'');
return true;
}
/**
* Use 1.7 theme manager is order to enable the new theme.
*
* @param string $themeName
*
* @return bool|array
*/
private function enableTheme17($themeName)
{
$themeManager = $this->getThemeManager();
$isThemeEnabled = $themeManager->enable($themeName);
if (!$isThemeEnabled) {
$errors = $themeManager->getErrors($themeName);
return $errors ? $errors : 'Unknown error';
}
return true;
}
private function getThemeManager()
{
return (new \PrestaShop\PrestaShop\Core\Addon\Theme\ThemeManagerBuilder(\Context::getContext(), $this->db))->build();
}
}

View File

@@ -0,0 +1,212 @@
<?php
/*
* 2007-2018 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\AutoUpgrade\UpgradeTools;
use PrestaShop\Module\AutoUpgrade\Tools14;
use PrestaShop\Module\AutoUpgrade\Log\LoggerInterface;
class Translation
{
private $installedLanguagesIso;
private $logger;
private $translator;
public function __construct($translator, LoggerInterface $logger, $installedLanguagesIso)
{
$this->logger = $logger;
$this->translator = $translator;
$this->installedLanguagesIso = $installedLanguagesIso;
}
/**
* getTranslationFileType.
*
* @param string $file filepath to check
*
* @return string type of translation item
*/
public function getTranslationFileType($file)
{
$type = false;
// line shorter
$separator = addslashes(DIRECTORY_SEPARATOR);
$translation_dir = $separator . 'translations' . $separator;
$regex_module = '#' . $separator . 'modules' . $separator . '.*' . $translation_dir . '(' . implode('|', $this->installedLanguagesIso) . ')\.php#';
if (preg_match($regex_module, $file)) {
$type = 'module';
} elseif (preg_match('#' . $translation_dir . '(' . implode('|', $this->installedLanguagesIso) . ')' . $separator . 'admin\.php#', $file)) {
$type = 'back office';
} elseif (preg_match('#' . $translation_dir . '(' . implode('|', $this->installedLanguagesIso) . ')' . $separator . 'errors\.php#', $file)) {
$type = 'error message';
} elseif (preg_match('#' . $translation_dir . '(' . implode('|', $this->installedLanguagesIso) . ')' . $separator . 'fields\.php#', $file)) {
$type = 'field';
} elseif (preg_match('#' . $translation_dir . '(' . implode('|', $this->installedLanguagesIso) . ')' . $separator . 'pdf\.php#', $file)) {
$type = 'pdf';
} elseif (preg_match('#' . $separator . 'themes' . $separator . '(default|prestashop)' . $separator . 'lang' . $separator . '(' . implode('|', $this->installedLanguagesIso) . ')\.php#', $file)) {
$type = 'front office';
}
return $type;
}
public function isTranslationFile($file)
{
return $this->getTranslationFileType($file) !== false;
}
/**
* merge the translations of $orig into $dest, according to the $type of translation file.
*
* @param string $orig file from upgrade package
* @param string $dest filepath of destination
* @param string $type type of translation file (module, back office, front office, field, pdf, error)
*
* @return bool
*/
public function mergeTranslationFile($orig, $dest, $type)
{
switch ($type) {
case 'front office':
$var_name = '_LANG';
break;
case 'back office':
$var_name = '_LANGADM';
break;
case 'error message':
$var_name = '_ERRORS';
break;
case 'field':
$var_name = '_FIELDS';
break;
case 'module':
$var_name = '_MODULE';
break;
case 'pdf':
$var_name = '_LANGPDF';
break;
case 'mail':
$var_name = '_LANGMAIL';
break;
default:
return false;
}
if (!file_exists($orig)) {
$this->logger->notice($this->translator->trans('[NOTICE] File %s does not exist, merge skipped.', array($orig), 'Modules.Autoupgrade.Admin'));
return true;
}
include $orig;
if (!isset($$var_name)) {
$this->logger->warning($this->translator->trans(
'[WARNING] %variablename% variable missing in file %filename%. Merge skipped.',
array(
'%variablename%' => $var_name,
'%filename%' => $orig,
),
'Modules.Autoupgrade.Admin'
));
return true;
}
$var_orig = $$var_name;
if (!file_exists($dest)) {
$this->logger->notice($this->translator->trans('[NOTICE] File %s does not exist, merge skipped.', array($dest), 'Modules.Autoupgrade.Admin'));
return false;
}
include $dest;
if (!isset($$var_name)) {
// in that particular case : file exists, but variable missing, we need to delete that file
// (if not, this invalid file will be copied in /translations during upgradeDb process)
if ('module' == $type && file_exists($dest)) {
unlink($dest);
}
$this->logger->warning($this->translator->trans(
'[WARNING] %variablename% variable missing in file %filename%. File %filename% deleted and merge skipped.',
array(
'%variablename%' => $var_name,
'%filename%' => $dest,
),
'Modules.Autoupgrade.Admin'
));
return false;
}
$var_dest = $$var_name;
$merge = array_merge($var_orig, $var_dest);
$fd = fopen($dest, 'w');
if ($fd === false) {
return false;
}
fwrite($fd, "<?php\n\nglobal \$" . $var_name . ";\n\$" . $var_name . " = array();\n");
foreach ($merge as $k => $v) {
if (get_magic_quotes_gpc()) {
$v = stripslashes($v);
}
if ('mail' == $type) {
fwrite($fd, '$' . $var_name . '[\'' . $this->escape($k) . '\'] = \'' . $this->escape($v) . '\';' . "\n");
} else {
fwrite($fd, '$' . $var_name . '[\'' . $this->escape($k, true) . '\'] = \'' . $this->escape($v, true) . '\';' . "\n");
}
}
fwrite($fd, "\n?>");
fclose($fd);
return true;
}
/**
* Escapes illegal characters in a string.
* Extracted from DB class, in order to avoid dependancies.
*
* @see DbCore::_escape()
*
* @param string $str
* @param bool $html_ok Does data contain HTML code ? (optional)
*
* @return string
*/
private function escape($str, $html_ok = false)
{
$search = array('\\', "\0", "\n", "\r", "\x1a", "'", '"');
$replace = array('\\\\', '\\0', '\\n', '\\r', "\Z", "\'", '\"');
$str = str_replace($search, $replace, $str);
if (!$html_ok) {
return strip_tags(Tools14::nl2br($str));
}
return $str;
}
}

View File

@@ -0,0 +1,92 @@
<?php
/*
* 2007-2018 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\Module\AutoUpgrade\UpgradeTools;
class Translator
{
private $caller;
public function __construct($caller)
{
$this->caller = $caller;
}
/**
* Translate a string to the current language.
*
* This methods has the same signature as the 1.7 trans method, but only relies
* on the module translation files.
*
* @param string $id Original text
* @param array $parameters Parameters to apply
* @param string $domain Unused
* @param string $locale Unused
*
* @return string Translated string with parameters applied
*/
public function trans($id, array $parameters = array(), $domain = 'Modules.Autoupgrade.Admin', $locale = null)
{
// If PrestaShop core is not instancied properly, do not try to translate
if (!method_exists('\Context', 'getContext') || null === \Context::getContext()->language) {
return $this->applyParameters($id, $parameters);
}
if (method_exists('\Translate', 'getModuleTranslation')) {
$translated = \Translate::getModuleTranslation('autoupgrade', $id, $this->caller, null);
if (!count($parameters)) {
return $translated;
}
} else {
$translated = $id;
}
return $this->applyParameters($translated, $parameters);
}
/**
* @param string $id
* @param array $parameters
*
* @return string Translated string with parameters applied
*
* @internal Public for tests
*/
public function applyParameters($id, array $parameters = array())
{
// Replace placeholders for non numeric keys
foreach ($parameters as $placeholder => $value) {
if (is_int($placeholder)) {
continue;
}
$id = str_replace($placeholder, $value, $id);
unset($parameters[$placeholder]);
}
return call_user_func_array('sprintf', array_merge(array($id), $parameters));
}
}