public static function createCacheDirectories($level_depth, $directory = false)
 {
     if (!$directory) {
         $directory = CACHEFS_DIR;
     }
     $chars = '0123456789abcdef';
     for ($i = 0, $length = strlen($chars); $i < $length; $i++) {
         $new_dir = $directory . $chars[$i] . '/';
         if (mkdir($new_dir)) {
             if (chmod($new_dir, 0777)) {
                 if ($level_depth - 1 > 0) {
                     CacheFs::createCacheDirectories($level_depth - 1, $new_dir);
                 }
             }
         }
     }
 }
    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');
        }
    }
Example #3
0
    $tools_dir = rtrim(_PS_INSTALL_PATH_, '\\/') . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'tools' . DIRECTORY_SEPARATOR;
    $arrayToClean = array($tools_dir . 'smarty' . DIRECTORY_SEPARATOR . 'cache', $tools_dir . 'smarty' . DIRECTORY_SEPARATOR . 'compile', $tools_dir . 'smarty_v2' . DIRECTORY_SEPARATOR . 'cache', $tools_dir . 'smarty_v2' . DIRECTORY_SEPARATOR . 'compile');
    foreach ($arrayToClean as $dir) {
        if (file_exists($dir)) {
            foreach (scandir($dir) as $file) {
                if ($file[0] != '.' and $file != 'index.php' and $file != '.htaccess') {
                    unlink($dir . DIRECTORY_SEPARATOR . $file);
                }
            }
        }
    }
    // delete cache filesystem if activated
    $depth = Configuration::get('PS_CACHEFS_DIRECTORY_DEPTH');
    if (defined('_PS_CACHE_ENABLED_') && _PS_CACHE_ENABLED_ && $depth) {
        CacheFs::deleteCacheDirectory();
        CacheFs::createCacheDirectories((int) $depth);
    }
}
$result = '<?xml version="1.0" encoding="UTF-8"?>';
if (empty($fail_result)) {
    Configuration::updateValue('PS_HIDE_OPTIMIZATION_TIPS', 0);
    Configuration::updateValue('PS_NEED_REBUILD_INDEX', 1);
    Configuration::updateValue('PS_VERSION_DB', _PS_INSTALL_VERSION_);
    $result .= $warningExist ? '<action result="fail" error="34">' . "\n" : '<action result="ok" error="">' . "\n";
    $result .= $requests;
    $result .= '</action>' . "\n";
} else {
    $result = $fail_result;
}
if (!isset($return_type)) {
    $return_type = 'xml';
    public function postProcess()
    {
        if (Tools::isSubmit('submitAddServer')) {
            if ($this->tabAccess['add'] === '1') {
                if (!Tools::getValue('memcachedIp')) {
                    $this->errors[] = Tools::displayError('Memcached IP is missing');
                }
                if (!Tools::getValue('memcachedPort')) {
                    $this->errors[] = Tools::displayError('Memcached port is missing');
                }
                if (!Tools::getValue('memcachedWeight')) {
                    $this->errors[] = Tools::displayError('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('Cannot add Memcached server');
                    }
                }
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to add here.');
            }
        }
        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('Error in deleting Memcached server');
                }
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to delete here.');
            }
        }
        $redirecAdmin = 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));
                $redirecAdmin = true;
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to edit here.');
            }
        }
        if ((bool) Tools::getValue('features_detachables_up')) {
            if ($this->tabAccess['edit'] === '1') {
                if (!Combination::isCurrentlyUsed()) {
                    Configuration::updateValue('PS_COMBINATION_FEATURE_ACTIVE', Tools::getValue('combination'));
                }
                Configuration::updateValue('PS_FEATURE_FEATURE_ACTIVE', Tools::getValue('feature'));
                $redirecAdmin = true;
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to edit here.');
            }
        }
        if ((bool) Tools::getValue('ccc_up')) {
            if ($this->tabAccess['edit'] === '1') {
                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_HIGH_HTML_THEME_COMPRESSION', (int) Tools::getValue('PS_HIGH_HTML_THEME_COMPRESSION')) || !Configuration::updateValue('PS_HTACCESS_CACHE_CONTROL', (int) Tools::getValue('PS_HTACCESS_CACHE_CONTROL'))) {
                    $this->errors[] = Tools::displayError('Unknown error.');
                } else {
                    $redirecAdmin = true;
                    if (Configuration::get('PS_HTACCESS_CACHE_CONTROL')) {
                        Tools::generateHtaccess();
                    }
                }
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to edit here.');
            }
        }
        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_');
                    rewriteSettingsFile($base_urls, null, null);
                    unset($this->_fieldsGeneral['_MEDIA_SERVER_1_']);
                    unset($this->_fieldsGeneral['_MEDIA_SERVER_2_']);
                    unset($this->_fieldsGeneral['_MEDIA_SERVER_3_']);
                    $redirecAdmin = true;
                }
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to edit here.');
            }
        }
        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');
                $settings = file_get_contents(dirname(__FILE__) . '/../../config/settings.inc.php');
                if ($algo) {
                    if (!function_exists('mcrypt_encrypt')) {
                        $this->errors[] = Tools::displayError('PHP "Mcrypt" extension is not activated on this server.');
                    } else {
                        if (!strstr($settings, '_RIJNDAEL_KEY_')) {
                            $key_size = mcrypt_get_key_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
                            $key = Tools::passwdGen($key_size);
                            $settings = preg_replace('/define\\(\'_COOKIE_KEY_\', \'([a-z0-9=\\/+-_]+)\'\\);/i', 'define(\'_COOKIE_KEY_\', \'\\1\');' . "\n" . 'define(\'_RIJNDAEL_KEY_\', \'' . $key . '\');', $settings);
                        }
                        if (!strstr($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));
                            $settings = preg_replace('/define\\(\'_COOKIE_IV_\', \'([a-z0-9=\\/+-_]+)\'\\);/i', 'define(\'_COOKIE_IV_\', \'\\1\');' . "\n" . 'define(\'_RIJNDAEL_IV_\', \'' . $iv . '\');', $settings);
                        }
                    }
                }
                if (!count($this->errors)) {
                    if (file_put_contents(dirname(__FILE__) . '/../../config/settings.inc.php', $settings)) {
                        Configuration::updateValue('PS_CIPHER_ALGORITHM', $algo);
                        $redirecAdmin = true;
                    } else {
                        $this->errors[] = Tools::displayError('Cannot overwrite settings file.');
                    }
                }
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to edit here.');
            }
        }
        if ((bool) Tools::getValue('cache_up')) {
            if ($this->tabAccess['edit'] === '1') {
                $settings = file_get_contents(dirname(__FILE__) . '/../../config/settings.inc.php');
                if (!Tools::getValue('active')) {
                    $cache_active = 0;
                } else {
                    $cache_active = 1;
                }
                if (!($caching_system = Tools::getValue('caching_system'))) {
                    $this->errors[] = Tools::displayError('Caching system is missing');
                } else {
                    $settings = preg_replace('/define\\(\'_PS_CACHING_SYSTEM_\', \'([a-z0-9=\\/+-_]+)\'\\);/Ui', 'define(\'_PS_CACHING_SYSTEM_\', \'' . $caching_system . '\');', $settings);
                }
                if ($cache_active && $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>';
                } else {
                    if ($cache_active && $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>';
                    } else {
                        if ($cache_active && $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>';
                        } else {
                            if ($cache_active && $caching_system == 'CacheFs' && !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' && $cache_active) {
                    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);
                    }
                } else {
                    if ($caching_system == 'MCached' && $cache_active && !_PS_CACHE_ENABLED_ && _PS_CACHING_SYSTEM_ == 'MCached') {
                        Cache::getInstance()->flush();
                    }
                }
                if (!count($this->errors)) {
                    $settings = preg_replace('/define\\(\'_PS_CACHE_ENABLED_\', \'([0-9])\'\\);/Ui', 'define(\'_PS_CACHE_ENABLED_\', \'' . (int) $cache_active . '\');', $settings);
                    if (file_put_contents(dirname(__FILE__) . '/../../config/settings.inc.php', $settings)) {
                        $redirecAdmin = true;
                    } else {
                        $this->errors[] = Tools::displayError('Cannot overwrite settings file.');
                    }
                }
            } else {
                $this->errors[] = Tools::displayError('You do not have permission to edit here.');
            }
        }
        if ($redirecAdmin) {
            Tools::redirectAdmin(self::$currentIndex . '&token=' . Tools::getValue('token') . '&conf=4');
        } else {
            return parent::postProcess();
        }
    }
Example #5
0
 public static function enable_cache($cache, $cacheFSDepth = 1)
 {
     if (!Validate::isInt($cacheFSDepth)) {
         echo "Error, cacheFSDepth must be integer\n";
         return false;
     }
     if ($cacheFSDepth <= 0) {
         echo "Error, depth must be superior to 0\n";
         return false;
     }
     $new_settings = $prev_settings = file_get_contents(_PS_ROOT_DIR_ . '/config/settings.inc.php');
     $new_settings = preg_replace('/define\\(\'_PS_CACHE_ENABLED_\', \'([01]?)\'\\);/Ui', 'define(\'_PS_CACHE_ENABLED_\', \'1\');', $new_settings);
     if ($cache = 'default') {
         $cache = _PS_CACHING_SYSTEM_;
     }
     echo "Enabling {$cache} cache system\n";
     switch ($cache) {
         case 'CacheMemcache':
             if (!extension_loaded('memcache')) {
                 echo "Error: PHP memcache PECL extension is not loaded\n";
                 return false;
             }
             break;
         case 'CacheApc':
             if (!extension_loaded('apc')) {
                 echo "Error: PHP APC PECL extension is not loaded\n";
                 return false;
             }
             break;
         case 'CacheXcache':
             if (!extension_loaded('xcache')) {
                 echo "Error: PHP Xcache extension not loaded\n";
                 return false;
             }
             break;
         case 'CacheFs':
             if (!is_dir(_PS_CACHEFS_DIRECTORY_)) {
                 if (!@mkdir(_PS_CACHE_FS_DIR_, 0750, true)) {
                     echo "Error, could not create cache directory\n";
                     return false;
                 }
             } elseif (!is_writeable(_PS_CACHEFS_DIRECTORY_)) {
                 echo "Error: Cache directory is not writeable\n";
                 return false;
             }
             CacheFs::deleteCacheDirectory();
             CacheFs::createCacheDirectories($cacheFSDepth);
             Configuration::updateValue('PS_CACHEFS_DIRECTORY_DEPTH', $cacheFSDepth);
             break;
         default:
             echo "Unknown cache type: {$cache}\n";
             return false;
     }
     $new_settings = preg_replace('/define\\(\'_PS_CACHING_SYSTEM_\', \'([a-z0-9=\\/+-_]*)\'\\);/Ui', 'define(\'_PS_CACHING_SYSTEM_\', \'' . $cache . '\');', $new_settings);
     if ($new_settings == $prev_settings) {
         echo "Cache {$cache} is already in use\n";
         return true;
     }
     if (!@copy(_PS_ROOT_DIR_ . '/config/settings.inc.php', _PS_ROOT_DIR_ . '/config/settings.old.php')) {
         echo "Error, could not backup config file\n";
         return false;
     }
     if (file_put_contents(_PS_ROOT_DIR_ . '/config/settings.inc.php', $new_settings)) {
         echo "cache {$cache} successfully activated\n";
         return true;
     } else {
         echo "Could not update config file\n";
         return false;
     }
 }
    public function postProcess()
    {
        /* PrestaShop demo mode */
        if (_PS_MODE_DEMO_) {
            $this->errors[] = $this->trans('This functionality has been disabled.', array(), 'Admin.Notifications.Error');
            return;
        }
        Hook::exec('action' . get_class($this) . ucfirst($this->action) . 'Before', array('controller' => $this));
        if (Tools::isSubmit('submitAddServer')) {
            if ($this->access('add')) {
                if (!Tools::getValue('memcachedIp')) {
                    $this->errors[] = $this->trans('The Memcached IP is missing.', array(), 'Admin.Parameters.Notification');
                }
                if (!Tools::getValue('memcachedPort')) {
                    $this->errors[] = $this->trans('The Memcached port is missing.', array(), 'Admin.Parameters.Notification');
                }
                if (!Tools::getValue('memcachedWeight')) {
                    $this->errors[] = $this->trans('The Memcached weight is missing.', array(), 'Admin.Parameters.Notification');
                }
                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[] = $this->trans('The Memcached server cannot be added.', array(), 'Admin.Parameters.Notification');
                    }
                }
            } else {
                $this->errors[] = $this->trans('You do not have permission to add this.', array(), 'Admin.Notifications.Error');
            }
        }
        if (Tools::getValue('deleteMemcachedServer')) {
            if ($this->access('add')) {
                if (CacheMemcache::deleteServer((int) Tools::getValue('deleteMemcachedServer'))) {
                    Tools::redirectAdmin(self::$currentIndex . '&token=' . Tools::getValue('token') . '&conf=4');
                } else {
                    $this->errors[] = $this->trans('There was an error when attempting to delete the Memcached server.', array(), 'Admin.Parameters.Notification');
                }
            } else {
                $this->errors[] = $this->trans('You do not have permission to delete this.', array(), 'Admin.Notifications.Error');
            }
        }
        $redirectAdmin = false;
        if ((bool) Tools::getValue('smarty_up')) {
            if ($this->access('edit')) {
                Configuration::updateValue('PS_SMARTY_FORCE_COMPILE', Tools::getValue('smarty_force_compile', _PS_SMARTY_NO_COMPILE_));
                if (Configuration::get('PS_SMARTY_CACHE') != Tools::getValue('smarty_cache')) {
                    Tools::clearSmartyCache();
                }
                Configuration::updateValue('PS_SMARTY_CACHE', Tools::getValue('smarty_cache', 0));
                Configuration::updateValue('PS_SMARTY_CLEAR_CACHE', Tools::getValue('smarty_clear_cache'));
                Configuration::updateValue('PS_SMARTY_LOCAL', Tools::getValue('smarty_local', 0));
                $redirectAdmin = true;
            } else {
                $this->errors[] = $this->trans('You do not have permission to edit this.', array(), 'Admin.Notifications.Error');
            }
        }
        if ((bool) Tools::getValue('features_detachables_up')) {
            if ($this->access('edit')) {
                if (Tools::isSubmit('combination')) {
                    if ((!Tools::getValue('combination') && Combination::isCurrentlyUsed()) === false) {
                        Configuration::updateValue('PS_COMBINATION_FEATURE_ACTIVE', (bool) Tools::getValue('combination'));
                    }
                }
                if (Tools::isSubmit('customer_group')) {
                    if ((!Tools::getValue('customer_group') && Group::isCurrentlyUsed()) === false) {
                        Configuration::updateValue('PS_GROUP_FEATURE_ACTIVE', (bool) Tools::getValue('customer_group'));
                    }
                }
                Configuration::updateValue('PS_FEATURE_FEATURE_ACTIVE', (bool) Tools::getValue('feature'));
                $redirectAdmin = true;
            } else {
                $this->errors[] = $this->trans('You do not have permission to edit this.', array(), 'Admin.Notifications.Error');
            }
        }
        if ((bool) Tools::getValue('ccc_up')) {
            if ($this->access('edit')) {
                $theme_cache_directory = _PS_ALL_THEMES_DIR_ . $this->context->shop->theme_directory . '/cache/';
                @mkdir($theme_cache_directory, 0777, true);
                if (((bool) Tools::getValue('PS_CSS_THEME_CACHE') || (bool) Tools::getValue('PS_JS_THEME_CACHE')) && !is_writable($theme_cache_directory)) {
                    $this->errors[] = $this->trans('To use Smart Cache, the directory %directorypath% must be writable.', array('%directorypath%' => realpath($theme_cache_directory)), 'Admin.Parameters.Notification');
                }
                if ($tmp = (int) Tools::getValue('PS_CSS_THEME_CACHE')) {
                    $version = (int) Configuration::get('PS_CCCCSS_VERSION');
                    if (Configuration::get('PS_CSS_THEME_CACHE') != $tmp) {
                        Configuration::updateValue('PS_CCCCSS_VERSION', ++$version);
                    }
                }
                if ($tmp = (int) Tools::getValue('PS_JS_THEME_CACHE')) {
                    $version = (int) Configuration::get('PS_CCCJS_VERSION');
                    if (Configuration::get('PS_JS_THEME_CACHE') != $tmp) {
                        Configuration::updateValue('PS_CCCJS_VERSION', ++$version);
                    }
                }
                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_JS_DEFER', (int) Tools::getValue('PS_JS_DEFER')) || !Configuration::updateValue('PS_HTACCESS_CACHE_CONTROL', (int) Tools::getValue('PS_HTACCESS_CACHE_CONTROL'))) {
                    $this->errors[] = $this->trans('Unknown error.', array(), 'Admin.Notifications.Error');
                } else {
                    $redirectAdmin = true;
                    if (Configuration::get('PS_HTACCESS_CACHE_CONTROL')) {
                        if (is_writable(_PS_ROOT_DIR_ . '/.htaccess')) {
                            Tools::generateHtaccess();
                        } else {
                            $message = $this->l('Before being able to use this tool, you need to:');
                            $message .= '<br />- ' . $this->l('Create a blank .htaccess in your root directory.');
                            $message .= '<br />- ' . $this->l('Give it write permissions (CHMOD 666 on Unix system).');
                            $this->errors[] = Tools::displayError($message, false);
                            Configuration::updateValue('PS_HTACCESS_CACHE_CONTROL', false);
                        }
                    }
                }
            } else {
                $this->errors[] = $this->trans('You do not have permission to edit this.', array(), 'Admin.Notifications.Error');
            }
        }
        if ((bool) Tools::getValue('media_server_up') && !defined('_PS_HOST_MODE_')) {
            if ($this->access('edit')) {
                if (Tools::getValue('_MEDIA_SERVER_1_') != null && !Validate::isFileName(Tools::getValue('_MEDIA_SERVER_1_'))) {
                    $this->errors[] = $this->trans('Media server #1 is invalid', array(), 'Admin.Parameters.Notification');
                }
                if (Tools::getValue('_MEDIA_SERVER_2_') != null && !Validate::isFileName(Tools::getValue('_MEDIA_SERVER_2_'))) {
                    $this->errors[] = $this->trans('Media server #2 is invalid', array(), 'Admin.Parameters.Notification');
                }
                if (Tools::getValue('_MEDIA_SERVER_3_') != null && !Validate::isFileName(Tools::getValue('_MEDIA_SERVER_3_'))) {
                    $this->errors[] = $this->trans('Media server #3 is invalid', array(), 'Admin.Parameters.Notification');
                }
                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);
                    Configuration::updateValue('PS_MEDIA_SERVER_1', Tools::getValue('_MEDIA_SERVER_1_'));
                    Configuration::updateValue('PS_MEDIA_SERVER_2', Tools::getValue('_MEDIA_SERVER_2_'));
                    Configuration::updateValue('PS_MEDIA_SERVER_3', Tools::getValue('_MEDIA_SERVER_3_'));
                    Tools::clearSmartyCache();
                    Media::clearCache();
                    if (is_writable(_PS_ROOT_DIR_ . '/.htaccess')) {
                        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 {
                        $message = $this->l('Before being able to use this tool, you need to:');
                        $message .= '<br />- ' . $this->l('Create a blank .htaccess in your root directory.');
                        $message .= '<br />- ' . $this->l('Give it write permissions (CHMOD 666 on Unix system).');
                        $this->errors[] = Tools::displayError($message, false);
                        Configuration::updateValue('PS_HTACCESS_CACHE_CONTROL', false);
                    }
                }
            } else {
                $this->errors[] = $this->trans('You do not have permission to edit this.', array(), 'Admin.Notifications.Error');
            }
        }
        if ((bool) Tools::getValue('cache_up')) {
            if ($this->access('edit')) {
                $config = Yaml::parse(_PS_ROOT_DIR_ . '/app/config/parameters.yml');
                $cache_active = (bool) Tools::getValue('cache_active');
                if ($caching_system = preg_replace('[^a-zA-Z0-9]', '', Tools::getValue('caching_system'))) {
                    $config['parameters']['ps_caching'] = $caching_system;
                } else {
                    $cache_active = false;
                    $this->errors[] = $this->trans('The caching system is missing.', array(), 'Admin.Parameters.Notification');
                }
                if ($cache_active) {
                    if ($caching_system == 'CacheMemcache' && !extension_loaded('memcache')) {
                        $this->errors[] = $this->trans('To use Memcached, you must install the Memcache PECL extension on your server.', array(), 'Admin.Parameters.Notification') . '
							<a href="http://www.php.net/manual/en/memcache.installation.php">http://www.php.net/manual/en/memcache.installation.php</a>';
                    } elseif ($caching_system == 'CacheMemcached' && !extension_loaded('memcached')) {
                        $this->errors[] = $this->trans('To use Memcached, you must install the Memcached PECL extension on your server.', array(), 'Admin.Parameters.Notification') . '
							<a href="http://www.php.net/manual/en/memcached.installation.php">http://www.php.net/manual/en/memcached.installation.php</a>';
                    } elseif ($caching_system == 'CacheApc' && !extension_loaded('apc') && !extension_loaded('apcu')) {
                        $this->errors[] = $this->trans('To use APC cache, you must install the APC PECL extension on your server.', array(), 'Admin.Parameters.Notification') . '
							<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[] = $this->trans('To use Xcache, you must install the Xcache extension on your server.', array(), 'Admin.Parameters.Notification') . '
							<a href="http://xcache.lighttpd.net">http://xcache.lighttpd.net</a>';
                    } elseif ($caching_system == 'CacheXcache' && !ini_get('xcache.var_size')) {
                        $this->errors[] = $this->trans('To use Xcache, you must configure "xcache.var_size" for the Xcache extension (recommended value 16M to 64M).', array(), 'Admin.Parameters.Notification') . '
							<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[] = $this->trans('To use CacheFS, the directory %directorypath% must be writable.', array('%directorypath%' => realpath(_PS_CACHEFS_DIRECTORY_)), 'Admin.Parameters.Notification');
                        }
                    }
                    if ($caching_system == 'CacheFs') {
                        if (!($depth = Tools::getValue('ps_cache_fs_directory_depth'))) {
                            $this->errors[] = $this->trans('Please set a directory depth.', array(), 'Admin.Parameters.Notification');
                        }
                        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();
                    } elseif ($caching_system == 'CacheMemcached' && !_PS_CACHE_ENABLED_ && _PS_CACHING_SYSTEM_ == 'CacheMemcached') {
                        Cache::getInstance()->flush();
                    }
                }
                if (!count($this->errors)) {
                    $config['parameters']['ps_cache_enable'] = $cache_active;
                    // If there is not settings file modification or if the backup and replacement of the settings file worked
                    if (file_put_contents(_PS_ROOT_DIR_ . '/app/config/parameters.yml', Yaml::dump($config))) {
                        if (function_exists('opcache_invalidate')) {
                            opcache_invalidate(_PS_ROOT_DIR_ . '/app/config/parameters.yml');
                        }
                        $redirectAdmin = true;
                    } else {
                        $this->errors[] = $this->trans('The settings file cannot be overwritten.', array(), 'Admin.Parameters.Notification');
                    }
                }
            } else {
                $this->errors[] = $this->trans('You do not have permission to edit this.', array(), 'Admin.Notifications.Error');
            }
        }
        if ((bool) Tools::getValue('empty_smarty_cache')) {
            $redirectAdmin = true;
            Tools::clearSmartyCache();
            Tools::clearXMLCache();
            Media::clearCache();
            Tools::generateIndex();
        }
        if ((bool) Tools::getValue('empty_sf2_cache')) {
            $redirectAdmin = true;
            $sf2Refresh = new \PrestaShopBundle\Service\Cache\Refresh();
            $sf2Refresh->addCacheClear(_PS_MODE_DEV_ ? 'dev' : 'prod');
            $sf2Refresh->execute();
        }
        if (Tools::isSubmit('submitAddconfiguration')) {
            Configuration::updateGlobalValue('PS_DISABLE_NON_NATIVE_MODULE', (int) Tools::getValue('native_module'));
            Configuration::updateGlobalValue('PS_DISABLE_OVERRIDES', (int) Tools::getValue('overrides'));
            if (Tools::isSubmit('debug_mode') && (bool) Tools::getValue('debug_mode')) {
                $debug_mode_status = $this->enableDebugMode();
            } else {
                $debug_mode_status = $this->disableDebugMode();
            }
            if (!empty($debug_mode_status)) {
                switch ($debug_mode_status) {
                    case self::DEBUG_MODE_ERROR_COULD_NOT_BACKUP:
                        $this->errors[] = Tools::displayError(sprintf($this->l('Error: could not write to file. Make sure that the correct permissions are set on the file %s'), _PS_ROOT_DIR_ . '/config/defines.old.php'));
                        break;
                    case self::DEBUG_MODE_ERROR_NO_DEFINITION_FOUND:
                        $this->errors[] = Tools::displayError(sprintf($this->l('Error: could not find whether debug mode is enabled. Make sure that the correct permissions are set on the file %s'), _PS_ROOT_DIR_ . '/config/defines.inc.php'));
                        break;
                    case self::DEBUG_MODE_ERROR_NO_WRITE_ACCESS:
                        $this->errors[] = Tools::displayError(sprintf($this->l('Error: could not write to file. Make sure that the correct permissions are set on the file %s'), _PS_ROOT_DIR_ . '/config/defines.inc.php'));
                        break;
                    case self::DEBUG_MODE_ERROR_NO_WRITE_ACCESS_CUSTOM:
                        $this->errors[] = Tools::displayError(sprintf($this->l('Error: could not write to file. Make sure that the correct permissions are set on the file %s'), _PS_ROOT_DIR_ . '/config/defines_custom.inc.php'));
                        break;
                    case self::DEBUG_MODE_ERROR_NO_READ_ACCESS:
                        $this->errors[] = Tools::displayError(sprintf($this->l('Error: could not read file. Make sure that the correct permissions are set on the file %s'), _PS_ROOT_DIR_ . '/config/defines.inc.php'));
                        break;
                    default:
                        break;
                }
            }
            Tools::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');
        }
    }
    /**
     * 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' and (substr($memory_limit, -1) == 'M' and substr($memory_limit, 0, -1) < 128 or 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']) || $_SERVER['REQUEST_URI'] == '') {
            $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'];
        }
        if ($tmp = strpos($_SERVER['REQUEST_URI'], '?')) {
            $_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'], 0, $tmp);
        }
        $_SERVER['REQUEST_URI'] = str_replace('//', '/', $_SERVER['REQUEST_URI']);
        define('INSTALL_VERSION', $this->install_version);
        define('INSTALL_PATH', realpath($this->latestRootDir . DIRECTORY_SEPARATOR . 'install'));
        define('PS_INSTALLATION_IN_PROGRESS', true);
        define('SETTINGS_FILE', $this->prodRootDir . '/config/settings.inc.php');
        define('DEFINES_FILE', $this->prodRootDir . '/config/defines.inc.php');
        define('INSTALLER__PS_BASE_URI', substr($_SERVER['REQUEST_URI'], 0, -1 * (strlen($_SERVER['REQUEST_URI']) - strrpos($_SERVER['REQUEST_URI'], '/')) - strlen(substr(dirname($_SERVER['REQUEST_URI']), strrpos(dirname($_SERVER['REQUEST_URI']), '/') + 1))));
        //	define('INSTALLER__PS_BASE_URI_ABSOLUTE', 'http://'.ToolsInstall::getHttpHost(false, true).INSTALLER__PS_BASE_URI);
        // XML Header
        // header('Content-Type: text/xml');
        $filePrefix = 'PREFIX_';
        $engineType = 'ENGINE_TYPE';
        $mysqlEngine = defined('_MYSQL_ENGINE_') ? _MYSQL_ENGINE_ : 'MyISAM';
        if (function_exists('date_default_timezone_set')) {
            date_default_timezone_set('Europe/Paris');
        }
        // if _PS_ROOT_DIR_ is defined, use it instead of "guessing" the module dir.
        if (defined('_PS_ROOT_DIR_') and !defined('_PS_MODULE_DIR_')) {
            define('_PS_MODULE_DIR_', _PS_ROOT_DIR_ . '/modules/');
        } else {
            if (!defined('_PS_MODULE_DIR_')) {
                define('_PS_MODULE_DIR_', INSTALL_PATH . '/../modules/');
            }
        }
        // @todo upgrade_dir_php should be handled by Upgrader class
        $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->nextDesc = $this->l('php upgrade dir is not found');
                $this->nextQuickInfo[] = 'php upgrade dir is missing';
                return false;
            }
        }
        define('_PS_INSTALLER_PHP_UPGRADE_DIR_', INSTALL_PATH . DIRECTORY_SEPARATOR . $upgrade_dir_php . DIRECTORY_SEPARATOR);
        //old version detection
        global $oldversion, $logger;
        $oldversion = false;
        if (file_exists(SETTINGS_FILE)) {
            include_once SETTINGS_FILE;
            // include_once(DEFINES_FILE);
            $oldversion = _PS_VERSION_;
        } else {
            $this->next = 'error';
            $this->nextQuickInfo[] = $this->l('The config/settings.inc.php file was not found.');
            return false;
            die('<action result="fail" error="30" />' . "\n");
        }
        if (!defined('__PS_BASE_URI__')) {
            define('__PS_BASE_URI__', realpath(dirname($_SERVER['SCRIPT_NAME'])) . '/../../');
        }
        if (!defined('_THEMES_DIR_')) {
            define('_THEMES_DIR_', __PS_BASE_URI__ . 'themes/');
        }
        $oldversion = _PS_VERSION_;
        $versionCompare = version_compare(INSTALL_VERSION, $oldversion);
        if ($versionCompare == '-1') {
            $this->next = 'error';
            $this->nextQuickInfo[] = $this->l('This installer is too old');
            return false;
            // die('<action result="fail" error="27" />'."\n");
        } elseif ($versionCompare == 0) {
            $this->next = 'error';
            $this->nextQuickInfo[] = $this->l(sprintf('You already have the %s version.', INSTALL_VERSION));
            return false;
            die('<action result="fail" error="28" />' . "\n");
        } elseif ($versionCompare === false) {
            $this->next = 'error';
            $this->nextQuickInfo[] = $this->l('There is no older version. Did you delete or rename the config/settings.inc.php file?');
            return false;
            die('<action result="fail" error="29" />' . "\n");
        }
        //check DB access
        $this->db();
        error_reporting(E_ALL);
        $resultDB = MySql::tryToConnect(_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');
            return false;
            die("<action result='fail' error='" . $resultDB . "'/>\n");
        }
        //custom sql file creation
        $upgradeFiles = array();
        // @todo : upgrade/sql or sql/upgrade should be handled in the Upgrader class
        $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->nextDesc = $this->l('unable to find upgrade directory in the install 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 verify that the %s folder is not empty'), $upgrade_dir_sql);
            // fail 31
            return false;
        }
        natcasesort($upgradeFiles);
        $neededUpgradeFiles = array();
        // fix : complete version number if there is not all 4 numbers
        // for example replace 1.4.3 by 1.4.3.0
        // consequences : file 1.4.3.0.sql will be skipped if oldversion = 1.4.3
        // @since 1.4.4.0
        $arrayVersion = preg_split('#\\.#', $oldversion);
        $versionNumbers = sizeof($arrayVersion);
        if ($versionNumbers != 4) {
            $arrayVersion = array_pad($arrayVersion, 4, '0');
        }
        $oldversion = implode('.', $arrayVersion);
        // end of fix
        foreach ($upgradeFiles as $version) {
            if (version_compare($version, $oldversion) == 1 and version_compare(INSTALL_VERSION, $version) != -1) {
                $neededUpgradeFiles[] = $version;
            }
        }
        if (empty($neededUpgradeFiles)) {
            $this->next = 'error';
            $this->nextQuickInfo[] = $this->l('No upgrade is possible.');
            return false;
            $logger->logError('No upgrade is possible.');
            die('<action result="fail" error="32" />' . "\n");
        }
        $sqlContentVersion = array();
        if (isset($_GET['customModule']) and $_GET['customModule'] == 'desactivate') {
            require_once _PS_INSTALLER_PHP_UPGRADE_DIR_ . 'deactivate_custom_modules.php';
            deactivate_custom_modules();
        }
        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);
                return false;
                $logger->logError('Error while loading sql upgrade file.');
                die('<action result="fail" error="33" />' . "\n");
            }
            if (!($sqlContent = file_get_contents($file) . "\n")) {
                $this->next = 'error';
                $this->nextQuickInfo[] = $this->l(sprintf('Error while loading sql upgrade file %s.', $version));
                return false;
                $logger->logError(sprintf('Error while loading sql upgrade file %s.', $version));
                die('<action result="fail" error="33" />' . "\n");
            }
            $sqlContent = str_replace(array($filePrefix, $engineType), array(_DB_PREFIX_, $mysqlEngine), $sqlContent);
            $sqlContent = preg_split("/;\\s*[\r\n]+/", $sqlContent);
            $sqlContentVersion[$version] = $sqlContent;
        }
        //sql file execution
        global $requests, $warningExist;
        $requests = '';
        $warningExist = false;
        // Configuration::loadConfiguration();
        $request = '';
        foreach ($sqlContentVersion as $upgrade_file => $sqlContent) {
            foreach ($sqlContent as $query) {
                $query = trim($query);
                if (!empty($query)) {
                    /* If php code have to be executed */
                    if (strpos($query, '/* PHP:') !== false) {
                        /* Parsing php code */
                        $pos = strpos($query, '/* PHP:') + strlen('/* PHP:');
                        $phpString = substr($query, $pos, strlen($query) - $pos - strlen(' */;'));
                        $php = explode('::', $phpString);
                        preg_match('/\\((.*)\\)/', $phpString, $pattern);
                        $paramsString = trim($pattern[0], '()');
                        preg_match_all('/([^,]+),? ?/', $paramsString, $parameters);
                        if (isset($parameters[1])) {
                            $parameters = $parameters[1];
                        } else {
                            $parameters = array();
                        }
                        if (is_array($parameters)) {
                            foreach ($parameters as &$parameter) {
                                $parameter = str_replace('\'', '', $parameter);
                            }
                        }
                        // reset phpRes to a null value
                        $phpRes = null;
                        /* Call a simple function */
                        if (strpos($phpString, '::') === false) {
                            $func_name = str_replace($pattern[0], '', $php[0]);
                            if (!file_exists(_PS_INSTALLER_PHP_UPGRADE_DIR_ . strtolower($func_name) . '.php')) {
                                $this->nextQuickInfo[] = '<div class="upgradeDbError">[ERROR] ' . $upgrade_file . ' PHP - missing file ' . $query . '</div>';
                            } 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 called ' . $php[0] . '::' . str_replace($pattern[0], '', $php[1]) . '</div>';
                        }
                        if (isset($phpRes) && (is_array($phpRes) && !empty($phpRes['error'])) || $phpRes === false) {
                            $this->next = 'error';
                            $this->nextQuickInfo[] = '<div class="upgradeDbError">[ERROR] PHP ' . $upgrade_file . ' ' . (empty($phpRes['error']) ? $query : ' ' . $phpRes['error']) . ' ' . (empty($phpRes['msg']) ? '' : ' - ' . $phpRes['msg']) . '</div>';
                        } else {
                            $this->nextQuickInfo[] = '<div class="upgradeDbOk">[OK] PHP' . $upgrade_file . ' ' . $query . '</div>';
                        }
                    } elseif (!Db::getInstance()->execute($query)) {
                        $this->next = 'error';
                        $this->nextQuickInfo[] = '<div class="upgradeDbError">[ERROR] SQL ' . $upgrade_file . ' ' . Db::getInstance()->getNumberError() . ' in ' . $query . ': ' . Db::getInstance()->getMsgError() . '</div>';
                        $warningExist = true;
                    } else {
                        $this->nextQuickInfo[] = '<div class="upgradeDbOk">[OK] SQL ' . $upgrade_file . ' ' . $query . '</div>';
                    }
                }
            }
        }
        if ($this->next == 'error') {
            $this->nextDesc = $this->l('An error happen during database upgrade');
            return false;
        }
        $this->nextQuickInfo[] = $this->l('Upgrade Db Ok');
        // no error !
        # At this point, database upgrade is over.
        # Now we need to add all previous missing settings items, and reset cache and compile directories
        $this->writeNewSettings();
        // Settings updated, compile and cache directories must be emptied
        // @todo : the list of theses directory should be available elsewhere
        $arrayToClean[] = INSTALL_PATH . '/../tools/smarty/cache/';
        $arrayToClean[] = INSTALL_PATH . '/../tools/smarty/compile/';
        $arrayToClean[] = INSTALL_PATH . '/../tools/smarty_v2/cache/';
        $arrayToClean[] = INSTALL_PATH . '/../tools/smarty_v2/compile/';
        foreach ($arrayToClean as $dir) {
            if (!file_exists($dir)) {
                $this->nextQuickInfo[] = sprintf($this->l('[SKIP] directory "%s" doesn\'t exist and cannot be emptied.'), $dir);
                continue;
            } else {
                foreach (scandir($dir) as $file) {
                    if ($file[0] != '.' and $file != 'index.php' and $file != '.htaccess') {
                        unlink($dir . $file);
                        $this->nextQuickInfo[] = sprintf($this->l('[cleaning cache] %s removed'), $file);
                    }
                }
            }
        }
        // delete cache filesystem if activated
        $depth = (int) Db::getInstance()->getValue('SELECT value 
			FROM ' . _DB_PREFIX_ . 'configuration 
			WHERE name = "PS_CACHEFS_DIRECTORY_DEPTH"');
        if ($depth) {
            Tools::deleteDirectory(_PS_CACHEFS_DIRECTORY_, false);
            CacheFs::createCacheFsDirectories((int) $depth);
        }
        // we do not use class Configuration because it's not loaded;
        Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'configuration`
			SET value="0" WHERE name = "PS_HIDE_OPTIMIZATION_TIS"');
        Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'configuration`
			SET value="1" WHERE name = "PS_NEED_REBUILD_INDEX"');
        Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'configuration`
			SET value="' . INSTALL_VERSION . '" WHERE name = "PS_VERSION_DB"');
        if ($warningExist) {
            $this->next = 'error';
            $this->nextQuickInfo[] = $this->l('Warning detected during upgrade.');
            $this->nextDesc = $this->l('Error while inserting content into the database');
            return false;
        } else {
            $this->next = 'upgradeComplete';
            $this->nextDesc = $this->l('Upgrade completed');
            return true;
        }
    }