function reorderpositions()
{
    /* Clean products positions */
    if ($cat = Category::getCategories(1, false, false)) {
        foreach ($cat as $i => $categ) {
            Product::cleanPositions((int) $categ['id_category']);
        }
    }
    //clean Category position and delete old position system
    Language::loadLanguages();
    $language = Language::getLanguages();
    $cat_parent = Db::getInstance()->ExecuteS('SELECT DISTINCT c.id_parent FROM `' . _DB_PREFIX_ . 'category` c WHERE id_category != 1');
    foreach ($cat_parent as $parent) {
        $result = Db::getInstance()->ExecuteS('
							SELECT DISTINCT c.*, cl.*
							FROM `' . _DB_PREFIX_ . 'category` c 
							LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (c.`id_category` = cl.`id_category` AND `id_lang` = ' . (int) Configuration::get('PS_LANG_DEFAULT') . ')
							WHERE c.id_parent = ' . (int) $parent['id_parent'] . '
							ORDER BY name ASC');
        foreach ($result as $i => $categ) {
            Db::getInstance()->Execute('
			UPDATE `' . _DB_PREFIX_ . 'category`
			SET `position` = ' . (int) $i . '
			WHERE `id_parent` = ' . (int) $categ['id_parent'] . '
			AND `id_category` = ' . (int) $categ['id_category']);
        }
        $result = Db::getInstance()->ExecuteS('
							SELECT DISTINCT c.*, cl.*
							FROM `' . _DB_PREFIX_ . 'category` c 
							LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (c.`id_category` = cl.`id_category`)
							WHERE c.id_parent = ' . (int) $parent['id_parent'] . '
							ORDER BY name ASC');
        // Remove number from category name
        foreach ($result as $i => $categ) {
            Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'category` c 
			LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (c.`id_category` = cl.`id_category`)
			SET `name` = \'' . preg_replace('/^[0-9]+\\./', '', $categ['name']) . '\' 
			WHERE c.id_category = ' . (int) $categ['id_category'] . ' AND id_lang = \'' . (int) $categ['id_lang'] . '\'');
        }
    }
    /* Clean CMS positions */
    if ($cms_cat = CMSCategory::getCategories(1, false, false)) {
        foreach ($cms_cat as $i => $categ) {
            CMS::cleanPositions((int) $categ['id_cms_category']);
        }
    }
}
示例#2
0
 public static function generateHtaccess($path, $rewrite_settings, $cache_control, $specific = '', $disableMuliviews = false)
 {
     $tab = array('ErrorDocument' => array(), 'RewriteEngine' => array(), 'RewriteRule' => array());
     $multilang = Language::countActiveLanguages() > 1;
     // ErrorDocument
     $tab['ErrorDocument']['comment'] = '# Catch 404 errors';
     $tab['ErrorDocument']['content'] = '404 ' . __PS_BASE_URI__ . '404.php';
     // RewriteEngine
     $tab['RewriteEngine']['comment'] = '# URL rewriting module activation';
     // RewriteRules
     $tab['RewriteRule']['comment'] = '# URL rewriting rules';
     // Compatibility with the old image filesystem
     if (Configuration::get('PS_LEGACY_IMAGES')) {
         $tab['RewriteRule']['content']['^([a-z0-9]+)\\-([a-z0-9]+)(\\-[_a-zA-Z0-9-]*)/[_a-zA-Z0-9-]*\\.jpg$'] = _PS_PROD_IMG_ . '$1-$2$3.jpg [L]';
         $tab['RewriteRule']['content']['^([0-9]+)\\-([0-9]+)/[_a-zA-Z0-9-]*\\.jpg$'] = _PS_PROD_IMG_ . '$1-$2.jpg [L]';
     }
     // Rewriting for product image id < 100 millions
     $tab['RewriteRule']['content']['^([0-9])(\\-[_a-zA-Z0-9-]*)?/[_a-zA-Z0-9-]*\\.jpg$'] = _PS_PROD_IMG_ . '$1/$1$2.jpg [L]';
     $tab['RewriteRule']['content']['^([0-9])([0-9])(\\-[_a-zA-Z0-9-]*)?/[_a-zA-Z0-9-]*\\.jpg$'] = _PS_PROD_IMG_ . '$1/$2/$1$2$3.jpg [L]';
     $tab['RewriteRule']['content']['^([0-9])([0-9])([0-9])(\\-[_a-zA-Z0-9-]*)?/[_a-zA-Z0-9-]*\\.jpg$'] = _PS_PROD_IMG_ . '$1/$2/$3/$1$2$3$4.jpg [L]';
     $tab['RewriteRule']['content']['^([0-9])([0-9])([0-9])([0-9])(\\-[_a-zA-Z0-9-]*)?/[_a-zA-Z0-9-]*\\.jpg$'] = _PS_PROD_IMG_ . '$1/$2/$3/$4/$1$2$3$4$5.jpg [L]';
     $tab['RewriteRule']['content']['^([0-9])([0-9])([0-9])([0-9])([0-9])(\\-[_a-zA-Z0-9-]*)?/[_a-zA-Z0-9-]*\\.jpg$'] = _PS_PROD_IMG_ . '$1/$2/$3/$4/$5/$1$2$3$4$5$6.jpg [L]';
     $tab['RewriteRule']['content']['^([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\\-[_a-zA-Z0-9-]*)?/[_a-zA-Z0-9-]*\\.jpg$'] = _PS_PROD_IMG_ . '$1/$2/$3/$4/$5/$6/$1$2$3$4$5$6$7.jpg [L]';
     $tab['RewriteRule']['content']['^([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\\-[_a-zA-Z0-9-]*)?/[_a-zA-Z0-9-]*\\.jpg$'] = _PS_PROD_IMG_ . '$1/$2/$3/$4/$5/$6/$7/$1$2$3$4$5$6$7$8.jpg [L]';
     $tab['RewriteRule']['content']['^([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\\-[_a-zA-Z0-9-]*)?/[_a-zA-Z0-9-]*\\.jpg$'] = _PS_PROD_IMG_ . '$1/$2/$3/$4/$5/$6/$7/$8/$1$2$3$4$5$6$7$8$9.jpg [L]';
     $tab['RewriteRule']['content']['^c/([0-9]+)(\\-[_a-zA-Z0-9-]*)/[_a-zA-Z0-9-]*\\.jpg$'] = 'img/c/$1$2.jpg [L]';
     $tab['RewriteRule']['content']['^c/([a-zA-Z-]+)/[a-zA-Z0-9-]+\\.jpg$'] = 'img/c/$1.jpg [L]';
     if ($multilang) {
         $tab['RewriteRule']['content']['^([a-z]{2})/[a-zA-Z0-9-]*/([0-9]+)\\-[a-zA-Z0-9-]*\\.html'] = 'product.php?id_product=$2&isolang=$1 [QSA,L]';
         $tab['RewriteRule']['content']['^([a-z]{2})/([0-9]+)\\-[a-zA-Z0-9-]*\\.html'] = 'product.php?id_product=$2&isolang=$1 [QSA,L]';
         $tab['RewriteRule']['content']['^([a-z]{2})/([0-9]+)\\-[a-zA-Z0-9-]*(/[a-zA-Z0-9-]*)+'] = 'category.php?id_category=$2&isolang=$1&noredirect=1 [QSA,L]';
         $tab['RewriteRule']['content']['^([a-z]{2})/([0-9]+)\\-[a-zA-Z0-9-]*'] = 'category.php?id_category=$2&isolang=$1 [QSA,L]';
         $tab['RewriteRule']['content']['^([a-z]{2})/content/([0-9]+)\\-[a-zA-Z0-9-]*'] = 'cms.php?isolang=$1&id_cms=$2 [QSA,L]';
         $tab['RewriteRule']['content']['^([a-z]{2})/content/category/([0-9]+)\\-[a-zA-Z0-9-]*'] = 'cms.php?isolang=$1&id_cms_category=$2 [QSA,L]';
         $tab['RewriteRule']['content']['^([a-z]{2})/([0-9]+)__[a-zA-Z0-9-]*'] = 'supplier.php?isolang=$1&id_supplier=$2 [QSA,L]';
         $tab['RewriteRule']['content']['^([a-z]{2})/([0-9]+)_[a-zA-Z0-9-]*'] = 'manufacturer.php?isolang=$1&id_manufacturer=$2 [QSA,L]';
     }
     // PS BASE URI automaticaly prepend the string, do not use PS defines for the image directories
     $tab['RewriteRule']['content']['^([0-9]+)(\\-[_a-zA-Z0-9-]*)/[_a-zA-Z0-9-]*\\.jpg$'] = 'img/c/$1$2.jpg [L]';
     $tab['RewriteRule']['content']['^([0-9]+)\\-[a-zA-Z0-9-]*\\.html'] = 'product.php?id_product=$1 [QSA,L]';
     $tab['RewriteRule']['content']['^[a-zA-Z0-9-]*/([0-9]+)\\-[a-zA-Z0-9-]*\\.html'] = 'product.php?id_product=$1 [QSA,L]';
     // Notice : the id_category rule has to be after product rules.
     // If not, category with number in their name will result a bug
     $tab['RewriteRule']['content']['^([0-9]+)\\-[a-zA-Z0-9-]*(/[a-zA-Z0-9-]*)+'] = 'category.php?id_category=$1&noredirect=1 [QSA,L]';
     $tab['RewriteRule']['content']['^([0-9]+)\\-[a-zA-Z0-9-]*'] = 'category.php?id_category=$1 [QSA,L]';
     $tab['RewriteRule']['content']['^([0-9]+)__([a-zA-Z0-9-]*)'] = 'supplier.php?id_supplier=$1 [QSA,L]';
     $tab['RewriteRule']['content']['^([0-9]+)_([a-zA-Z0-9-]*)'] = 'manufacturer.php?id_manufacturer=$1 [QSA,L]';
     $tab['RewriteRule']['content']['^content/([0-9]+)\\-([a-zA-Z0-9-]*)'] = 'cms.php?id_cms=$1 [QSA,L]';
     $tab['RewriteRule']['content']['^content/category/([0-9]+)\\-([a-zA-Z0-9-]*)'] = 'cms.php?id_cms_category=$1 [QSA,L]';
     // Compatibility with the old URLs
     if (!Configuration::get('PS_INSTALL_VERSION') or version_compare(Configuration::get('PS_INSTALL_VERSION'), '1.4.0.7') == -1) {
         // This is a nasty copy/paste of the previous links, but with "lang-en" instead of "en"
         // Do not update it when you add something in the one at the top, it's only for the old links
         $tab['RewriteRule']['content']['^lang-([a-z]{2})/([a-zA-Z0-9-]*)/([0-9]+)\\-([a-zA-Z0-9-]*)\\.html'] = 'product.php?id_product=$3&isolang=$1 [QSA,L]';
         $tab['RewriteRule']['content']['^lang-([a-z]{2})/([0-9]+)\\-([a-zA-Z0-9-]*)\\.html'] = 'product.php?id_product=$2&isolang=$1 [QSA,L]';
         $tab['RewriteRule']['content']['^lang-([a-z]{2})/([0-9]+)\\-([a-zA-Z0-9-]*)'] = 'category.php?id_category=$2&isolang=$1 [QSA,L]';
         $tab['RewriteRule']['content']['^content/([0-9]+)\\-([a-zA-Z0-9-]*)'] = 'cms.php?id_cms=$1 [QSA,L]';
         $tab['RewriteRule']['content']['^content/category/([0-9]+)\\-([a-zA-Z0-9-]*)'] = 'cms.php?id_cms_category=$1 [QSA,L]';
     }
     Language::loadLanguages();
     $default_meta = Meta::getMetasByIdLang((int) Configuration::get('PS_LANG_DEFAULT'));
     if ($multilang) {
         foreach (Language::getLanguages() as $language) {
             foreach (Meta::getMetasByIdLang($language['id_lang']) as $key => $meta) {
                 if (!empty($meta['url_rewrite']) and Validate::isLinkRewrite($meta['url_rewrite'])) {
                     $tab['RewriteRule']['content']['^' . $language['iso_code'] . '/' . $meta['url_rewrite'] . '$'] = $meta['page'] . '.php?isolang=' . $language['iso_code'] . ' [QSA,L]';
                 } elseif (array_key_exists($key, $default_meta) && $default_meta[$key]['url_rewrite'] != '') {
                     $tab['RewriteRule']['content']['^' . $language['iso_code'] . '/' . $default_meta[$key]['url_rewrite'] . '$'] = $default_meta[$key]['page'] . '.php?isolang=' . $language['iso_code'] . ' [QSA,L]';
                 }
             }
             $tab['RewriteRule']['content']['^' . $language['iso_code'] . '$'] = $language['iso_code'] . '/ [QSA,L]';
             $tab['RewriteRule']['content']['^' . $language['iso_code'] . '/([^?&]*)$'] = '$1?isolang=' . $language['iso_code'] . ' [QSA,L]';
         }
     } else {
         foreach ($default_meta as $key => $meta) {
             if (!empty($meta['url_rewrite'])) {
                 $tab['RewriteRule']['content']['^' . $meta['url_rewrite'] . '$'] = $meta['page'] . '.php [QSA,L]';
             } elseif (array_key_exists($key, $default_meta) && $default_meta[$key]['url_rewrite'] != '') {
                 $tab['RewriteRule']['content']['^' . $default_meta[$key]['url_rewrite'] . '$'] = $default_meta[$key]['page'] . '.php [QSA,L]';
             }
         }
     }
     if (!($writeFd = @fopen($path, 'w'))) {
         return false;
     }
     // PS Comments
     fwrite($writeFd, "# .htaccess automaticaly generated by PrestaShop e-commerce open-source solution\n");
     fwrite($writeFd, "# WARNING: PLEASE DO NOT MODIFY THIS FILE MANUALLY. IF NECESSARY, ADD YOUR SPECIFIC CONFIGURATION WITH THE HTACCESS GENERATOR IN BACK OFFICE\n");
     fwrite($writeFd, "# http://www.prestashop.com - http://www.prestashop.com/forums\n\n");
     if (!empty($specific)) {
         fwrite($writeFd, $specific);
     }
     // RewriteEngine
     fwrite($writeFd, "\n<IfModule mod_rewrite.c>\n");
     if ($disableMuliviews) {
         fwrite($writeFd, "\n# Disable Multiviews\nOptions -Multiviews\n\n");
     }
     fwrite($writeFd, $tab['RewriteEngine']['comment'] . "\nRewriteEngine on\n\n");
     fwrite($writeFd, $tab['RewriteRule']['comment'] . "\n");
     // Webservice
     fwrite($writeFd, 'RewriteRule ^api/?(.*)$ ' . __PS_BASE_URI__ . "webservice/dispatcher.php?url=\$1 [QSA,L]\n");
     // Classic URL rewriting
     if ($rewrite_settings) {
         foreach ($tab['RewriteRule']['content'] as $rule => $url) {
             fwrite($writeFd, 'RewriteRule ' . $rule . ' ' . __PS_BASE_URI__ . $url . "\n");
         }
     }
     fwrite($writeFd, "</IfModule>\n\n");
     // ErrorDocument
     fwrite($writeFd, $tab['ErrorDocument']['comment'] . "\nErrorDocument " . $tab['ErrorDocument']['content'] . "\n");
     // Cache control
     if ($cache_control) {
         $cacheControl = "\n<IfModule mod_expires.c>\n\tExpiresActive On\n\tExpiresByType image/gif \"access plus 1 month\"\n\tExpiresByType image/jpeg \"access plus 1 month\"\n\tExpiresByType image/png \"access plus 1 month\"\n\tExpiresByType text/css \"access plus 1 week\"\n\tExpiresByType text/javascript \"access plus 1 week\"\n\tExpiresByType application/javascript \"access plus 1 week\"\n\tExpiresByType application/x-javascript \"access plus 1 week\"\n\tExpiresByType image/x-icon \"access plus 1 year\"\n</IfModule>\n\nFileETag INode MTime Size\n<IfModule mod_deflate.c>\n\tAddOutputFilterByType DEFLATE text/html\n\tAddOutputFilterByType DEFLATE text/css\n\tAddOutputFilterByType DEFLATE text/javascript\n\tAddOutputFilterByType DEFLATE application/javascript\n\tAddOutputFilterByType DEFLATE application/x-javascript\n</IfModule>\n\t\t\t\t";
         fwrite($writeFd, $cacheControl);
     }
     fclose($writeFd);
     Module::hookExec('afterCreateHtaccess');
     return true;
 }
 public static function downloadAndInstallLanguagePack($iso, $version = null, $params = null, $install = true)
 {
     if (!Validate::isLanguageIsoCode((string) $iso)) {
         return false;
     }
     if ($version == null) {
         $version = _PS_VERSION_;
     }
     $lang_pack = false;
     $lang_pack_ok = false;
     $errors = array();
     $file = _PS_TRANSLATIONS_DIR_ . (string) $iso . '.gzip';
     if (!($lang_pack_link = Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/get_language_pack.php?version=' . $version . '&iso_lang=' . Tools::strtolower((string) $iso)))) {
         $errors[] = Tools::displayError('Archive cannot be downloaded from prestashop.com.');
     } elseif (!($lang_pack = Tools::jsonDecode($lang_pack_link))) {
         $errors[] = Tools::displayError('Error occurred when language was checked according to your Prestashop version.');
     } elseif (empty($lang_pack->error) && ($content = Tools::file_get_contents('http://translations.prestashop.com/download/lang_packs/gzip/' . $lang_pack->version . '/' . Tools::strtolower($lang_pack->iso_code . '.gzip')))) {
         if (!@file_put_contents($file, $content)) {
             if (is_writable(dirname($file))) {
                 @unlink($file);
                 @file_put_contents($file, $content);
             } elseif (!is_writable($file)) {
                 $errors[] = Tools::displayError('Server does not have permissions for writing.') . ' (' . $file . ')';
             }
         }
     }
     if (!file_exists($file)) {
         $errors[] = Tools::displayError('No language pack is available for your version.');
     } elseif ($install) {
         require_once _PS_TOOL_DIR_ . 'tar/Archive_Tar.php';
         $gz = new Archive_Tar($file, true);
         $files_list = AdminTranslationsController::filterTranslationFiles(Language::getLanguagePackListContent((string) $iso, $gz));
         $files_paths = AdminTranslationsController::filesListToPaths($files_list);
         $i = 0;
         $tmp_array = array();
         foreach ($files_paths as $files_path) {
             $path = dirname($files_path);
             if (is_dir(_PS_TRANSLATIONS_DIR_ . '../' . $path) && !is_writable(_PS_TRANSLATIONS_DIR_ . '../' . $path) && !in_array($path, $tmp_array)) {
                 $errors[] = (!$i++ ? Tools::displayError('The archive cannot be extracted.') . ' ' : '') . Tools::displayError('The server does not have permissions for writing.') . ' ' . sprintf(Tools::displayError('Please check rights for %s'), $path);
                 $tmp_array[] = $path;
             }
         }
         if (defined('_PS_HOST_MODE_')) {
             $mails_files = array();
             $other_files = array();
             foreach ($files_list as $key => $data) {
                 if (substr($data['filename'], 0, 5) == 'mails') {
                     $mails_files[] = $data;
                 } else {
                     $other_files[] = $data;
                 }
             }
             $files_list = $other_files;
         }
         if (!$gz->extractList(AdminTranslationsController::filesListToPaths($files_list), _PS_TRANSLATIONS_DIR_ . '../')) {
             $errors[] = sprintf(Tools::displayError('Cannot decompress the translation file for the following language: %s'), (string) $iso);
         }
         // Clear smarty modules cache
         Tools::clearCache();
         if (!Language::checkAndAddLanguage((string) $iso, $lang_pack, false, $params)) {
             $errors[] = sprintf(Tools::displayError('An error occurred while creating the language: %s'), (string) $iso);
         } else {
             // Reset cache
             Language::loadLanguages();
             AdminTranslationsController::checkAndAddMailsFiles((string) $iso, $files_list);
             AdminTranslationsController::addNewTabs((string) $iso, $files_list);
         }
     }
     return count($errors) ? $errors : true;
 }
示例#4
0
 /**
  * Return available languages
  *
  * @param boolean $active Select only active languages
  * @return array Languages
  */
 public static function getLanguages($active = true, $id_shop = false)
 {
     if (!self::$_LANGUAGES) {
         Language::loadLanguages();
     }
     $languages = array();
     foreach (self::$_LANGUAGES as $language) {
         if ($active && !$language['active'] || $id_shop && !isset($language['shops'][(int) $id_shop])) {
             continue;
         }
         $languages[] = $language;
     }
     return $languages;
 }
 $sqlParams[] = "INSERT IGNORE INTO " . _DB_PREFIX_ . "configuration (name, value, date_add, date_upd) VALUES ('PS_SHOP_DOMAIN', '" . Tools::getHttpHost() . "', NOW(), NOW())";
 $sqlParams[] = "INSERT IGNORE INTO " . _DB_PREFIX_ . "configuration (name, value, date_add, date_upd) VALUES ('PS_SHOP_DOMAIN_SSL', '" . Tools::getHttpHost() . "', NOW(), NOW())";
 $sqlParams[] = "INSERT IGNORE INTO " . _DB_PREFIX_ . "configuration (name, value, date_add, date_upd) VALUES ('PS_INSTALL_VERSION', '" . pSQL(INSTALL_VERSION) . "', NOW(), NOW())";
 $sqlParams[] = "INSERT IGNORE INTO " . _DB_PREFIX_ . "configuration (name, value, date_add, date_upd) VALUES ('PS_SHOP_NAME', '" . pSQL($_GET['infosShop']) . "', NOW(), NOW())";
 $sqlParams[] = "INSERT IGNORE INTO " . _DB_PREFIX_ . "configuration (name, value, date_add, date_upd) VALUES ('PS_SHOP_EMAIL', '" . pSQL($_GET['infosEmail']) . "', NOW(), NOW())";
 $sqlParams[] = "INSERT IGNORE INTO " . _DB_PREFIX_ . "configuration (name, value, date_add, date_upd) VALUES ('PS_MAIL_METHOD', '" . pSQL($_GET['infosMailMethod'] == "smtp" ? "2" : "1") . "', NOW(), NOW())";
 $sqlParams[] = 'UPDATE ' . _DB_PREFIX_ . 'configuration SET value = \'' . pSQL($_GET['isoCode']) . '\' WHERE name = \'PS_LOCALE_LANGUAGE\'';
 $sqlParams[] = 'UPDATE ' . _DB_PREFIX_ . 'configuration SET value = \'' . (int) $_GET['catalogMode'] . '\' WHERE name = \'PS_CATALOG_MODE\'';
 $sqlParams[] = "INSERT IGNORE INTO " . _DB_PREFIX_ . "configuration (name, value, date_add, date_upd) VALUES ('PS_SHOP_ACTIVITY', '" . (int) $_GET['infosActivity'] . "', NOW(), NOW())";
 if ((int) $_GET['infosCountry'] != 0) {
     $sqlParams[] = 'UPDATE ' . _DB_PREFIX_ . 'configuration SET value = ' . (int) $_GET['infosCountry'] . ' WHERE name = \'PS_COUNTRY_DEFAULT\'';
     $sqlParams[] = 'UPDATE ' . _DB_PREFIX_ . 'configuration SET value = "' . pSQL($_GET['infosTimezone']) . '" WHERE name = \'PS_TIMEZONE\'';
     $sql_isocode = Db::getInstance()->getValue('SELECT `iso_code` FROM `' . _DB_PREFIX_ . 'country` WHERE `id_country` = ' . (int) $_GET['infosCountry']);
     $sqlParams[] = 'UPDATE ' . _DB_PREFIX_ . 'configuration SET value = \'' . pSQL($sql_isocode) . '\' WHERE name = \'PS_LOCALE_COUNTRY\'';
 }
 Language::loadLanguages();
 Configuration::loadConfiguration();
 require_once dirname(__FILE__) . '/../../config/defines.inc.php';
 require_once dirname(__FILE__) . '/../../classes/LocalizationPack.php';
 $context = stream_context_create(array('http' => array('timeout' => 5)));
 $localization_file = @Tools::file_get_contents('http://www.prestashop.com/download/localization_pack.php?country=' . $_GET['countryName'], false, $context);
 if (!$localization_file and file_exists(dirname(__FILE__) . '/../../localization/' . strtolower($_GET['countryName']) . '.xml')) {
     $localization_file = @file_get_contents(dirname(__FILE__) . '/../../localization/' . strtolower($_GET['countryName']) . '.xml');
 }
 if ($localization_file) {
     $localizationPack = new LocalizationPackCore();
     $localizationPack->loadLocalisationPack($localization_file, '', true);
     if (Configuration::get('PS_LANG_DEFAULT') == 1) {
         $sqlParams[] = 'UPDATE `' . _DB_PREFIX_ . 'configuration` SET `value` = (SELECT id_lang FROM ' . _DB_PREFIX_ . 'lang WHERE iso_code = \'' . pSQL($_GET['isoCode']) . '\') WHERE name = \'PS_LANG_DEFAULT\'';
         // This request is used when _PS_MODE_DEV_ is set to true
         $sqlParams[] = 'UPDATE `' . _DB_PREFIX_ . 'lang` SET `active` = 0 WHERE `iso_code` != \'' . pSQL($_GET['isoCode']) . '\'';
 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');
     }
 }
示例#7
0
 /**
  * Install languages
  *
  * @return array Association between ID and iso array(id_lang => iso, ...)
  */
 public function installLanguages($languages_list = null)
 {
     if ($languages_list == null || !is_array($languages_list) || !count($languages_list)) {
         $languages_list = $this->language->getIsoList();
     }
     $languages_available = $this->language->getIsoList();
     $languages = array();
     foreach ($languages_list as $iso) {
         if (!in_array($iso, $languages_available)) {
             continue;
         }
         if (!file_exists(_PS_INSTALL_LANGS_PATH_ . $iso . '/language.xml')) {
             throw new PrestashopInstallerException($this->language->l('File "language.xml" not found for language iso "%s"', $iso));
         }
         if (!($xml = @simplexml_load_file(_PS_INSTALL_LANGS_PATH_ . $iso . '/language.xml'))) {
             throw new PrestashopInstallerException($this->language->l('File "language.xml" not valid for language iso "%s"', $iso));
         }
         $params_lang = array('name' => (string) $xml->name, 'iso_code' => substr((string) $xml->language_code, 0, 2), 'allow_accented_chars_url' => (string) $xml->allow_accented_chars_url);
         if (InstallSession::getInstance()->safe_mode) {
             Language::checkAndAddLanguage($iso, false, true, $params_lang);
         } else {
             Language::downloadAndInstallLanguagePack($iso, _PS_INSTALL_VERSION_, $params_lang);
         }
         Language::loadLanguages();
         Tools::clearCache();
         if (!($id_lang = Language::getIdByIso($iso))) {
             throw new PrestashopInstallerException($this->language->l('Cannot install language "%s"', $xml->name ? $xml->name : $iso));
         }
         $languages[$id_lang] = $iso;
         // Copy language flag
         if (is_writable(_PS_IMG_DIR_ . 'l/')) {
             if (!copy(_PS_INSTALL_LANGS_PATH_ . $iso . '/flag.jpg', _PS_IMG_DIR_ . 'l/' . $id_lang . '.jpg')) {
                 throw new PrestashopInstallerException($this->language->l('Cannot copy flag language "%s"', _PS_INSTALL_LANGS_PATH_ . $iso . '/flag.jpg => ' . _PS_IMG_DIR_ . 'l/' . $id_lang . '.jpg'));
             }
         }
     }
     return $languages;
 }
示例#8
0
 public static function installLanguagePack($iso, $params, &$errors = array())
 {
     $file = _PS_TRANSLATIONS_DIR_ . (string) $iso . '.gzip';
     $gz = new \Archive_Tar($file, true);
     $files_list = AdminTranslationsController::filterTranslationFiles(Language::getLanguagePackListContent((string) $iso, $gz));
     $files_paths = AdminTranslationsController::filesListToPaths($files_list);
     $tmp_array = array();
     foreach ($files_paths as $files_path) {
         $path = dirname($files_path);
         if (is_dir(_PS_TRANSLATIONS_DIR_ . '../' . $path) && !is_writable(_PS_TRANSLATIONS_DIR_ . '../' . $path) && !in_array($path, $tmp_array)) {
             $error = Tools::displayError('The server does not have permissions for writing.') . ' ' . sprintf(Tools::displayError('Please check permissions for %s'), $path);
             $errors[] = count($tmp_array) == 0 ? Tools::displayError('The archive cannot be extracted.') . ' ' . $error : $error;
             $tmp_array[] = $path;
         }
     }
     if (defined('_PS_HOST_MODE_')) {
         $mails_files = array();
         $other_files = array();
         foreach ($files_list as $key => $data) {
             if (substr($data['filename'], 0, 5) == 'mails') {
                 $mails_files[] = $data;
             }
         }
         $files_list = array_diff($files_list, $mails_files);
     }
     if (!$gz->extractList(AdminTranslationsController::filesListToPaths($files_list), _PS_TRANSLATIONS_DIR_ . '../')) {
         $errors[] = sprintf(Tools::displayError('Cannot decompress the translation file for the following language: %s'), (string) $iso);
     }
     // Clear smarty modules cache
     Tools::clearCache();
     if (!Language::checkAndAddLanguage((string) $iso, false, false, $params)) {
         $errors[] = sprintf(Tools::displayError('An error occurred while creating the language: %s'), (string) $iso);
     } else {
         // Reset cache
         Language::loadLanguages();
         AdminTranslationsController::checkAndAddMailsFiles((string) $iso, $files_list);
         AdminTranslationsController::addNewTabs((string) $iso, $files_list);
     }
     self::installSfLanguagePack(self::getLocaleByIso($iso), $errors);
     return count($errors) ? $errors : true;
 }
 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');
     }
 }
示例#10
0
    /**
     * 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_PHP', $this->prodRootDir . '/app/config/parameters.php');
        define('SETTINGS_FILE_YML', $this->prodRootDir . '/app/config/parameters.yml');
        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/');
        } elseif (!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_PHP)) {
            $this->next = 'error';
            $this->nextQuickInfo[] = $this->l('The app/config/parameters.php file was not found.');
            $this->nextErrors[] = $this->l('The app/config/parameters.php file was not found.');
            return false;
        }
        if (!file_exists(SETTINGS_FILE_YML)) {
            $this->next = 'error';
            $this->nextQuickInfo[] = $this->l('The app/config/parameters.yml file was not found.');
            $this->nextErrors[] = $this->l('The app/config/parameters.yml file was not found.');
            return false;
        }
        $oldversion = Configuration::get('PS_VERSION_DB');
        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/');
        }
        $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 app/config/parameters.php file?');
            $this->nextErrors[] = $this->l('There is no older version. Did you delete or rename the app/config/parameters.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) {
            $this->disableNonNativeModules();
        }
        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;
        $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;
        }
        $sf2Refresh = new \PrestaShopBundle\Service\Cache\Refresh();
        $sf2Refresh->addDoctrineSchemaUpdate();
        $output = $sf2Refresh->execute();
        if (0 !== $output['doctrine:schema:update']['exitCode']) {
            $msgErrors = explode("\n", $output['doctrine:schema:update']['output']);
            $this->nextErrors[] = $this->l('Error upgrading doctrine schema');
            $this->nextQuickInfo[] = $msgErrors;
            $this->next_desc = $msgErrors;
            return false;
        }
        $this->nextQuickInfo[] = $this->l('Database upgrade OK');
        // no error !
        // Settings updated, compile and cache directories must be emptied
        $arrayToClean[] = $this->prodRootDir . '/app/cache/';
        $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);
                    }
                }
            }
        }
        $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\'');
        }
        if (defined('_THEME_NAME_') && $this->updateDefaultTheme && 'classic' === _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);
                        }
                    }
                }
            }
        }
        // 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 = $this->db->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'lang` WHERE `active` = 1');
        if (is_array($langs)) {
            foreach ($langs as $lang) {
                $isoCode = $lang['iso_code'];
                if (Validate::isLangIsoCode($isoCode)) {
                    $errorsLanguage = array();
                    Language::downloadLanguagePack($isoCode, _PS_VERSION_, $errorsLanguage);
                    $lang_pack = Language::getLangDetails($isoCode);
                    Language::installSfLanguagePack($lang_pack['locale'], $errorsLanguage);
                    if (!$this->keepMails) {
                        Language::installEmailsLanguagePack($lang_pack, $errorsLanguage);
                    }
                    if (empty($errorsLanguage)) {
                        Language::loadLanguages();
                        // TODO: Update AdminTranslationsController::addNewTabs to install tabs translated
                        $cldrUpdate = new \PrestaShop\PrestaShop\Core\Cldr\Update(_PS_TRANSLATIONS_DIR_);
                        $cldrUpdate->fetchLocale(Language::getLocaleByIso($isoCode));
                    } else {
                        $this->nextErrors[] = $this->l('Error updating translations');
                        $this->nextQuickInfo[] = $this->l('Error updating translations');
                        $this->next_desc = $this->l('Error updating translations');
                        return false;
                    }
                }
            }
        }
        require_once _PS_ROOT_DIR_ . '/src/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) $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) 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);
        }
        $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_ . '/app/cache/dev/class_index.php')) {
            unlink(_PS_ROOT_DIR_ . '/app/cache/dev/class_index.php');
        }
        if (file_exists(_PS_ROOT_DIR_ . '/app/cache/prod/class_index.php')) {
            unlink(_PS_ROOT_DIR_ . '/app/cache/prod/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 = $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();
            }
        }
        $themeManager = $this->getThemeManager();
        $themeName = $this->changeToDefaultTheme ? 'classic' : _THEME_NAME_;
        $isThemeEnabled = $themeManager->enable($themeName);
        if (!$isThemeEnabled) {
            $themeErrors = $themeManager->getErrors($themeName);
            $this->nextQuickInfo[] = $themeErrors;
            $this->nextErrors[] = $themeErrors;
            $this->next_desc = $themeErrors;
            return false;
        } else {
            Tools::clearCache();
        }
        // 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;
    }
示例#11
0
 public static function downloadAndInstallLanguagePack($iso, $version = null, $params = null)
 {
     require_once _PS_TOOL_DIR_ . 'tar/Archive_Tar.php';
     if (!Validate::isLanguageIsoCode($iso)) {
         return false;
     }
     if ($version == null) {
         $version = _PS_VERSION_;
     }
     $lang_pack = false;
     $lang_pack_ok = false;
     $errors = array();
     $file = _PS_TRANSLATIONS_DIR_ . $iso . '.gzip';
     if (!($lang_pack_link = Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/get_language_pack.php?version=' . $version . '&iso_lang=' . $iso))) {
         $errors[] = Tools::displayError('Archive cannot be downloaded from prestashop.com.');
     } elseif (!($lang_pack = Tools::jsonDecode($lang_pack_link))) {
         $errors[] = Tools::displayError('Error occurred when language was checked according to your Prestashop version.');
     } elseif ($content = Tools::file_get_contents('http://translations.prestashop.com/download/lang_packs/gzip/' . $lang_pack->version . '/' . $lang_pack->iso_code . '.gzip')) {
         if (!@file_put_contents($file, $content)) {
             $errors[] = Tools::displayError('Server does not have permissions for writing.');
         }
     }
     if (file_exists($file)) {
         $gz = new Archive_Tar($file, true);
         $files_list = $gz->listContent();
         if (!$gz->extract(_PS_TRANSLATIONS_DIR_ . '../', false)) {
             $errors[] = Tools::displayError('Cannot decompress the translation file for the following language: ') . (string) $iso;
         }
         if (!Language::checkAndAddLanguage((string) $iso, $lang_pack, false, $params)) {
             $errors[] = Tools::displayError('An error occurred while creating the language: ') . (string) $iso;
         } else {
             // Reset cache
             Language::loadLanguages();
             AdminTranslationsController::checkAndAddMailsFiles($iso, $files_list);
             AdminTranslationsController::addNewTabs($iso, $files_list);
         }
         @unlink($file);
     } else {
         $errors[] = Tools::displayError('No language pack is available for your version.');
     }
     return count($errors) ? $errors : true;
 }