/**
  * Get instance of autoload (singleton)
  *
  * @return Autoload
  */
 public static function getInstance()
 {
     if (!PrestaShopAutoload::$instance) {
         PrestaShopAutoload::$instance = new PrestaShopAutoload();
     }
     return PrestaShopAutoload::$instance;
 }
Exemple #2
0
 public static function generateIndex()
 {
     if (defined('_DB_PREFIX_') && Configuration::get('PS_DISABLE_OVERRIDES')) {
         PrestaShopAutoload::getInstance()->_include_override_path = false;
     }
     PrestaShopAutoload::getInstance()->generateIndex();
 }
Exemple #3
0
<?php

/*
* 2007-2014 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 <*****@*****.**>
*  @copyright  2007-2014 PrestaShop SA
*  @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
// Include some alias functions
require_once _PS_CONFIG_DIR_ . 'alias.php';
require_once _PS_CLASS_DIR_ . 'PrestaShopAutoload.php';
spl_autoload_register(array(PrestaShopAutoload::getInstance(), 'load'));
    public function postProcess()
    {
        /* PrestaShop demo mode */
        if (_PS_MODE_DEMO_) {
            $this->errors[] = Tools::displayError('This functionality has been disabled.');
            return;
        }
        Hook::exec('action' . get_class($this) . ucfirst($this->action) . 'Before', array('controller' => $this));
        if (Tools::isSubmit('submitAddServer')) {
            if ($this->tabAccess['add'] === '1') {
                if (!Tools::getValue('memcachedIp')) {
                    $this->errors[] = Tools::displayError('The Memcached IP is missing.');
                }
                if (!Tools::getValue('memcachedPort')) {
                    $this->errors[] = Tools::displayError('The Memcached port is missing.');
                }
                if (!Tools::getValue('memcachedWeight')) {
                    $this->errors[] = Tools::displayError('The Memcached weight is missing.');
                }
                if (!count($this->errors)) {
                    if (CacheMemcache::addServer(pSQL(Tools::getValue('memcachedIp')), (int) Tools::getValue('memcachedPort'), (int) Tools::getValue('memcachedWeight'))) {
                        Tools::redirectAdmin(self::$currentIndex . '&token=' . Tools::getValue('token') . '&conf=4');
                    } else {
                        $this->errors[] = Tools::displayError('The Memcached server cannot be added.');
                    }
                }
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to add this.');
            }
        }
        if (Tools::getValue('deleteMemcachedServer')) {
            if ($this->tabAccess['add'] === '1') {
                if (CacheMemcache::deleteServer((int) Tools::getValue('deleteMemcachedServer'))) {
                    Tools::redirectAdmin(self::$currentIndex . '&token=' . Tools::getValue('token') . '&conf=4');
                } else {
                    $this->errors[] = Tools::displayError('There was an error when attempting to delete the Memcached server.');
                }
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to delete this.');
            }
        }
        $redirectAdmin = false;
        if ((bool) Tools::getValue('smarty_up')) {
            if ($this->tabAccess['edit'] === '1') {
                Configuration::updateValue('PS_SMARTY_FORCE_COMPILE', Tools::getValue('smarty_force_compile', _PS_SMARTY_NO_COMPILE_));
                Configuration::updateValue('PS_SMARTY_CACHE', Tools::getValue('smarty_cache', 0));
                Configuration::updateValue('PS_SMARTY_CONSOLE', Tools::getValue('smarty_console', 0));
                Configuration::updateValue('PS_SMARTY_CONSOLE_KEY', Tools::getValue('smarty_console_key', 'SMARTY_DEBUG'));
                $redirecAdmin = true;
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to edit this.');
            }
        }
        if ((bool) Tools::getValue('features_detachables_up')) {
            if ($this->tabAccess['edit'] === '1') {
                if (Tools::getValue('combination') || !Combination::isCurrentlyUsed()) {
                    Configuration::updateValue('PS_COMBINATION_FEATURE_ACTIVE', Tools::getValue('combination'));
                }
                if (Tools::getValue('customer_group') && !Group::isCurrentlyUsed()) {
                    Configuration::updateValue('PS_GROUP_FEATURE_ACTIVE', Tools::getValue('customer_group'));
                }
                Configuration::updateValue('PS_FEATURE_FEATURE_ACTIVE', Tools::getValue('feature'));
                $redirectAdmin = true;
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to edit this.');
            }
        }
        if ((bool) Tools::getValue('ccc_up')) {
            if ($this->tabAccess['edit'] === '1') {
                $theme_cache_directory = _PS_ALL_THEMES_DIR_ . $this->context->shop->theme_directory . '/cache/';
                if (((bool) Tools::getValue('PS_CSS_THEME_CACHE') || (bool) Tools::getValue('PS_JS_THEME_CACHE')) && !is_writable($theme_cache_directory)) {
                    $this->errors[] = Tools::displayError(sprintf($this->l('To use Smart Cache directory %s must be writable.'), realpath($theme_cache_directory)));
                }
                if (!Configuration::updateValue('PS_CSS_THEME_CACHE', (int) Tools::getValue('PS_CSS_THEME_CACHE')) || !Configuration::updateValue('PS_JS_THEME_CACHE', (int) Tools::getValue('PS_JS_THEME_CACHE')) || !Configuration::updateValue('PS_HTML_THEME_COMPRESSION', (int) Tools::getValue('PS_HTML_THEME_COMPRESSION')) || !Configuration::updateValue('PS_JS_HTML_THEME_COMPRESSION', (int) Tools::getValue('PS_JS_HTML_THEME_COMPRESSION')) || !Configuration::updateValue('PS_HTACCESS_CACHE_CONTROL', (int) Tools::getValue('PS_HTACCESS_CACHE_CONTROL'))) {
                    $this->errors[] = Tools::displayError('Unknown error.');
                } else {
                    $redirectAdmin = true;
                    if (Configuration::get('PS_HTACCESS_CACHE_CONTROL')) {
                        Tools::generateHtaccess();
                    }
                }
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to edit this.');
            }
        }
        if ((bool) Tools::getValue('media_server_up')) {
            if ($this->tabAccess['edit'] === '1') {
                if (Tools::getValue('_MEDIA_SERVER_1_') != null && !Validate::isFileName(Tools::getValue('_MEDIA_SERVER_1_'))) {
                    $this->errors[] = Tools::displayError('Media server #1 is invalid');
                }
                if (Tools::getValue('_MEDIA_SERVER_2_') != null && !Validate::isFileName(Tools::getValue('_MEDIA_SERVER_2_'))) {
                    $this->errors[] = Tools::displayError('Media server #2 is invalid');
                }
                if (Tools::getValue('_MEDIA_SERVER_3_') != null && !Validate::isFileName(Tools::getValue('_MEDIA_SERVER_3_'))) {
                    $this->errors[] = Tools::displayError('Media server #3 is invalid');
                }
                if (!count($this->errors)) {
                    $base_urls = array();
                    $base_urls['_MEDIA_SERVER_1_'] = Tools::getValue('_MEDIA_SERVER_1_');
                    $base_urls['_MEDIA_SERVER_2_'] = Tools::getValue('_MEDIA_SERVER_2_');
                    $base_urls['_MEDIA_SERVER_3_'] = Tools::getValue('_MEDIA_SERVER_3_');
                    if ($base_urls['_MEDIA_SERVER_1_'] || $base_urls['_MEDIA_SERVER_2_'] || $base_urls['_MEDIA_SERVER_3_']) {
                        Configuration::updateValue('PS_MEDIA_SERVERS', 1);
                    } else {
                        Configuration::updateValue('PS_MEDIA_SERVERS', 0);
                    }
                    rewriteSettingsFile($base_urls, null, null);
                    Tools::clearSmartyCache();
                    Media::clearCache();
                    Tools::generateHtaccess(null, null, null, '', null, array($base_urls['_MEDIA_SERVER_1_'], $base_urls['_MEDIA_SERVER_2_'], $base_urls['_MEDIA_SERVER_3_']));
                    unset($this->_fieldsGeneral['_MEDIA_SERVER_1_']);
                    unset($this->_fieldsGeneral['_MEDIA_SERVER_2_']);
                    unset($this->_fieldsGeneral['_MEDIA_SERVER_3_']);
                    $redirectAdmin = true;
                }
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to edit this.');
            }
        }
        if ((bool) Tools::getValue('ciphering_up') && Configuration::get('PS_CIPHER_ALGORITHM') != (int) Tools::getValue('PS_CIPHER_ALGORITHM')) {
            if ($this->tabAccess['edit'] === '1') {
                $algo = (int) Tools::getValue('PS_CIPHER_ALGORITHM');
                $prev_settings = file_get_contents(_PS_ROOT_DIR_ . '/config/settings.inc.php');
                $new_settings = $prev_settings;
                if ($algo) {
                    if (!function_exists('mcrypt_encrypt')) {
                        $this->errors[] = Tools::displayError('The "Mcrypt" PHP extension is not activated on this server.');
                    } else {
                        if (!strstr($new_settings, '_RIJNDAEL_KEY_')) {
                            $key_size = mcrypt_get_key_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
                            $key = Tools::passwdGen($key_size);
                            $new_settings = preg_replace('/define\\(\'_COOKIE_KEY_\', \'([a-z0-9=\\/+-_]+)\'\\);/i', 'define(\'_COOKIE_KEY_\', \'\\1\');' . "\n" . 'define(\'_RIJNDAEL_KEY_\', \'' . $key . '\');', $new_settings);
                        }
                        if (!strstr($new_settings, '_RIJNDAEL_IV_')) {
                            $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
                            $iv = base64_encode(mcrypt_create_iv($iv_size, MCRYPT_RAND));
                            $new_settings = preg_replace('/define\\(\'_COOKIE_IV_\', \'([a-z0-9=\\/+-_]+)\'\\);/i', 'define(\'_COOKIE_IV_\', \'\\1\');' . "\n" . 'define(\'_RIJNDAEL_IV_\', \'' . $iv . '\');', $new_settings);
                        }
                    }
                }
                if (!count($this->errors)) {
                    // If there is not settings file modification or if the backup and replacement of the settings file worked
                    if ($new_settings == $prev_settings || copy(_PS_ROOT_DIR_ . '/config/settings.inc.php', _PS_ROOT_DIR_ . '/config/settings.old.php') && (bool) file_put_contents(_PS_ROOT_DIR_ . '/config/settings.inc.php', $new_settings)) {
                        Configuration::updateValue('PS_CIPHER_ALGORITHM', $algo);
                        $redirectAdmin = true;
                    } else {
                        $this->errors[] = Tools::displayError('The settings file cannot be overwritten.');
                    }
                }
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to edit this.');
            }
        }
        if ((bool) Tools::getValue('cache_up')) {
            if ($this->tabAccess['edit'] === '1') {
                $new_settings = $prev_settings = file_get_contents(_PS_ROOT_DIR_ . '/config/settings.inc.php');
                $cache_active = (bool) Tools::getValue('cache_active');
                if ($caching_system = Tools::getValue('caching_system')) {
                    $new_settings = preg_replace('/define\\(\'_PS_CACHING_SYSTEM_\', \'([a-z0-9=\\/+-_]*)\'\\);/Ui', 'define(\'_PS_CACHING_SYSTEM_\', \'' . $caching_system . '\');', $new_settings);
                } else {
                    $cache_active = false;
                    $this->errors[] = Tools::displayError('The caching system is missing.');
                }
                if ($cache_active) {
                    if ($caching_system == 'CacheMemcache' && !extension_loaded('memcache')) {
                        $this->errors[] = Tools::displayError('To use Memcached, you must install the Memcache PECL extension on your server.') . '
							<a href="http://www.php.net/manual/en/memcache.installation.php">http://www.php.net/manual/en/memcache.installation.php</a>';
                    } elseif ($caching_system == 'CacheApc' && !extension_loaded('apc')) {
                        $this->errors[] = Tools::displayError('To use APC cache, you must install the APC PECL extension on your server.') . '
							<a href="http://fr.php.net/manual/fr/apc.installation.php">http://fr.php.net/manual/fr/apc.installation.php</a>';
                    } elseif ($caching_system == 'CacheXcache' && !extension_loaded('xcache')) {
                        $this->errors[] = Tools::displayError('To use Xcache, you must install the Xcache extension on your server.') . '
							<a href="http://xcache.lighttpd.net">http://xcache.lighttpd.net</a>';
                    } elseif ($caching_system == 'CacheXcache' && !ini_get('xcache.var_size')) {
                        $this->errors[] = Tools::displayError('To use Xcache, you must configure "xcache.var_size" for the Xcache extension (recommended value 16M to 64M).') . '
							<a href="http://xcache.lighttpd.net/wiki/XcacheIni">http://xcache.lighttpd.net/wiki/XcacheIni</a>';
                    } elseif ($caching_system == 'CacheFs') {
                        if (!is_dir(_PS_CACHEFS_DIRECTORY_)) {
                            @mkdir(_PS_CACHEFS_DIRECTORY_, 0777, true);
                        } elseif (!is_writable(_PS_CACHEFS_DIRECTORY_)) {
                            $this->errors[] = sprintf(Tools::displayError('To use CacheFS, the directory %s must be writable.'), realpath(_PS_CACHEFS_DIRECTORY_));
                        }
                    }
                    if ($caching_system == 'CacheFs') {
                        if (!($depth = Tools::getValue('ps_cache_fs_directory_depth'))) {
                            $this->errors[] = Tools::displayError('Please set a directory depth.');
                        }
                        if (!count($this->errors)) {
                            CacheFs::deleteCacheDirectory();
                            CacheFs::createCacheDirectories((int) $depth);
                            Configuration::updateValue('PS_CACHEFS_DIRECTORY_DEPTH', (int) $depth);
                        }
                    } elseif ($caching_system == 'CacheMemcache' && !_PS_CACHE_ENABLED_ && _PS_CACHING_SYSTEM_ == 'CacheMemcache') {
                        Cache::getInstance()->flush();
                    }
                }
                if (!count($this->errors)) {
                    $new_settings = preg_replace('/define\\(\'_PS_CACHE_ENABLED_\', \'([01]?)\'\\);/Ui', 'define(\'_PS_CACHE_ENABLED_\', \'' . (int) $cache_active . '\');', $new_settings);
                    // If there is not settings file modification or if the backup and replacement of the settings file worked
                    if ($new_settings == $prev_settings || copy(_PS_ROOT_DIR_ . '/config/settings.inc.php', _PS_ROOT_DIR_ . '/config/settings.old.php') && (bool) file_put_contents(_PS_ROOT_DIR_ . '/config/settings.inc.php', $new_settings)) {
                        $redirectAdmin = true;
                    } else {
                        $this->errors[] = Tools::displayError('The settings file cannot be overwritten.');
                    }
                }
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to edit this.');
            }
        }
        if ((bool) Tools::getValue('empty_smarty_cache')) {
            $redirectAdmin = true;
            Tools::clearSmartyCache();
            Tools::clearXMLCache();
            Media::clearCache();
            PrestaShopAutoload::getInstance()->generateIndex();
        }
        if (Tools::isSubmit('submitAddconfiguration') && _PS_MODE_DEV_) {
            Configuration::updateGlobalValue('PS_DISABLE_NON_NATIVE_MODULE', (int) Tools::getValue('native_module'));
            Configuration::updateGlobalValue('PS_DISABLE_OVERRIDES', (int) Tools::getValue('overrides'));
            if (Tools::getValue('overrides')) {
                PrestaShopAutoload::getInstance()->_include_override_path = false;
            }
            PrestaShopAutoload::getInstance()->generateIndex();
        }
        if ($redirectAdmin && (!isset($this->errors) || !count($this->errors))) {
            Hook::exec('action' . get_class($this) . ucfirst($this->action) . 'After', array('controller' => $this, 'return' => ''));
            Tools::redirectAdmin(self::$currentIndex . '&token=' . Tools::getValue('token') . '&conf=4');
        }
    }
Exemple #5
0
 /**
  * Remove all methods in a module override from the override class
  *
  * @param string $classname
  * @return bool
  */
 public function removeOverride($classname)
 {
     $orig_path = $path = PrestaShopAutoload::getInstance()->getClassPath($classname . 'Core');
     if ($orig_path && !($file = PrestaShopAutoload::getInstance()->getClassPath($classname))) {
         return true;
     } else {
         if (!$orig_path && Module::getModuleIdByName($classname)) {
             $path = 'modules' . DIRECTORY_SEPARATOR . $classname . DIRECTORY_SEPARATOR . $classname . '.php';
         }
     }
     // Check if override file is writable
     if ($orig_path) {
         $override_path = _PS_ROOT_DIR_ . '/' . $file;
     } else {
         $override_path = _PS_OVERRIDE_DIR_ . $path;
     }
     if (!is_file($override_path) || !is_writable($override_path)) {
         return false;
     }
     file_put_contents($override_path, preg_replace('#(\\r|\\r\\n)#ism', "\n", file_get_contents($override_path)));
     if ($orig_path) {
         // Get a uniq id for the class, because you can override a class (or remove the override) twice in the same session and we need to avoid redeclaration
         do {
             $uniq = uniqid();
         } while (class_exists($classname . 'OverrideOriginal_remove', false));
         // Make a reflection of the override class and the module override class
         $override_file = file($override_path);
         eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+' . $classname . '\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?#i'), array(' ', 'class ' . $classname . 'OverrideOriginal_remove' . $uniq), implode('', $override_file)));
         $override_class = new ReflectionClass($classname . 'OverrideOriginal_remove' . $uniq);
         $module_file = file($this->getLocalPath() . 'override/' . $path);
         eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+' . $classname . '(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'), array(' ', 'class ' . $classname . 'Override_remove' . $uniq), implode('', $module_file)));
         $module_class = new ReflectionClass($classname . 'Override_remove' . $uniq);
         // Remove methods from override file
         foreach ($module_class->getMethods() as $method) {
             if (!$override_class->hasMethod($method->getName())) {
                 continue;
             }
             $method = $override_class->getMethod($method->getName());
             $length = $method->getEndLine() - $method->getStartLine() + 1;
             $module_method = $module_class->getMethod($method->getName());
             $module_length = $module_method->getEndLine() - $module_method->getStartLine() + 1;
             $override_file_orig = $override_file;
             $orig_content = preg_replace('/\\s/', '', implode('', array_splice($override_file, $method->getStartLine() - 1, $length, array_pad(array(), $length, '#--remove--#'))));
             $module_content = preg_replace('/\\s/', '', implode('', array_splice($module_file, $module_method->getStartLine() - 1, $length, array_pad(array(), $length, '#--remove--#'))));
             $replace = true;
             if (preg_match('/\\* module: (' . $this->name . ')/ism', $override_file[$method->getStartLine() - 5])) {
                 $override_file[$method->getStartLine() - 6] = $override_file[$method->getStartLine() - 5] = $override_file[$method->getStartLine() - 4] = $override_file[$method->getStartLine() - 3] = $override_file[$method->getStartLine() - 2] = '#--remove--#';
                 $replace = false;
             }
             if (md5($module_content) != md5($orig_content) && $replace) {
                 $override_file = $override_file_orig;
             }
         }
         // Remove properties from override file
         foreach ($module_class->getProperties() as $property) {
             if (!$override_class->hasProperty($property->getName())) {
                 continue;
             }
             // Replace the declaration line by #--remove--#
             foreach ($override_file as $line_number => &$line_content) {
                 if (preg_match('/(public|private|protected|const)\\s+(static\\s+)?(\\$)?' . $property->getName() . '/i', $line_content)) {
                     if (preg_match('/\\* module: (' . $this->name . ')/ism', $override_file[$line_number - 4])) {
                         $override_file[$line_number - 5] = $override_file[$line_number - 4] = $override_file[$line_number - 3] = $override_file[$line_number - 2] = $override_file[$line_number - 1] = '#--remove--#';
                     }
                     $line_content = '#--remove--#';
                     break;
                 }
             }
         }
         $count = count($override_file);
         for ($i = 0; $i < $count; ++$i) {
             if (preg_match('/(\\/\\/.*)/i', $override_file[$i])) {
                 $override_file[$i] = '#--remove--#';
             } elseif (preg_match('/(^\\s*\\/\\*)/i', $override_file[$i])) {
                 if (!preg_match('/(^\\s*\\* module:)/i', $override_file[$i + 1]) && !preg_match('/(^\\s*\\* date:)/i', $override_file[$i + 2]) && !preg_match('/(^\\s*\\* version:)/i', $override_file[$i + 3]) && !preg_match('/(^\\s*\\*\\/)/i', $override_file[$i + 4])) {
                     for (; $override_file[$i] && !preg_match('/(.*?\\*\\/)/i', $override_file[$i]); ++$i) {
                         $override_file[$i] = '#--remove--#';
                     }
                     $override_file[$i] = '#--remove--#';
                 }
             }
         }
         // Rewrite nice code
         $code = '';
         foreach ($override_file as $line) {
             if ($line == '#--remove--#') {
                 continue;
             }
             $code .= $line;
         }
         $to_delete = preg_match('/<\\?(?:php)?\\s+class\\s+' . $classname . '\\s+extends\\s+' . $classname . 'Core\\s*?[{]\\s*?[}]/ism', $code);
     }
     if (!isset($to_delete) || $to_delete) {
         unlink($override_path);
     } else {
         file_put_contents($override_path, $code);
     }
     // Re-generate the class index
     Tools::generateIndex();
     return true;
 }
 /**
  * This method generate the form for fields translations
  */
 public function initFormFields()
 {
     $name_var = $this->translations_informations[$this->type_selected]['var'];
     $GLOBALS[$name_var] = $this->fileExists();
     $missing_translations_fields = array();
     $class_array = array();
     $tabs_array = array();
     $count = 0;
     $files_by_directory = $this->getFileToParseByTypeTranslation();
     foreach ($files_by_directory['php'] as $dir => $files) {
         foreach ($files as $file) {
             $exclude_files = array('index.php', 'PrestaShopAutoload.php', 'StockManagerInterface.php', 'TaxManagerInterface.php', 'WebserviceOutputInterface.php', 'WebserviceSpecificManagementInterface.php');
             if (!preg_match('/\\.php$/', $file) || in_array($file, $exclude_files)) {
                 continue;
             }
             $class_name = substr($file, 0, -4);
             if (!class_exists($class_name, false) && !class_exists($class_name . 'Core', false)) {
                 PrestaShopAutoload::getInstance()->load($class_name);
             }
             if (!is_subclass_of($class_name . 'Core', 'ObjectModel')) {
                 continue;
             }
             $class_array[$class_name] = call_user_func(array($class_name, 'getValidationRules'), $class_name);
         }
     }
     foreach ($class_array as $prefix_key => $rules) {
         if (isset($rules['validate'])) {
             foreach ($rules['validate'] as $key => $value) {
                 if (isset($GLOBALS[$name_var][$prefix_key . '_' . md5($key)])) {
                     $tabs_array[$prefix_key][$key]['trad'] = html_entity_decode($GLOBALS[$name_var][$prefix_key . '_' . md5($key)], ENT_COMPAT, 'UTF-8');
                     $count++;
                 } else {
                     if (!isset($tabs_array[$prefix_key][$key]['trad'])) {
                         $tabs_array[$prefix_key][$key]['trad'] = '';
                         if (!isset($missing_translations_fields[$prefix_key])) {
                             $missing_translations_fields[$prefix_key] = 1;
                         } else {
                             $missing_translations_fields[$prefix_key]++;
                         }
                         $count++;
                     }
                 }
             }
         }
         if (isset($rules['validateLang'])) {
             foreach ($rules['validateLang'] as $key => $value) {
                 if (isset($GLOBALS[$name_var][$prefix_key . '_' . md5($key)])) {
                     $tabs_array[$prefix_key][$key]['trad'] = '';
                     if (array_key_exists($prefix_key . '_' . md5(addslashes($key)), $GLOBALS[$name_var])) {
                         $tabs_array[$prefix_key][$key]['trad'] = html_entity_decode($GLOBALS[$name_var][$prefix_key . '_' . md5(addslashes($key))], ENT_COMPAT, 'UTF-8');
                     }
                     $count++;
                 } else {
                     if (!isset($tabs_array[$prefix_key][$key]['trad'])) {
                         $tabs_array[$prefix_key][$key]['trad'] = '';
                         if (!isset($missing_translations_fields[$prefix_key])) {
                             $missing_translations_fields[$prefix_key] = 1;
                         } else {
                             $missing_translations_fields[$prefix_key]++;
                         }
                         $count++;
                     }
                 }
             }
         }
     }
     $this->tpl_view_vars = array_merge($this->tpl_view_vars, array('count' => $count, 'limit_warning' => $this->displayLimitPostWarning($count), 'tabsArray' => $tabs_array, 'cancel_url' => $this->context->link->getAdminLink('AdminTranslations'), 'missing_translations' => $missing_translations_fields));
     $this->initToolbar();
     $this->base_tpl_view = 'translation_form.tpl';
     return parent::renderView();
 }
Exemple #7
0
 public static final function execute()
 {
     $session = InstallSession::getInstance();
     if (!$session->last_step || $session->last_step == 'welcome') {
         PrestaShopAutoload::getInstance()->generateIndex();
     }
     if (Tools::getValue('compile_templates')) {
         require_once _PS_INSTALL_CONTROLLERS_PATH_ . 'http/smarty_compile.php';
         exit;
     }
     // Include all controllers
     foreach (self::$steps as $step) {
         if (!file_exists(_PS_INSTALL_CONTROLLERS_PATH_ . 'http/' . $step . '.php')) {
             throw new PrestashopInstallerException("Controller file 'http/{$step}.php' not found");
         }
         require_once _PS_INSTALL_CONTROLLERS_PATH_ . 'http/' . $step . '.php';
         $classname = 'InstallControllerHttp' . $step;
         self::$instances[$step] = new $classname($step);
     }
     if (!$session->last_step || !in_array($session->last_step, self::$steps)) {
         $session->last_step = self::$steps[0];
     }
     // Set timezone
     if ($session->shop_timezone) {
         @date_default_timezone_set($session->shop_timezone);
     }
     // Get current step (check first if step is changed, then take it from session)
     if (Tools::getValue('step')) {
         $current_step = Tools::getValue('step');
         $session->step = $current_step;
     } else {
         $current_step = isset($session->step) ? $session->step : self::$steps[0];
     }
     if (!in_array($current_step, self::$steps)) {
         $current_step = self::$steps[0];
     }
     // Validate all steps until current step. If a step is not valid, use it as current step.
     foreach (self::$steps as $check_step) {
         // Do not validate current step
         if ($check_step == $current_step) {
             break;
         }
         if (!self::$instances[$check_step]->validate()) {
             $current_step = $check_step;
             $session->step = $current_step;
             $session->last_step = $current_step;
             break;
         }
     }
     // Submit form to go to next step
     if (Tools::getValue('submitNext')) {
         self::$instances[$current_step]->processNextStep();
         // If current step is validated, let's go to next step
         if (self::$instances[$current_step]->validate()) {
             $current_step = self::$instances[$current_step]->findNextStep();
         }
         $session->step = $current_step;
         // Change last step
         if (self::getStepOffset($current_step) > self::getStepOffset($session->last_step)) {
             $session->last_step = $current_step;
         }
     } else {
         if (Tools::getValue('submitPrevious') && $current_step != self::$steps[0]) {
             $current_step = self::$instances[$current_step]->findPreviousStep($current_step);
             $session->step = $current_step;
         }
     }
     self::$instances[$current_step]->process();
     self::$instances[$current_step]->display();
 }
Exemple #8
0
 /**
  * Remove all methods in a module override from the override class
  *
  * @param string $classname
  * @return bool
  */
 public function removeOverride($classname)
 {
     $path = PrestaShopAutoload::getInstance()->getClassPath($classname . 'Core');
     if (!PrestaShopAutoload::getInstance()->getClassPath($classname)) {
         return true;
     }
     // Check if override file is writable
     $override_path = _PS_ROOT_DIR_ . '/' . PrestaShopAutoload::getInstance()->getClassPath($classname);
     if (!is_writable($override_path)) {
         return false;
     }
     // Get a uniq id for the class, because you can override a class (or remove the override) twice in the same session and we need to avoid redeclaration
     do {
         $uniq = uniqid();
     } while (class_exists($classname . 'OverrideOriginal_remove', false));
     // Make a reflection of the override class and the module override class
     $override_file = file($override_path);
     eval(preg_replace(array('#^\\s*<\\?php#', '#class\\s+' . $classname . '\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?#i'), array('', 'class ' . $classname . 'OverrideOriginal_remove' . $uniq), implode('', $override_file)));
     $override_class = new ReflectionClass($classname . 'OverrideOriginal_remove' . $uniq);
     $module_file = file($this->getLocalPath() . 'override/' . $path);
     eval(preg_replace(array('#^\\s*<\\?php#', '#class\\s+' . $classname . '(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'), array('', 'class ' . $classname . 'Override_remove' . $uniq), implode('', $module_file)));
     $module_class = new ReflectionClass($classname . 'Override_remove' . $uniq);
     // Remove methods from override file
     $override_file = file($override_path);
     foreach ($module_class->getMethods() as $method) {
         if (!$override_class->hasMethod($method->getName())) {
             continue;
         }
         $method = $override_class->getMethod($method->getName());
         $length = $method->getEndLine() - $method->getStartLine() + 1;
         $module_method = $module_class->getMethod($method->getName());
         $module_length = $module_method->getEndLine() - $module_method->getStartLine() + 1;
         $override_file_orig = $override_file;
         $orig_content = preg_replace("/\\s/", '', implode('', array_splice($override_file, $method->getStartLine() - 1, $length, array_pad(array(), $length, '#--remove--#'))));
         $module_content = preg_replace("/\\s/", '', implode('', array_splice($module_file, $module_method->getStartLine() - 1, $length, array_pad(array(), $length, '#--remove--#'))));
         if (md5($module_content) != md5($orig_content)) {
             $override_file = $override_file_orig;
         }
     }
     // Remove properties from override file
     foreach ($module_class->getProperties() as $property) {
         if (!$override_class->hasProperty($property->getName())) {
             continue;
         }
         // Remplacer la ligne de declaration par "remove"
         foreach ($override_file as $line_number => &$line_content) {
             if (preg_match('/(public|private|protected|const)\\s+(static\\s+)?(\\$)?' . $property->getName() . '/i', $line_content)) {
                 $line_content = '#--remove--#';
                 break;
             }
         }
     }
     // Rewrite nice code
     $code = '';
     foreach ($override_file as $line) {
         if ($line == '#--remove--#') {
             continue;
         }
         $code .= $line;
     }
     file_put_contents($override_path, $code);
     // Re-generate the class index
     PrestaShopAutoload::getInstance()->generateIndex();
     return true;
 }
 /**
  * Generate classes index
  */
 public function generateIndex()
 {
     $classes = array_merge($this->getClassesFromDir('classes/'), $this->getClassesFromDir('controllers/'));
     if ($this->_include_override_path) {
         $classes = array_merge($classes, $this->getClassesFromDir('override/classes/', defined('_PS_HOST_MODE_')), $this->getClassesFromDir('override/controllers/', defined('_PS_HOST_MODE_')));
     }
     ksort($classes);
     $content = '<?php return ' . var_export($classes, true) . '; ?>';
     // Write classes index on disc to cache it
     $filename = PrestaShopAutoload::getCacheFileIndex();
     @mkdir(_PS_CACHE_DIR_);
     if (!$this->dumpFile($filename, $content)) {
         Tools::error_log('Cannot write temporary file ' . $filename);
     }
     $this->index = $classes;
 }
    /**
     * 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;
    }
Exemple #11
0
 /**
  * Retrieve an array of the override in the module
  *
  * @return array|null
  */
 public function getOverrides()
 {
     if (!is_dir($this->getLocalPath() . 'override')) {
         return null;
     }
     $result = array();
     foreach (Tools::scandir($this->getLocalPath() . 'override', 'php', '', true) as $file) {
         $class = basename($file, '.php');
         if (PrestaShopAutoload::getInstance()->getClassPath($class . 'Core') || Module::getModuleIdByName($class)) {
             $result[] = $class;
         }
     }
     return $result;
 }
Exemple #12
0
 public function uninstall()
 {
     set_time_limit(0);
     $plugins = $this->plugins();
     foreach ($plugins as $name => $api_version) {
         if (Module::isInstalled($name)) {
             $this->_errors[] = sprintf($this->l('Please uninstall the "%s" module.'), Module::getModuleName($name));
         }
     }
     if ($this->_errors) {
         return false;
     }
     $setup = $this->setupInstance();
     $setup->cleanupOverriddenFiles();
     if (!parent::uninstall() || !$setup->uninstallAdminTab('AdminPproperties')) {
         return false;
     }
     $setup->uninstall();
     Configuration::deleteByName('PP_INTEGRATION');
     Configuration::deleteByName('PP_INTEGRATION_CHECK');
     Configuration::deleteByName('PP_INTEGRATION_EXTRA_MODULES');
     Configuration::deleteByName('PP_INFO_CONTENT');
     Configuration::deleteByName('PP_INFO_CHECK_TIME');
     Configuration::deleteByName('PP_VERSION');
     Configuration::updateValue('PP_LAST_VERSION', $this->version);
     PrestaShopAutoload::getInstance()->generateIndex();
     return true;
 }
 public function removeOverride($classname)
 {
     /*
      * Legal 0.0.1 | 20140324
      * Die Do-While schleife benötigt uniqid als Argument
      * Bei löschen von overrides müssen auch Klassenkostanten 'const' entfernt werden
      */
     $path = PrestaShopAutoload::getInstance()->getClassPath($classname . 'Core');
     if (!PrestaShopAutoload::getInstance()->getClassPath($classname)) {
         return true;
     }
     // Check if override file is writable
     $override_path = _PS_ROOT_DIR_ . '/' . PrestaShopAutoload::getInstance()->getClassPath($classname);
     if (!is_writable($override_path)) {
         return false;
     }
     // Get a uniq id for the class, because you can override a class (or remove the override) twice in the same session and we need to avoid redeclaration
     do {
         $uniq = uniqid();
     } while (class_exists($classname . 'OverrideOriginal_remove' . $uniq, false));
     // Make a reflection of the override class and the module override class
     $override_file = file($override_path);
     eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+' . $classname . '\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?#i'), array(' ', 'class ' . $classname . 'OverrideOriginal_remove' . $uniq), implode('', $override_file)));
     $override_class = new ReflectionClass($classname . 'OverrideOriginal_remove' . $uniq);
     $module_file = file($this->getLocalPath() . 'override/' . $path);
     eval(preg_replace(array('#^\\s*<\\?(?:php)?#', '#class\\s+' . $classname . '(\\s+extends\\s+([a-z0-9_]+)(\\s+implements\\s+([a-z0-9_]+))?)?#i'), array(' ', 'class ' . $classname . 'Override_remove' . $uniq), implode('', $module_file)));
     $module_class = new ReflectionClass($classname . 'Override_remove' . $uniq);
     // Remove methods from override file
     $override_file = file($override_path);
     foreach ($module_class->getMethods() as $method) {
         if (!$override_class->hasMethod($method->getName())) {
             continue;
         }
         $method = $override_class->getMethod($method->getName());
         $length = $method->getEndLine() - $method->getStartLine() + 1;
         $module_method = $module_class->getMethod($method->getName());
         $module_length = $module_method->getEndLine() - $module_method->getStartLine() + 1;
         $override_file_orig = $override_file;
         $orig_content = preg_replace("/\\s/", '', implode('', array_splice($override_file, $method->getStartLine() - 1, $length, array_pad(array(), $length, '#--remove--#'))));
         $module_content = preg_replace("/\\s/", '', implode('', array_splice($module_file, $module_method->getStartLine() - 1, $module_length, array_pad(array(), $module_length, '#--remove--#'))));
         $replace = true;
         if (preg_match('/\\* module: (' . $this->name . ')/ism', $override_file[$method->getStartLine() - 5])) {
             $override_file[$method->getStartLine() - 7] = $override_file[$method->getStartLine() - 6] = $override_file[$method->getStartLine() - 5] = $override_file[$method->getStartLine() - 4] = $override_file[$method->getStartLine() - 3] = $override_file[$method->getStartLine() - 2] = '#--remove--#';
             $replace = false;
         }
         if (md5($module_content) != md5($orig_content) && $replace) {
             $override_file = $override_file_orig;
         }
     }
     // Remove properties from override file
     foreach ($module_class->getProperties() as $property) {
         if (!$override_class->hasProperty($property->getName())) {
             continue;
         }
         // Remplacer la ligne de declaration par "remove"
         foreach ($override_file as $line_number => &$line_content) {
             if (preg_match('/(public|private|protected)\\s+(static\\s+)?(\\$)?' . $property->getName() . '/i', $line_content)) {
                 if (preg_match('/\\* module: (' . $this->name . ')/ism', $override_file[$line_number - 5])) {
                     $override_file[$line_number - 7] = $override_file[$line_number - 6] = $override_file[$line_number - 5] = $override_file[$line_number - 4] = $override_file[$line_number - 3] = $override_file[$line_number - 2] = '#--remove--#';
                 }
                 $line_content = '#--remove--#';
                 break;
             }
         }
     }
     // Remove constants from override file
     foreach ($module_class->getConstants() as $constant => $value) {
         if (!$override_class->hasConstant($constant)) {
             continue;
         }
         // Remplacer la ligne de declaration par "remove"
         foreach ($override_file as $line_number => &$line_content) {
             if (preg_match('/(const)\\s+' . $constant . '/i', $line_content)) {
                 $line_content = '#--remove--#';
                 break;
             }
         }
     }
     // Rewrite nice code
     $code = '';
     foreach ($override_file as $line) {
         if ($line == '#--remove--#') {
             continue;
         }
         $code .= $line;
     }
     $to_delete = preg_match('/<\\?(?:php)?\\s+class\\s+' . $classname . '\\s+extends\\s+' . $classname . 'Core\\s*?[{]\\s*?[}]/ism', $code);
     if ($to_delete) {
         unlink($override_path);
     } else {
         file_put_contents($override_path, $code);
     }
     // Re-generate the class index
     Tools::generateIndex();
     return true;
 }
 public function testLoad()
 {
     PrestaShopAutoload::getInstance()->load('RequestSql');
     $this->assertTrue(class_exists('RequestSqlCore', false));
     $this->assertTrue(class_exists('RequestSql', false));
 }
Exemple #15
0
 public static function generateIndex()
 {
     if (defined('_PS_CREATION_DATE_') && _PS_CREATION_DATE_ !== null && Configuration::get('PS_DISABLE_OVERRIDES')) {
         PrestaShopAutoload::getInstance()->_include_override_path = false;
     }
     PrestaShopAutoload::getInstance()->generateIndex();
 }