diff --git a/core/core.services.yml b/core/core.services.yml index bffe0aa..d90a4dd 100644 --- a/core/core.services.yml +++ b/core/core.services.yml @@ -220,7 +220,6 @@ services: arguments: ['@event_dispatcher', '@service_container', '@controller_resolver'] language_manager: class: Drupal\Core\Language\LanguageManager - arguments: ['@state', '@module_handler'] string_translator.custom_strings: class: Drupal\Core\StringTranslation\Translator\CustomStrings arguments: ['@settings'] @@ -499,11 +498,6 @@ services: tags: - { name: event_subscriber } arguments: ['@config.storage', '@config.storage.snapshot'] - language_request_subscriber: - class: Drupal\Core\EventSubscriber\LanguageRequestSubscriber - tags: - - { name: event_subscriber } - arguments: ['@language_manager', '@string_translation'] exception_controller: class: Drupal\Core\Controller\ExceptionController arguments: ['@content_negotiation'] diff --git a/core/includes/bootstrap.inc b/core/includes/bootstrap.inc index 086f025..a822869 100644 --- a/core/includes/bootstrap.inc +++ b/core/includes/bootstrap.inc @@ -22,6 +22,7 @@ use Drupal\Core\Lock\DatabaseLockBackend; use Drupal\Core\Lock\LockBackendInterface; use Drupal\Core\Session\UserSession; +use Drupal\language\ConfigurableLanguageManagerInterface; /** * @file @@ -2392,37 +2393,13 @@ function language($type) { } /** - * Returns an array of the available language types. - * - * @return array - * An array of all language types where the keys of each are the language type - * name and its value is its configurability (TRUE/FALSE). - */ -function language_types_get_all() { - $types = \Drupal::config('system.language.types')->get('all'); - return $types ? $types : array_keys(language_types_get_default()); -} - -/** - * Returns a list of the built-in language types. - * - * @return array - * An array of key-values pairs where the key is the language type name and - * the value is its configurability (TRUE/FALSE). - */ -function language_types_get_default() { - return array( - Language::TYPE_INTERFACE => TRUE, - Language::TYPE_CONTENT => FALSE, - Language::TYPE_URL => FALSE, - ); -} - -/** * Returns TRUE if there is more than one language enabled. * * @return bool * TRUE if more than one language is enabled. + * + * @deprecated as of Drupal 8.0, use + * \Drupal::languageManager()->isMultilingual() instead. */ function language_multilingual() { return \Drupal::languageManager()->isMultilingual(); @@ -2439,67 +2416,12 @@ function language_multilingual() { * @return array * An associative array of languages, keyed by the language code, ordered by * weight ascending and name ascending. + * + * @deprecated as of Drupal 8, use + * \Drupal::languageManager()->getLanguageList($flags) instead. */ function language_list($flags = Language::STATE_CONFIGURABLE) { - - $languages = &drupal_static(__FUNCTION__); - - // Initialize master language list. - if (!isset($languages)) { - // Initialize local language list cache. - $languages = array(); - - // Fill in master language list based on current configuration. - $default = language_default(); - if (language_multilingual() || \Drupal::moduleHandler()->moduleExists('language')) { - // Use language module configuration if available. - $language_entities = config_get_storage_names_with_prefix('language.entity'); - - // Initialize default property so callers have an easy reference and can - // save the same object without data loss. - foreach ($language_entities as $langcode_config_name) { - $langcode = substr($langcode_config_name, strlen('language.entity.')); - $info = \Drupal::config($langcode_config_name)->get(); - $languages[$langcode] = new Language(array( - 'default' => ($info['id'] == $default->id), - 'name' => $info['label'], - 'id' => $info['id'], - 'direction' => $info['direction'], - 'locked' => $info['locked'], - 'weight' => $info['weight'], - )); - } - Language::sort($languages); - } - else { - // No language module, so use the default language only. - $languages = array($default->id => $default); - // Add the special languages, they will be filtered later if needed. - $languages += language_default_locked_languages($default->weight); - } - } - - // Filter the full list of languages based on the value of the $all flag. By - // default we remove the locked languages, but the caller may request for - // those languages to be added as well. - $filtered_languages = array(); - - // Add the site's default language if flagged as allowed value. - if ($flags & Language::STATE_SITE_DEFAULT) { - $default = isset($default) ? $default : language_default(); - // Rename the default language. - $default->name = t("Site's default language (@lang_name)", array('@lang_name' => $default->name)); - $filtered_languages['site_default'] = $default; - } - - foreach ($languages as $langcode => $language) { - if (($language->locked && !($flags & Language::STATE_LOCKED)) || (!$language->locked && !($flags & Language::STATE_CONFIGURABLE))) { - continue; - } - $filtered_languages[$langcode] = $language; - } - - return $filtered_languages; + return \Drupal::languageManager()->getLanguageList($flags); } /** @@ -2511,26 +2433,12 @@ function language_list($flags = Language::STATE_CONFIGURABLE) { * * @return array * An array of language objects. + * + * @deprecated as of Drupal 8.0, use + * \Drupal::languageManager()->getDefaultLockedLanguages($weight) instead. */ function language_default_locked_languages($weight = 0) { - $locked_language = array( - 'default' => FALSE, - 'locked' => TRUE, - 'enabled' => TRUE, - ); - - $languages = array(); - $languages[Language::LANGCODE_NOT_SPECIFIED] = new Language(array( - 'id' => Language::LANGCODE_NOT_SPECIFIED, - 'name' => t('Not specified'), - 'weight' => ++$weight, - ) + $locked_language); - $languages[Language::LANGCODE_NOT_APPLICABLE] = new Language(array( - 'id' => Language::LANGCODE_NOT_APPLICABLE, - 'name' => t('Not applicable'), - 'weight' => ++$weight, - ) + $locked_language); - return $languages; + return \Drupal::languageManager()->getDefaultLockedLanguages($weight); } /** @@ -2541,10 +2449,14 @@ function language_default_locked_languages($weight = 0) { * * @return \Drupal\core\Language\Language|null * A fully-populated language object or NULL. + * + * @see \Drupal\Core\Language\LanguageManager::loadLanguage(). + * + * @deprecated as of Drupal 8.0, use + * \Drupal::languageManager()->loadLanguage($langcode) instead. */ function language_load($langcode) { - $languages = language_list(Language::STATE_ALL); - return isset($languages[$langcode]) ? $languages[$langcode] : NULL; + return \Drupal::languageManager()->loadLanguage($langcode); } /** @@ -2557,6 +2469,7 @@ function language_load($langcode) { * The printed name of the language. */ function language_name($langcode) { + // FIXME if ($langcode == Language::LANGCODE_NOT_SPECIFIED) { return t('None'); } @@ -2578,10 +2491,14 @@ function language_name($langcode) { * * @return bool * Returns whether the language is locked. + * + * @see \Drupal\Core\Language\LanguageManager::isLanguageLocked(). + * + * @deprecated as of Drupal 8.0, use + * \Drupal::languageManager()->isLanguageLocked($langcode) instead. */ function language_is_locked($langcode) { - $language = language_load($langcode); - return ($language ? $language->locked : FALSE); + return \Drupal::languageManager()->isLanguageLocked($langcode); } /** @@ -2591,33 +2508,80 @@ function language_is_locked($langcode) { * A language object. */ function language_default() { - $info = variable_get('language_default', array( - 'id' => 'en', - 'name' => 'English', - 'direction' => 0, - 'weight' => 0, - 'locked' => 0, - )); - $info['default'] = TRUE; - return new Language($info); + // FIXME + $default_info = variable_get('language_default', Language::$defaultValues); + return new Language($default_info + array('default' => TRUE)); } /** - * Stores or retrieves the path derived during language negotiation. + * Returns information about all defined language types. * - * @param string $new_path - * The altered path. + * @return + * An associative array of language type information arrays keyed by type + * names. Based on information from hook_language_types_info(). * - * @todo Replace this with a path processor in language module. See - * http://drupal.org/node/1888424. + * @see hook_language_types_info(). */ -function _language_resolved_path($new_path = NULL) { - $path = &drupal_static(__FUNCTION__, NULL); - if ($new_path === NULL) { - return $path; +function language_types_info() { + $language_types = &drupal_static(__FUNCTION__); + + if (!isset($language_types)) { + $language_types = \Drupal::moduleHandler()->invokeAll('language_types_info'); + // Let other modules alter the list of language types. + drupal_alter('language_types_info', $language_types); } - $path = $new_path; - return $path; + + return $language_types; +} + +/** + * Returns only the configurable language types. + * + * A language type maybe configurable or fixed. A fixed language type is a type + * whose language negotiation methods are module-defined and not altered through + * the user interface. + * + * @return + * An array of language type names. + * + * @deprecated as of 8.0, use + * \Drupal::languageManager()->getConfigurableLanguageTypes() instead. + */ +function language_types_get_configurable() { + $language_manager = \Drupal::languageManager(); + return $language_manager instanceof ConfigurableLanguageManagerInterface ? $language_manager->getConfigurableLanguageTypes() : array(); +} + +/** + * Returns the language switch links for the given language type. + * + * @param $type + * The language type. + * @param $path + * The internal path the switch links will be relative to. + * + * @return + * A keyed array of links ready to be themed. + * + * @deprecated as of 8.0, use + * \Drupal::languageManager()->getLanguageSwitchLinks() instead. + */ +function language_negotiation_get_switch_links($type, $path) { + return Drupal::languageManager()->getLanguageSwitchLinks($type, $path); +} + +/** + * Returns all defined language negotiation methods. + * + * @return + * An array of language negotiation methods. + * + * @deprecated as of 8.0, use + * Drupal::service('plugin.manager.language_negotiation_method')->getDefinitions() + * instead. + */ +function language_negotiation_info() { + return \Drupal::service('plugin.manager.language_negotiation_method')->getDefinitions(); } /** diff --git a/core/includes/install.core.inc b/core/includes/install.core.inc index 3cbbd82..7171036 100644 --- a/core/includes/install.core.inc +++ b/core/includes/install.core.inc @@ -1,5 +1,6 @@ register('event_dispatcher', 'Symfony\Component\EventDispatcher\EventDispatcher'); $container->register('config.storage', 'Drupal\Core\Config\InstallStorage'); @@ -391,9 +391,7 @@ function install_begin_request(&$install_state) { ->addArgument(new Reference('config.context')); // Register the 'language_manager' service. - $container - ->register('language_manager', 'Drupal\Core\Language\LanguageManager') - ->addArgument(NULL); + $container->register('language_manager', 'Drupal\Core\Language\LanguageManager'); // Register the translation services. install_register_translation_service($container); @@ -1612,9 +1610,6 @@ function install_select_language(&$install_state) { * @ingroup forms */ function install_select_language_form($form, &$form_state, $files = array()) { - include_once __DIR__ . '/../modules/language/language.module'; - include_once __DIR__ . '/../modules/language/language.negotiation.inc'; - $standard_languages = LanguageManager::getStandardLanguageList(); $select_options = array(); $browser_options = array(); @@ -1626,22 +1621,19 @@ function install_select_language_form($form, &$form_state, $files = array()) { // Select lists based on available language files. foreach ($files as $langcode => $uri) { $select_options[$langcode] = isset($standard_languages[$langcode]) ? $standard_languages[$langcode][1] : $langcode; - $browser_options[$langcode] = new Language(array( - 'id' => $langcode, - )); + $browser_options[] = $langcode; } } else { // Select lists based on all standard languages. foreach ($standard_languages as $langcode => $language_names) { $select_options[$langcode] = $language_names[1]; - $browser_options[$langcode] = new Language(array( - 'id' => $langcode, - )); + $browser_options[] = $langcode; } } - $browser_langcode = language_from_browser($browser_options); + $request = Request::createFromGlobals(); + $browser_langcode = Browser::getLangcode($request->server->get('HTTP_ACCEPT_LANGUAGE'), $browser_options); $form['langcode'] = array( '#type' => 'select', '#title' => t('Choose language'), diff --git a/core/includes/language.inc b/core/includes/language.inc index 618e3a7..a6b69bc 100644 --- a/core/includes/language.inc +++ b/core/includes/language.inc @@ -8,16 +8,8 @@ */ use Drupal\Core\Language\Language; - -/** - * No language negotiation. The default language is used. - */ -const LANGUAGE_NEGOTIATION_SELECTED = 'language-selected'; - -/** - * The language is determined using the current interface language. - */ -const LANGUAGE_NEGOTIATION_INTERFACE = 'language-interface'; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationSelected; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUI; /** * @defgroup language_negotiation Language Negotiation API functionality @@ -89,8 +81,8 @@ * function mymodule_language_negotiation_info_alter(&$negotiation_info) { * // Replace the core function with our own function. * module_load_include('language', 'inc', 'language.negotiation'); - * $negotiation_info[LANGUAGE_NEGOTIATION_URL]['callbacks']['negotiation'] = 'mymodule_from_url'; - * $negotiation_info[LANGUAGE_NEGOTIATION_URL]['file'] = drupal_get_path('module', 'mymodule') . '/mymodule.module'; + * $negotiation_info[\Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl::METHOD_ID]['callbacks']['negotiation'] = 'mymodule_from_url'; + * $negotiation_info[\Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl::METHOD_ID]['file'] = drupal_get_path('module', 'mymodule') . '/mymodule.module'; * } * * function mymodule_from_url($languages) { @@ -113,438 +105,7 @@ * @link http://drupal.org/node/1497272 Language Negotiation API @endlink */ -/** - * Chooses a language based on language negotiation method settings. - * - * @param $type - * The language type key to find the language for. - * - * @param $request - * The HttpReqeust object representing the current request. - * - * @return - * The negotiated language object. - */ -function language_types_initialize($type, $request = NULL) { - // Execute the language negotiation methods in the order they were set up and - // return the first valid language found. - $negotiation = variable_get("language_negotiation_$type", array()); - - foreach ($negotiation as $method_id => $method) { - // Skip negotiation methods not appropriate for this type. - if (isset($method['types']) && !in_array($type, $method['types'])) { - continue; - } - $language = language_negotiation_method_invoke($method_id, $method, $request); - if ($language) { - // Remember the method ID used to detect the language. - $language->method_id = $method_id; - return $language; - } - } - - // If no other language was found use the default one. - $language = language_default(); - $language->method_id = LANGUAGE_NEGOTIATION_SELECTED; - return $language; -} - -/** - * Returns information about all defined language types. - * - * @return - * An associative array of language type information arrays keyed by type - * names. Based on information from hook_language_types_info(). - * - * @see hook_language_types_info(). - */ -function language_types_info() { - $language_types = &drupal_static(__FUNCTION__); - - if (!isset($language_types)) { - $language_types = \Drupal::moduleHandler()->invokeAll('language_types_info'); - // Let other modules alter the list of language types. - drupal_alter('language_types_info', $language_types); - } - - return $language_types; -} - -/** - * Returns only the configurable language types. - * - * A language type maybe configurable or fixed. A fixed language type is a type - * whose language negotiation methods are module-defined and not altered through - * the user interface. - * - * @return - * An array of language type names. - */ -function language_types_get_configurable() { - $configurable = \Drupal::config('system.language.types')->get('configurable'); - return $configurable ? $configurable : array(); -} - -/** - * Disables the given language types. - * - * @param $types - * An array of language types. - */ -function language_types_disable($types) { - $configurable = language_types_get_configurable(); - \Drupal::config('system.language.types')->set('configurable', array_diff($configurable, $types))->save(); -} - -/** - * Updates the language type configuration. - * - * @param array $configurable_language_types - * An array of configurable language types. - */ -function language_types_set(array $configurable_language_types) { - // Ensure that we are getting the defined language negotiation information. An - // invocation of \Drupal\Core\Extension\ModuleHandler::install() or - // \Drupal\Core\Extension\ModuleHandler::uninstall() could invalidate the - // cached information. - drupal_static_reset('language_types_info'); - drupal_static_reset('language_negotiation_info'); - - $language_types = array(); - $negotiation_info = language_negotiation_info(); - $language_types_info = language_types_info(); - - foreach ($language_types_info as $type => $info) { - $configurable = in_array($type, $configurable_language_types); - - // Check whether the language type is unlocked. Only the status of unlocked - // language types can be toggled between configurable and non-configurable. - // The default language negotiation settings, if available, are stored in - // $info['fixed']. - if (empty($info['locked'])) { - // If we have a non-locked non-configurable language type without default - // language negotiation settings, we use the values negotiated for the - // interface language which should always be available. - if (!$configurable && !empty($info['fixed'])) { - $method_weights = array(LANGUAGE_NEGOTIATION_INTERFACE); - $method_weights = array_flip($method_weights); - language_negotiation_set($type, $method_weights); - } - } - else { - // Locked language types with default settings are always considered - // non-configurable. In turn if default settings are missing, the language - // type is always considered configurable. - $configurable = empty($info['fixed']); - - // If the language is non-configurable we need to store its language - // negotiation settings. - if (!$configurable) { - $method_weights = array(); - foreach ($info['fixed'] as $weight => $method_id) { - if (isset($negotiation_info[$method_id])) { - $method_weights[$method_id] = $weight; - } - } - language_negotiation_set($type, $method_weights); - } - } - - $language_types[$type] = $configurable; - } - - // Store the language type configuration. - $config = \Drupal::config('system.language.types'); - $config->set('configurable', array_keys(array_filter($language_types)))->save(); - $config->set('all', array_keys($language_types))->save(); - - // Ensure that subsequent calls of language_types_get_configurable() return - // the updated language type information. - drupal_static_reset('language_types_get_configurable'); -} - -/** - * Returns the ID of the language type's first language negotiation method. - * - * @param $type - * The language type. - * - * @return - * The identifier of the first language negotiation method for the given - * language type, or the default method if none exists. - */ -function language_negotiation_method_get_first($type) { - $negotiation = variable_get("language_negotiation_$type", array()); - return empty($negotiation) ? LANGUAGE_NEGOTIATION_SELECTED : key($negotiation); -} - -/** - * Checks whether a language negotiation method is enabled for a language type. - * - * @param $method_id - * The language negotiation method ID. - * @param $type - * (optional) The language type. If none is passed, all the configurable - * language types will be inspected. - * - * @return - * TRUE if the method is enabled for at least one of the given language - * types, or FALSE otherwise. - */ -function language_negotiation_method_enabled($method_id, $type = NULL) { - $language_types = !empty($type) ? array($type) : language_types_get_configurable(); - - foreach ($language_types as $type) { - $negotiation = variable_get("language_negotiation_$type", array()); - if (isset($negotiation[$method_id])) { - return TRUE; - } - } - - return FALSE; -} - -/** - * Returns the language switch links for the given language type. - * - * @param $type - * The language type. - * @param $path - * The internal path the switch links will be relative to. - * - * @return - * A keyed array of links ready to be themed. - */ -function language_negotiation_get_switch_links($type, $path) { - $links = FALSE; - $negotiation = variable_get("language_negotiation_$type", array()); - - foreach ($negotiation as $method_id => $method) { - if (isset($method['callbacks']['language_switch'])) { - if (isset($method['file'])) { - require_once DRUPAL_ROOT . '/' . $method['file']; - } - - $callback = $method['callbacks']['language_switch']; - $result = $callback($type, $path); - - if (!empty($result)) { - // Allow modules to provide translations for specific links. - drupal_alter('language_switch_links', $result, $type, $path); - $links = (object) array('links' => $result, 'method_id' => $method_id); - break; - } - } - } - - return $links; -} - -/** - * Removes any language negotiation methods that are no longer defined. - */ -function language_negotiation_purge() { - // Ensure that we are getting the defined language negotiation information. An - // invocation of \Drupal\Core\Extension\ModuleHandler::install() or - // \Drupal\Core\Extension\ModuleHandler::uninstall() could invalidate the - // cached information. - drupal_static_reset('language_negotiation_info'); - drupal_static_reset('language_types_info'); - - $negotiation_info = language_negotiation_info(); - foreach (language_types_info() as $type => $type_info) { - $weight = 0; - $method_weights = array(); - foreach (variable_get("language_negotiation_$type", array()) as $method_id => $method) { - if (isset($negotiation_info[$method_id])) { - $method_weights[$method_id] = $weight++; - } - } - language_negotiation_set($type, $method_weights); - } -} - -/** - * Saves a list of language negotiation methods for a language type. - * - * @param $type - * The language type. - * @param $method_weights - * An array of language negotiation method weights keyed by method ID. - */ -function language_negotiation_set($type, $method_weights) { - // Save only the necessary fields. - $method_fields = array('callbacks', 'file', 'cache'); - - $negotiation = array(); - $negotiation_info = language_negotiation_info(); - $default_types = language_types_get_configurable(); - - // Order the language negotiation method list by weight. - asort($method_weights); - - foreach ($method_weights as $method_id => $weight) { - if (isset($negotiation_info[$method_id])) { - $method = $negotiation_info[$method_id]; - // If the language negotiation method does not express any preference - // about types, make it available for any configurable type. - $types = array_flip(isset($method['types']) ? $method['types'] : $default_types); - // Check whether the method is defined and has the right type. - if (isset($types[$type])) { - $method_data = array(); - foreach ($method_fields as $field) { - if (isset($method[$field])) { - $method_data[$field] = $method[$field]; - } - } - $negotiation[$method_id] = $method_data; - } - } - } - - variable_set("language_negotiation_$type", $negotiation); -} - -/** - * Returns all defined language negotiation methods. - * - * @return - * An array of language negotiation methods. - */ -function language_negotiation_info() { - $negotiation_info = &drupal_static(__FUNCTION__); - - if (!isset($negotiation_info)) { - // Collect all the module-defined language negotiation methods. - $negotiation_info = \Drupal::moduleHandler()->invokeAll('language_negotiation_info'); - $languages = language_list(); - $selected_language = $languages[language_from_selected($languages)]; - $description = 'Language based on a selected language. '; - $description .= ($selected_language->id == language_default()->id) ? "(Site's default language (@language_name))" : '(@language_name)'; - // Add the default language negotiation method. - $negotiation_info[LANGUAGE_NEGOTIATION_SELECTED] = array( - 'callbacks' => array( - 'negotiation' => 'language_from_selected', - ), - 'weight' => 12, - 'name' => t('Selected language'), - 'description' => t($description, array('@language_name' => $selected_language->name)), - 'config' => 'admin/config/regional/language/detection/selected', - ); - - // Let other modules alter the list of language negotiation methods. - drupal_alter('language_negotiation_info', $negotiation_info); - } - - return $negotiation_info; -} - -/** - * Invokes a language negotiation method and caches the results. - * - * @param $method_id - * The language negotiation method's identifier. - * @param $method - * (optional) An associative array of information about the method to be - * invoked (see hook_language_negotiation_info() for details). If not passed - * in, it will be loaded through language_negotiation_info(). - * - * @param $request - * (optional) The HttpRequest object representing the current request. - * - * @return - * A language object representing the language chosen by the method. - */ -function language_negotiation_method_invoke($method_id, $method = NULL, $request = NULL) { - $results = &drupal_static(__FUNCTION__); - - if (!isset($results[$method_id])) { - global $user; - - $languages = language_list(); - - if (!isset($method)) { - $negotiation_info = language_negotiation_info(); - $method = $negotiation_info[$method_id]; - } - - if (isset($method['file'])) { - require_once DRUPAL_ROOT . '/' . $method['file']; - } - // Check for a cache mode force from settings.php. - if (settings()->get('page_cache_without_database')) { - $cache_enabled = TRUE; - } - else { - drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES, FALSE); - $config = \Drupal::config('system.performance'); - $cache_enabled = $config->get('cache.page.use_internal'); - } - // If the language negotiation method has no cache preference or this is - // satisfied we can execute the callback. - $cache = !isset($method['cache']) || $user->isAuthenticated() || $method['cache'] == $cache_enabled; - $callback = isset($method['callbacks']['negotiation']) ? $method['callbacks']['negotiation'] : FALSE; - $langcode = $cache && function_exists($callback) ? $callback($languages, $request) : FALSE; - $results[$method_id] = isset($languages[$langcode]) ? $languages[$langcode] : FALSE; - } - - // Since objects are resources, we need to return a clone to prevent the - // language negotiation method cache from being unintentionally altered. The - // same methods might be used with different language types based on - // configuration. - return !empty($results[$method_id]) ? clone($results[$method_id]) : $results[$method_id]; -} - - /** - * Identifies language from configuration. - * - * @param $languages - * An array of valid language objects. - * - * @return - * A valid language code on success, FALSE otherwise. - */ -function language_from_selected($languages) { - $langcode = (string) \Drupal::config('language.negotiation')->get('selected_langcode'); - // Replace the site's default langcode by its real value. - if ($langcode == 'site_default') { - $langcode = language_default()->id; - } - return isset($languages[$langcode]) ? $langcode : language_default()->id; -} - -/** - * Splits the given path into prefix and actual path. - * - * Parse the given path and return the language object identified by the prefix - * and the actual path. - * - * @param $path - * The path to split. - * @param $languages - * An array of valid languages. - * - * @return - * An array composed of: - * - A language object corresponding to the identified prefix on success, - * FALSE otherwise. - * - The path without the prefix on success, the given path otherwise. - */ -function language_url_split_prefix($path, $languages) { - $args = empty($path) ? array() : explode('/', $path); - $prefix = array_shift($args); - - // Search prefix within enabled languages. - $prefixes = language_negotiation_url_prefixes(); - foreach ($languages as $language) { - if (isset($prefixes[$language->id]) && $prefixes[$language->id] == $prefix) { - // Rebuild $path with the language removed. - return array($language, implode('/', $args)); - } - } - - return array(FALSE, $path); -} +// TODO /** * @} End of "language_negotiation" diff --git a/core/includes/update.inc b/core/includes/update.inc index 7b8a6e2..1a7491f 100644 --- a/core/includes/update.inc +++ b/core/includes/update.inc @@ -477,9 +477,7 @@ function update_prepare_stored_includes() { foreach ($language_types as $language_type) { $negotiation = update_variable_get("language_negotiation_$language_type", array()); foreach ($negotiation as &$method) { - if (isset($method['file']) && $method['file'] == 'includes/locale.inc') { - $method['file'] = 'core/modules/language/language.negotiation.inc'; - } + unset($method['file']); } update_variable_set("language_negotiation_$language_type", $negotiation); } @@ -524,9 +522,6 @@ function update_prepare_d8_language() { db_drop_field('languages', 'native'); db_drop_field('languages', 'enabled'); - // Update language count. - \Drupal::state()->set('language_count', db_query('SELECT COUNT(language) FROM {languages}')->fetchField()); - // Rename the languages table to language. db_rename_table('languages', 'language'); diff --git a/core/lib/Drupal.php b/core/lib/Drupal.php index 5441e30..d7a40a4 100644 --- a/core/lib/Drupal.php +++ b/core/lib/Drupal.php @@ -520,7 +520,7 @@ public static function translation() { /** * Returns the language manager service. * - * @return \Drupal\Core\Language\LanguageManager + * @return \Drupal\Core\Language\LanguageManagerInterface * The language manager. */ public static function languageManager() { diff --git a/core/lib/Drupal/Component/Utility/Browser.php b/core/lib/Drupal/Component/Utility/Browser.php new file mode 100644 index 0000000..7977b39 --- /dev/null +++ b/core/lib/Drupal/Component/Utility/Browser.php @@ -0,0 +1,141 @@ + $standard_langcode) { + if ($langcode == $browser_langcode) { + $match[1] = $standard_langcode; + } + } + } + // We can safely use strtolower() here, tags are ASCII. + // RFC2616 mandates that the decimal part is no more than three digits, + // so we multiply the qvalue by 1000 to avoid floating point + // comparisons. + $langcode = strtolower($match[1]); + $qvalue = isset($match[2]) ? (float) $match[2] : 1; + // Take the highest qvalue for this langcode. Although the request + // supposedly contains unique langcodes, our mapping possibly resolves + // to the same langcode for different qvalues. Keep the highest. + $browser_langcodes[$langcode] = max( + (int) ($qvalue * 1000), + (isset($browser_langcodes[$langcode]) ? $browser_langcodes[$langcode] : 0) + ); + } + } + + // We should take pristine values from the HTTP headers, but Internet + // Explorer from version 7 sends only specific language tags (eg. fr-CA) + // without the corresponding generic tag (fr) unless explicitly configured. + // In that case, we assume that the lowest value of the specific tags is the + // value of the generic language to be as close to the HTTP 1.1 spec as + // possible. + // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 and + // http://blogs.msdn.com/b/ie/archive/2006/10/17/accept-language-header-for-internet-explorer-7.aspx + asort($browser_langcodes); + foreach ($browser_langcodes as $langcode => $qvalue) { + // For Chinese languages the generic tag is either zh-hans or zh-hant, so + // we need to handle this separately, we can not split $langcode on the + // first occurrence of '-' otherwise we get a non-existing language zh. + // All other languages use a langcode without a '-', so we can safely + // split on the first occurrence of it. + $generic_tag = ''; + if (strlen($langcode) > 7 && (substr($langcode, 0, 7) == 'zh-hant' || substr($langcode, 0, 7) == 'zh-hans')) { + $generic_tag = substr($langcode, 0, 7); + } + else { + $generic_tag = strtok($langcode, '-'); + } + if (!empty($generic_tag) && !isset($browser_langcodes[$generic_tag])) { + // Add the generic langcode, but make sure it has a lower qvalue as the + // more specific one, so the more specific one gets selected if it's + // defined by both the browser and us. + $browser_langcodes[$generic_tag] = $qvalue - 0.1; + } + } + + // Find the enabled language with the greatest qvalue, following the rules + // of RFC 2616 (section 14.4). If several languages have the same qvalue, + // prefer the one with the greatest weight. + $best_match_langcode = FALSE; + $max_qvalue = 0; + foreach ($langcodes as $langcode_case_sensitive) { + // Language tags are case insensitive (RFC2616, sec 3.10). + $langcode = strtolower($langcode_case_sensitive); + + // If nothing matches below, the default qvalue is the one of the wildcard + // language, if set, or is 0 (which will never match). + $qvalue = isset($browser_langcodes['*']) ? $browser_langcodes['*'] : 0; + + // Find the longest possible prefix of the browser-supplied language ('the + // language-range') that matches this site language ('the language tag'). + $prefix = $langcode; + do { + if (isset($browser_langcodes[$prefix])) { + $qvalue = $browser_langcodes[$prefix]; + break; + } + } + while ($prefix = substr($prefix, 0, strrpos($prefix, '-'))); + + // Find the best match. + if ($qvalue > $max_qvalue) { + $best_match_langcode = $langcode_case_sensitive; + $max_qvalue = $qvalue; + } + } + + return $best_match_langcode; + } + +} diff --git a/core/lib/Drupal/Core/DrupalKernel.php b/core/lib/Drupal/Core/DrupalKernel.php index 0160119..3e48b75 100644 --- a/core/lib/Drupal/Core/DrupalKernel.php +++ b/core/lib/Drupal/Core/DrupalKernel.php @@ -520,6 +520,8 @@ protected function buildContainer() { $container->register('class_loader')->setSynthetic(TRUE); $container->register('kernel', 'Symfony\Component\HttpKernel\KernelInterface')->setSynthetic(TRUE); $container->register('service_container', 'Symfony\Component\DependencyInjection\ContainerInterface')->setSynthetic(TRUE); + // Register the kernel-level config storage. + $container->set('kernel.config.storage', $this->configStorage); $yaml_loader = new YamlFileLoader($container); foreach ($this->serviceYamls as $filename) { $yaml_loader->load($filename); diff --git a/core/lib/Drupal/Core/Language/Language.php b/core/lib/Drupal/Core/Language/Language.php index 1836933..8ad05a7 100644 --- a/core/lib/Drupal/Core/Language/Language.php +++ b/core/lib/Drupal/Core/Language/Language.php @@ -18,6 +18,22 @@ */ class Language { + /** + * The values to use to instantiate the default language. + * + * @todo Remove once converted to config. + * + * @var array + */ + public static $defaultValues = array( + 'id' => 'en', + 'name' => 'English', + 'direction' => 0, + 'weight' => 0, + 'locked' => 0, + 'default' => TRUE, + ); + // Properties within the Language are set up as the default language. /** diff --git a/core/lib/Drupal/Core/Language/LanguageManager.php b/core/lib/Drupal/Core/Language/LanguageManager.php index e6526f2..4476746 100644 --- a/core/lib/Drupal/Core/Language/LanguageManager.php +++ b/core/lib/Drupal/Core/Language/LanguageManager.php @@ -7,245 +7,162 @@ namespace Drupal\Core\Language; -use Drupal\Component\Utility\MapArray; -use Drupal\Core\Extension\ModuleHandlerInterface; -use Drupal\Core\KeyValueStore\StateInterface; -use Symfony\Component\HttpFoundation\Request; - /** * Class responsible for initializing each language type. */ -class LanguageManager { +class LanguageManager implements LanguageManagerInterface { /** - * A request object. + * An array of all the available languages keyed by language code. * - * @var \Symfony\Component\HttpFoundation\Request + * @var array */ - protected $request; + protected $languageList; /** - * The Key/Value Store to use for state. + * The default language object. * - * @var \Drupal\Core\KeyValueStore\StateInterface + * @var \Drupal\Core\Language\Language */ - protected $state = NULL; + protected $defaultLanguage; /** - * The module handler service. - * - * @var \Drupal\Core\Extension\ModuleHandlerInterface + * Constructs a new LanguageManager object. */ - protected $moduleHandler; + public function __construct() { + $this->defaultLanguage = new Language(Language::$defaultValues); + } /** - * An array of language objects keyed by language type. - * - * @var array + * {@inheritdoc} */ - protected $languages; + public function init() { + } /** - * Whether or not the language manager has been initialized. - * - * @var bool + * {@inheritdoc} */ - protected $initialized = FALSE; + public function isMultilingual() { + return FALSE; + } /** - * Whether already in the process of language initialization. - * - * @todo This is only needed due to the circular dependency between language - * and config. See http://drupal.org/node/1862202 for the plan to fix this. - * - * @var bool + * {@inheritdoc} */ - protected $initializing = FALSE; + public function getLanguageTypes() { + return array(Language::TYPE_INTERFACE, Language::TYPE_CONTENT, Language::TYPE_URL); + } /** - * Constructs an LanguageManager object. - * - * @param \Drupal\Core\KeyValueStore\StateInterface $state - * (optional) The state keyvalue store. Defaults to NULL. - * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler - * (optional) The module handler service. Defaults to NULL. + * {@inheritdoc} */ - public function __construct(StateInterface $state = NULL, ModuleHandlerInterface $module_handler = NULL) { - $this->state = $state; - $this->moduleHandler = $module_handler; + public function getLanguage($type = Language::TYPE_INTERFACE) { + return $this->defaultLanguage; } /** - * Initializes each language type to a language object. + * {@inheritdoc} */ - public function init() { - if ($this->initialized) { - return; - } - if ($this->isMultilingual()) { - foreach ($this->getLanguageTypes() as $type) { - $this->getLanguage($type); - } - } - $this->initialized = TRUE; + public function reset($type = NULL) { } /** - * Sets the $request property and resets all language types. - * - * @param \Symfony\Component\HttpFoundation\Request $request - * The HttpRequest object representing the current request. + * {@inheritdoc} */ - public function setRequest(Request $request) { - $this->request = $request; - $this->reset(); - $this->init(); + public function getDefaultLanguage() { + return $this->defaultLanguage; } /** - * Returns a language object for the given type. - * - * @param string $type - * (optional) The language type, e.g. the interface or the content language. - * Defaults to \Drupal\Core\Language\Language::TYPE_INTERFACE. - * - * @return \Drupal\Core\Language\Language - * A language object for the given type. + * {@inheritdoc} */ - public function getLanguage($type = Language::TYPE_INTERFACE) { - if (isset($this->languages[$type])) { - return $this->languages[$type]; + public function getLanguageList($flags = Language::STATE_CONFIGURABLE) { + // Initialize master language list. + if (!isset($this->languageList)) { + // No language module, so use the default language only. + $default = $this->getDefaultLanguage(); + $this->languageList = array($default->id => $default); + // Add the special languages, they will be filtered later if needed. + $this->languageList += $this->getDefaultLockedLanguages($default->weight); } - if ($this->isMultilingual() && $this->request) { - if (!$this->initializing) { - $this->initializing = TRUE; - // @todo Objectify the language system so that we don't have to load an - // include file and call out to procedural code. See - // http://drupal.org/node/1862202 - include_once DRUPAL_ROOT . '/core/includes/language.inc'; - $this->languages[$type] = language_types_initialize($type, $this->request); - $this->initializing = FALSE; - } - else { - // Config has called getLanguage() during initialization of a language - // type. Simply return the default language without setting it on the - // $this->languages property. See the TODO in the docblock for the - // $initializing property. - return $this->getLanguageDefault(); - } - } - else { - $this->languages[$type] = $this->getLanguageDefault(); - } - return $this->languages[$type]; - } + // Filter the full list of languages based on the value of the $all flag. By + // default we remove the locked languages, but the caller may request for + // those languages to be added as well. + $filtered_languages = array(); - /** - * Resets the given language type or all types if none specified. - * - * @param string|null $type - * (optional) The language type to reset as a string, e.g., - * Language::TYPE_INTERFACE, or NULL to reset all language types. Defaults - * to NULL. - */ - public function reset($type = NULL) { - if (!isset($type)) { - $this->languages = array(); - $this->initialized = FALSE; + // Add the site's default language if flagged as allowed value. + if ($flags & Language::STATE_SITE_DEFAULT) { + $default = isset($default) ? $default : $this->getDefaultLanguage(); + // Rename the default language. + $default->name = t("Site's default language (@lang_name)", array('@lang_name' => $default->name)); + $filtered_languages['site_default'] = $default; } - elseif (isset($this->languages[$type])) { - unset($this->languages[$type]); + + foreach ($this->languageList as $id => $language) { + if (($language->locked && !($flags & Language::STATE_LOCKED)) || (!$language->locked && !($flags & Language::STATE_CONFIGURABLE))) { + continue; + } + $filtered_languages[$id] = $language; } + + return $filtered_languages; } /** - * Returns whether or not the site has more than one language enabled. - * - * @return bool - * TRUE if more than one language is enabled, FALSE otherwise. + * {@inheritdoc} */ - public function isMultilingual() { - if (!isset($this->state)) { - // No state service in install time. - return FALSE; - } - return ($this->state->get('language_count') ?: 1) > 1; + public function loadLanguage($langcode) { + $languages = $this->getLanguageList(Language::STATE_ALL); + return isset($languages[$langcode]) ? $languages[$langcode] : NULL; } /** - * Returns the language fallback candidates for a given context. - * - * @param string $langcode - * (optional) The language of the current context. Defaults to NULL. - * @param array $context - * (optional) An associative array of data that can be useful to determine - * the fallback sequence. The following keys are used in core: - * - langcode: The desired language. - * - operation: The name of the operation indicating the context where - * language fallback is being applied, e.g. 'entity_view'. - * - data: An arbitrary data structure that makes sense in the provided - * context, e.g. an entity. - * - * @return array - * An array of language codes sorted by priority: first values should be - * tried first. + * {@inheritdoc} */ - public function getFallbackCandidates($langcode = NULL, array $context = array()) { - if ($this->isMultilingual()) { - // Get languages ordered by weight, add Language::LANGCODE_NOT_SPECIFIED at - // the end. - $candidates = array_keys(language_list()); - $candidates[] = Language::LANGCODE_NOT_SPECIFIED; - $candidates = MapArray::copyValuesToKeys($candidates); + public function getDefaultLockedLanguages($weight = 0) { + $languages = array(); - // The first candidate should always be the desired language if specified. - if (!empty($langcode)) { - $candidates = array($langcode => $langcode) + $candidates; - } + $locked_language = array( + 'default' => FALSE, + 'locked' => TRUE, + 'enabled' => TRUE, + ); + $languages[Language::LANGCODE_NOT_SPECIFIED] = new Language(array( + 'id' => Language::LANGCODE_NOT_SPECIFIED, + 'name' => t('Not specified'), + 'weight' => ++$weight, + ) + $locked_language); - // Let other modules hook in and add/change candidates. - $type = 'language_fallback_candidates'; - $types = array(); - if (!empty($context['operation'])) { - $types[] = $type . '_' . $context['operation']; - } - $types[] = $type; - $this->moduleHandler->alter($types, $candidates, $context); - } - else { - $candidates = array(Language::LANGCODE_DEFAULT); - } + $languages[Language::LANGCODE_NOT_APPLICABLE] = new Language(array( + 'id' => Language::LANGCODE_NOT_APPLICABLE, + 'name' => t('Not applicable'), + 'weight' => ++$weight, + ) + $locked_language); - return $candidates; + return $languages; } /** - * Returns an array of the available language types. - * - * @return array() - * An array of all language types. + * {@inheritdoc} */ - protected function getLanguageTypes() { - return language_types_get_all(); + public function isLanguageLocked($langcode) { + $language = $this->loadLanguage($langcode); + return ($language ? $language->locked : FALSE); } /** - * Returns a language object representing the site's default language. - * - * @return \Drupal\Core\Language\Language - * A language object. + * {@inheritdoc} + */ + public function getFallbackCandidates($langcode = NULL, array $context = array()) { + return array(Language::LANGCODE_DEFAULT); + } + + /** + * {@inheritdoc} */ - protected function getLanguageDefault() { - $default_info = variable_get('language_default', array( - 'id' => 'en', - 'name' => 'English', - 'direction' => 0, - 'weight' => 0, - 'locked' => 0, - )); - $default_info['default'] = TRUE; - return new Language($default_info); + public function getLanguageSwitchLinks($type, $path) { + return array(); } /** @@ -275,24 +192,24 @@ public static function getStandardLanguageList() { 'ar' => array('Arabic', /* Left-to-right marker "‭" */ 'العربية', Language::DIRECTION_RTL), 'ast' => array('Asturian', 'Asturianu'), 'az' => array('Azerbaijani', 'Azərbaycanca'), - 'be' => array('Belarusian', 'Беларуская'), - 'bg' => array('Bulgarian', 'Български'), + 'be' => array('Belarusian', 'Белару?ка?'), + 'bg' => array('Bulgarian', 'Българ?ки'), 'bn' => array('Bengali', 'বাংলা'), - 'bo' => array('Tibetan', 'བོད་སྐད་'), + 'bo' => array('Tibetan', 'བོད་ས?ད་'), 'bs' => array('Bosnian', 'Bosanski'), 'ca' => array('Catalan', 'Català'), 'cs' => array('Czech', 'Čeština'), 'cy' => array('Welsh', 'Cymraeg'), 'da' => array('Danish', 'Dansk'), 'de' => array('German', 'Deutsch'), - 'dz' => array('Dzongkha', 'རྫོང་ཁ'), + 'dz' => array('Dzongkha', 'རྫོང་?'), 'el' => array('Greek', 'Ελληνικά'), 'en' => array('English', 'English'), 'eo' => array('Esperanto', 'Esperanto'), 'es' => array('Spanish', 'Español'), 'et' => array('Estonian', 'Eesti'), 'eu' => array('Basque', 'Euskera'), - 'fa' => array('Persian, Farsi', /* Left-to-right marker "‭" */ 'فارسی', Language::DIRECTION_RTL), + 'fa' => array('Persian, Farsi', /* Left-to-right marker "‭" */ '?ارسی', Language::DIRECTION_RTL), 'fi' => array('Finnish', 'Suomi'), 'fil' => array('Filipino', 'Filipino'), 'fo' => array('Faeroese', 'Føroyskt'), @@ -302,22 +219,22 @@ public static function getStandardLanguageList() { 'gd' => array('Scots Gaelic', 'Gàidhlig'), 'gl' => array('Galician', 'Galego'), 'gsw-berne' => array('Swiss German', 'Schwyzerdütsch'), - 'gu' => array('Gujarati', 'ગુજરાતી'), + 'gu' => array('Gujarati', 'ગ?જરાતી'), 'he' => array('Hebrew', /* Left-to-right marker "‭" */ 'עברית', Language::DIRECTION_RTL), - 'hi' => array('Hindi', 'हिन्दी'), + 'hi' => array('Hindi', 'हिन?दी'), 'hr' => array('Croatian', 'Hrvatski'), 'ht' => array('Haitian Creole', 'Kreyòl ayisyen'), 'hu' => array('Hungarian', 'Magyar'), 'hy' => array('Armenian', 'Հայերեն'), 'id' => array('Indonesian', 'Bahasa Indonesia'), - 'is' => array('Icelandic', 'Íslenska'), + 'is' => array('Icelandic', '?slenska'), 'it' => array('Italian', 'Italiano'), 'ja' => array('Japanese', '日本語'), 'jv' => array('Javanese', 'Basa Java'), - 'ka' => array('Georgian', 'ქართული ენა'), + 'ka' => array('Georgian', 'ქ?რთული ენ?'), 'kk' => array('Kazakh', 'Қазақ'), - 'km' => array('Khmer', 'ភាសាខ្មែរ'), - 'kn' => array('Kannada', 'ಕನ್ನಡ'), + 'km' => array('Khmer', 'ភាសា?្មែរ'), + 'kn' => array('Kannada', 'ಕನ?ನಡ'), 'ko' => array('Korean', '한국어'), 'ku' => array('Kurdish', 'Kurdî'), 'ky' => array('Kyrgyz', 'Кыргызча'), @@ -325,7 +242,7 @@ public static function getStandardLanguageList() { 'lt' => array('Lithuanian', 'Lietuvių'), 'lv' => array('Latvian', 'Latviešu'), 'mg' => array('Malagasy', 'Malagasy'), - 'mk' => array('Macedonian', 'Македонски'), + 'mk' => array('Macedonian', 'Македон?ки'), 'ml' => array('Malayalam', 'മലയാളം'), 'mn' => array('Mongolian', 'монгол'), 'mr' => array('Marathi', 'मराठी'), @@ -341,29 +258,29 @@ public static function getStandardLanguageList() { 'pt-pt' => array('Portuguese, Portugal', 'Português, Portugal'), 'pt-br' => array('Portuguese, Brazil', 'Português, Brasil'), 'ro' => array('Romanian', 'Română'), - 'ru' => array('Russian', 'Русский'), + 'ru' => array('Russian', 'Ру??кий'), 'sco' => array('Scots', 'Scots'), 'se' => array('Northern Sami', 'Sámi'), 'si' => array('Sinhala', 'සිංහල'), - 'sk' => array('Slovak', 'Slovenčina'), - 'sl' => array('Slovenian', 'Slovenščina'), + 'sk' => array('Slovak', 'Sloven?ina'), + 'sl' => array('Slovenian', 'Slovenš?ina'), 'sq' => array('Albanian', 'Shqip'), - 'sr' => array('Serbian', 'Српски'), + 'sr' => array('Serbian', 'Срп?ки'), 'sv' => array('Swedish', 'Svenska'), 'sw' => array('Swahili', 'Kiswahili'), - 'ta' => array('Tamil', 'தமிழ்'), - 'ta-lk' => array('Tamil, Sri Lanka', 'தமிழ், இலங்கை'), - 'te' => array('Telugu', 'తెలుగు'), + 'ta' => array('Tamil', 'தமிழ?'), + 'ta-lk' => array('Tamil, Sri Lanka', 'தமிழ?, இலங?கை'), + 'te' => array('Telugu', 'తెల?గ?'), 'th' => array('Thai', 'ภาษาไทย'), 'tr' => array('Turkish', 'Türkçe'), 'tyv' => array('Tuvan', 'Тыва дыл'), 'ug' => array('Uyghur', 'Уйғур'), - 'uk' => array('Ukrainian', 'Українська'), + 'uk' => array('Ukrainian', 'Україн?ька'), 'ur' => array('Urdu', /* Left-to-right marker "‭" */ 'اردو', Language::DIRECTION_RTL), 'vi' => array('Vietnamese', 'Tiếng Việt'), 'xx-lolspeak' => array('Lolspeak', 'Lolspeak'), 'zh-hans' => array('Chinese, Simplified', '简体中文'), - 'zh-hant' => array('Chinese, Traditional', '繁體中文'), + 'zh-hant' => array('Chinese, Traditional', '?體中文'), ); } diff --git a/core/lib/Drupal/Core/Language/LanguageManagerInterface.php b/core/lib/Drupal/Core/Language/LanguageManagerInterface.php new file mode 100644 index 0000000..86fbacf --- /dev/null +++ b/core/lib/Drupal/Core/Language/LanguageManagerInterface.php @@ -0,0 +1,146 @@ +languageManager = $language_manager; $this->cacheBackend = $cache_backend; $this->cacheKeyPrefix = $cache_key_prefix; diff --git a/core/modules/block/lib/Drupal/block/Tests/BlockLanguageTest.php b/core/modules/block/lib/Drupal/block/Tests/BlockLanguageTest.php index 2e4a4c6..e2bb9da 100644 --- a/core/modules/block/lib/Drupal/block/Tests/BlockLanguageTest.php +++ b/core/modules/block/lib/Drupal/block/Tests/BlockLanguageTest.php @@ -74,14 +74,13 @@ public function testLanguageBlockVisibility() { $this->drupalPostForm('admin/config/regional/settings', $edit, t('Save configuration')); // Reset the static cache of the language list. - drupal_static_reset('language_list'); - + $this->container->get('language_manager')->reset(); // Check that a page has a block. - $this->drupalget('', array('language' => language_load('en'))); + $this->drupalGet('en'); $this->assertText('Powered by Drupal', 'The body of the custom block appears on the page.'); // Check that a page doesn't has a block for the current language anymore. - $this->drupalGet('', array('language' => language_load('fr'))); + $this->drupalGet('fr'); $this->assertNoText('Powered by Drupal', 'The body of the custom block does not appear on the page.'); } diff --git a/core/modules/comment/lib/Drupal/comment/Tests/CommentLanguageTest.php b/core/modules/comment/lib/Drupal/comment/Tests/CommentLanguageTest.php index 9255b34..107f84f 100644 --- a/core/modules/comment/lib/Drupal/comment/Tests/CommentLanguageTest.php +++ b/core/modules/comment/lib/Drupal/comment/Tests/CommentLanguageTest.php @@ -83,7 +83,6 @@ function setUp() { * Test that comment language is properly set. */ function testCommentLanguage() { - drupal_static_reset('language_list'); // Create two nodes, one for english and one for french, and comment each // node using both english and french as content language by changing URL diff --git a/core/modules/config_translation/lib/Drupal/config_translation/ConfigMapperManager.php b/core/modules/config_translation/lib/Drupal/config_translation/ConfigMapperManager.php index edb431c..4331d6f 100644 --- a/core/modules/config_translation/lib/Drupal/config_translation/ConfigMapperManager.php +++ b/core/modules/config_translation/lib/Drupal/config_translation/ConfigMapperManager.php @@ -13,7 +13,7 @@ use Drupal\Core\Config\Schema\ArrayElement; use Drupal\Core\Config\TypedConfigManager; use Drupal\Core\Extension\ModuleHandlerInterface; -use Drupal\Core\Language\LanguageManager; +use Drupal\Core\Language\LanguageManagerInterface; use Drupal\Core\Plugin\DefaultPluginManager; use Drupal\Core\Plugin\Discovery\InfoHookDecorator; use Drupal\Core\Plugin\Discovery\YamlDiscovery; @@ -49,14 +49,14 @@ class ConfigMapperManager extends DefaultPluginManager implements ConfigMapperMa * * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend * The cache backend. - * @param \Drupal\Core\Language\LanguageManager $language_manager + * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager * The language manager. * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler * The module handler. * @param \Drupal\Core\Config\TypedConfigManager $typed_config_manager * The typed config manager. */ - public function __construct(CacheBackendInterface $cache_backend, LanguageManager $language_manager, ModuleHandlerInterface $module_handler, TypedConfigManager $typed_config_manager) { + public function __construct(CacheBackendInterface $cache_backend, LanguageManagerInterface $language_manager, ModuleHandlerInterface $module_handler, TypedConfigManager $typed_config_manager) { $this->typedConfigManager = $typed_config_manager; // Look at all themes and modules. diff --git a/core/modules/config_translation/tests/Drupal/config_translation/Tests/ConfigMapperManagerTest.php b/core/modules/config_translation/tests/Drupal/config_translation/Tests/ConfigMapperManagerTest.php index b07e542..d13dde9 100644 --- a/core/modules/config_translation/tests/Drupal/config_translation/Tests/ConfigMapperManagerTest.php +++ b/core/modules/config_translation/tests/Drupal/config_translation/Tests/ConfigMapperManagerTest.php @@ -47,7 +47,7 @@ public static function getInfo() { public function setUp() { $language = new Language(array('id' => 'en')); - $language_manager = $this->getMock('Drupal\Core\Language\LanguageManager'); + $language_manager = $this->getMock('Drupal\Core\Language\LanguageManagerInterface'); $language_manager->expects($this->once()) ->method('getLanguage') ->with(Language::TYPE_INTERFACE) diff --git a/core/modules/content_translation/content_translation.install b/core/modules/content_translation/content_translation.install index bd817bc..7ec5f1a 100644 --- a/core/modules/content_translation/content_translation.install +++ b/core/modules/content_translation/content_translation.install @@ -6,6 +6,7 @@ */ use Drupal\Core\Language\Language; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl; /** * Implements hook_schema(). @@ -85,8 +86,7 @@ function content_translation_install() { // Assign a fairly low weight to ensure our implementation of // hook_module_implements_alter() is run among the last ones. module_set_weight('content_translation', 10); - language_negotiation_include(); - language_negotiation_set(Language::TYPE_CONTENT, array(LANGUAGE_NEGOTIATION_URL => 0)); + language_negotiation_set(Language::TYPE_CONTENT, array(LanguageNegotiationUrl::METHOD_ID => 0)); } /** diff --git a/core/modules/language/language.admin.inc b/core/modules/language/language.admin.inc index f9443c7..55ed837 100644 --- a/core/modules/language/language.admin.inc +++ b/core/modules/language/language.admin.inc @@ -6,6 +6,7 @@ */ use Drupal\Core\Language\LanguageManager; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationSelected; /** * Prepare a language code list for unused predefined languages. @@ -30,7 +31,6 @@ function language_admin_predefined_list() { * @deprecated Use \Drupal\language\Form\LanguageForm::negotiation() */ function language_negotiation_configure_form() { - language_negotiation_include(); $form = array( '#submit' => array('language_negotiation_configure_form_submit'), @@ -138,7 +138,7 @@ function language_negotiation_configure_form_table(&$form, $type) { '#title_display' => 'invisible', '#default_value' => $enabled, ); - if ($method_id === LANGUAGE_NEGOTIATION_SELECTED) { + if ($method_id === LanguageNegotiationSelected::METHOD_ID) { $table_form['enabled'][$method_id]['#default_value'] = TRUE; $table_form['enabled'][$method_id]['#attributes'] = array('disabled' => 'disabled'); } @@ -246,7 +246,7 @@ function language_negotiation_configure_form_submit($form, &$form_state) { $customized[$type] = in_array($type, $stored_values); $method_weights = array(); $enabled_methods = $form_state['values'][$type]['enabled']; - $enabled_methods[LANGUAGE_NEGOTIATION_SELECTED] = TRUE; + $enabled_methods[LanguageNegotiationSelected::METHOD_ID] = TRUE; $method_weights_input = $form_state['values'][$type]['weight']; if (isset($form_state['values'][$type]['configurable'])) { $customized[$type] = !empty($form_state['values'][$type]['configurable']); @@ -281,6 +281,9 @@ function language_negotiation_configure_form_submit($form, &$form_state) { \Drupal::service('plugin.manager.block')->clearCachedDefinitions(); } + // Rebuild the container to update the submitted settings. + language_negotiation_rebuild_settings(); + $form_state['redirect_route']['route_name'] = 'language.negotiation'; drupal_set_message(t('Language negotiation configuration saved.')); } diff --git a/core/modules/language/language.api.php b/core/modules/language/language.api.php index d0a31c4..4149476 100644 --- a/core/modules/language/language.api.php +++ b/core/modules/language/language.api.php @@ -66,7 +66,7 @@ function hook_language_delete($language) { * @param array $context * A language fallback context. * - * @see \Drupal\Core\Language\LanguageManager::getFallbackCandidates() + * @see \Drupal\Core\Language\LanguageManagerInterface::getFallbackCandidates() */ function hook_language_fallback_candidates_alter(array &$candidates, array $context) { $candidates = array_reverse($candidates); @@ -81,7 +81,7 @@ function hook_language_fallback_candidates_alter(array &$candidates, array $cont * @param array $context * A language fallback context. * - * @see \Drupal\Core\Language\LanguageManager::getFallbackCandidates() + * @see \Drupal\Core\Language\LanguageManagerInterface::getFallbackCandidates() */ function hook_language_fallback_candidates_OPERATION_alter(array &$candidates, array $context) { // We know that the current OPERATION deals with entities so no need to check diff --git a/core/modules/language/language.install b/core/modules/language/language.install index 5103389..137e7c3 100644 --- a/core/modules/language/language.install +++ b/core/modules/language/language.install @@ -6,6 +6,7 @@ */ use Drupal\Core\Language\Language; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl; /** * Implements hook_install(). @@ -15,10 +16,9 @@ */ function language_install() { // Enable URL language detection for each configurable language type. - require_once DRUPAL_ROOT . '/core/includes/language.inc'; foreach (language_types_get_configurable() as $type) { module_load_include('inc', 'language', 'language.negotiation'); - language_negotiation_set($type, array(LANGUAGE_NEGOTIATION_URL => 0)); + language_negotiation_set($type, array(LanguageNegotiationUrl::METHOD_ID => 0)); } // Update the language count. @@ -31,12 +31,9 @@ function language_install() { function language_uninstall() { // Clear variables. variable_del('language_default'); - \Drupal::state()->delete('language_count'); // Clear variables. - variable_del('language_types'); - - foreach (language_types_get_all() as $type) { + foreach (Drupal::languageManager()->getLanguageTypes() as $type) { variable_del("language_negotiation_$type"); variable_del("language_negotiation_methods_weight_$type"); } @@ -44,19 +41,4 @@ function language_uninstall() { // Re-initialize the language system so successive calls to t() and other // functions will not expect languages to be present. drupal_language_initialize(); - - // Force the language_count state to be 1, so that when checking if the - // site is multilingual (for example in language_multilingual()), the result - // will be FALSE, because the language module is not installed. - \Drupal::state()->set('language_count', 1); -} - -/** - * Implements hook_requirements(). - */ -function language_requirements($phase) { - if ($phase == 'update') { - // Load the include files to make constants available for updates. - language_negotiation_include(); - } } diff --git a/core/modules/language/language.module b/core/modules/language/language.module index b0dd216..36613df 100644 --- a/core/modules/language/language.module +++ b/core/modules/language/language.module @@ -5,8 +5,12 @@ * Add language handling functionality to Drupal. */ -use Drupal\node\NodeTypeInterface; +use Drupal\Component\PhpStorage\PhpStorageFactory; use Drupal\Core\Language\Language; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUI; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrlFallback; +use Drupal\node\NodeTypeInterface; /** * Implements hook_help(). @@ -466,8 +470,8 @@ function language_save($language) { variable_set('language_default', (array) $language); } - // Kill the static cache in language_list(). - drupal_static_reset('language_list'); + // Reset the language information. + Drupal::languageManager()->reset(); // Update language count based on unlocked language count. language_update_count(); @@ -475,8 +479,6 @@ function language_save($language) { // Update weight of locked system languages. language_update_locked_weights(); - language_negotiation_include(); - // Update URL Prefixes for all languages after the new default language is // propagated and the language_list() cache is flushed. language_negotiation_url_prefixes_update(); @@ -498,7 +500,6 @@ function language_update_count() { $count++; } } - \Drupal::state()->set('language_count', $count); } /** @@ -520,13 +521,13 @@ function language_delete($langcode) { // Remove the language. entity_delete_multiple('language_entity', array($language->id)); - drupal_static_reset('language_list'); - language_update_count(); // Update weight of locked system languages. language_update_locked_weights(); + Drupal::languageManager()->reset(); + $t_args = array('%language' => $language->name, '%langcode' => $language->id); watchdog('language', 'The %language (%langcode) language has been removed.', $t_args); return TRUE; @@ -569,8 +570,6 @@ function language_library_info() { * language if none is specified. */ function language_language_types_info() { - language_negotiation_include(); - return array( Language::TYPE_INTERFACE => array( 'name' => t('User interface text'), @@ -580,111 +579,236 @@ function language_language_types_info() { Language::TYPE_CONTENT => array( 'name' => t('Content'), 'description' => t('Order of language detection methods for content. If a version of content is available in the detected language, it will be displayed.'), - 'fixed' => array(LANGUAGE_NEGOTIATION_INTERFACE), + 'fixed' => array(LanguageNegotiationUI::METHOD_ID), 'locked' => TRUE, ), Language::TYPE_URL => array( - 'fixed' => array(LANGUAGE_NEGOTIATION_URL, LANGUAGE_NEGOTIATION_URL_FALLBACK), + 'fixed' => array(LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationUrlFallback::METHOD_ID), 'locked' => TRUE, ), ); } /** - * Implements hook_language_negotiation_info(). + * Updates the language type configuration. + * + * @param array $configurable_language_types + * An array of configurable language types. + */ +function language_types_set(array $configurable_language_types) { + // Ensure that we are getting the defined language negotiation information. An + // invocation of \Drupal\Core\Extension\ModuleHandler::install() or + // \Drupal\Core\Extension\ModuleHandler::uninstall() could invalidate the + // cached information. + \Drupal::service('plugin.manager.language_negotiation_method')->clearCachedDefinitions(); + drupal_static_reset('language_types_info'); + + $language_types = array(); + $negotiation_info = language_negotiation_info(); + $language_types_info = language_types_info(); + + foreach ($language_types_info as $type => $info) { + $configurable = in_array($type, $configurable_language_types); + + // Check whether the language type is unlocked. Only the status of unlocked + // language types can be toggled between configurable and non-configurable. + // The default language negotiation settings, if available, are stored in + // $info['fixed']. + if (empty($info['locked'])) { + // If we have a non-locked non-configurable language type without default + // language negotiation settings, we use the values negotiated for the + // interface language which should always be available. + if (!$configurable && !empty($info['fixed'])) { + $method_weights = array(LanguageNegotiationUI::METHOD_ID); + $method_weights = array_flip($method_weights); + language_negotiation_set($type, $method_weights); + } + } + else { + // Locked language types with default settings are always considered + // non-configurable. In turn if default settings are missing, the language + // type is always considered configurable. + $configurable = empty($info['fixed']); + + // If the language is non-configurable we need to store its language + // negotiation settings. + if (!$configurable) { + $method_weights = array(); + foreach ($info['fixed'] as $weight => $method_id) { + if (isset($negotiation_info[$method_id])) { + $method_weights[$method_id] = $weight; + } + } + language_negotiation_set($type, $method_weights); + } + } + + $language_types[$type] = $configurable; + } + + // Store the language type configuration. + $config = \Drupal::config('system.language.types'); + $config->set('configurable', array_keys(array_filter($language_types)))->save(); + $config->set('all', array_keys($language_types))->save(); +} + +/** + * Disables the given language types. + * + * @param $types + * An array of language types. */ -function language_language_negotiation_info() { - language_negotiation_include(); - $file = drupal_get_path('module', 'language') . '/language.negotiation.inc'; +function language_types_disable($types) { + $configurable = language_types_get_configurable(); + \Drupal::config('system.language.types')->set('configurable', array_diff($configurable, $types))->save(); +} - $negotiation_info = array(); - $negotiation_info[LANGUAGE_NEGOTIATION_URL] = array( - 'types' => array(Language::TYPE_CONTENT, Language::TYPE_INTERFACE, Language::TYPE_URL), - 'callbacks' => array( - 'negotiation' => 'language_from_url', - 'language_switch' => 'language_switcher_url', - ), - 'file' => $file, - 'weight' => -8, - 'name' => t('URL'), - 'description' => t('Language from the URL (Path prefix or domain).'), - 'config' => 'admin/config/regional/language/detection/url', - ); +/** + * Resave all negotiation configuration to purge missing negotiation methods. + */ +function language_negotiation_purge() { + // Ensure that we are getting the defined language negotiation information. An + // invocation of \Drupal\Core\Extension\ModuleHandler::install() or + // \Drupal\Core\Extension\ModuleHandler::uninstall() could invalidate the + // cached information. + Drupal::service('plugin.manager.language_negotiation_method')->clearCachedDefinitions(); + drupal_static_reset('language_types_info'); + foreach (language_types_info() as $type => $type_info) { + language_negotiation_set($type, variable_get("language_negotiation_$type", array())); + } +} - $negotiation_info[LANGUAGE_NEGOTIATION_SESSION] = array( - 'callbacks' => array( - 'negotiation' => 'language_from_session', - 'language_switch' => 'language_switcher_session', - 'url_rewrite' => 'language_url_rewrite_session', - ), - 'file' => $file, - 'weight' => -6, - 'name' => t('Session'), - 'description' => t('Language from a request/session parameter.'), - 'config' => 'admin/config/regional/language/detection/session', - ); +/** + * Saves a list of language negotiation methods for a language type. + * + * @param $type + * The language type. + * @param $method_weights + * An array of language negotiation method weights keyed by method ID. + */ +function language_negotiation_set($type, $method_weights) { + $negotiation_info = language_negotiation_info(); + $default_types = language_types_get_configurable(); + + // Order the language negotiation method list by weight. + asort($method_weights); + foreach ($method_weights as $method_id => $weight) { + if (isset($negotiation_info[$method_id])) { + $method = $negotiation_info[$method_id]; + // If the language negotiation method does not express any preference + // about types, make it available for any configurable type. + $types = array_flip(!empty($method['types']) ? $method['types'] : $default_types); + // Check whether the method is defined and has the right type. + if (!isset($types[$type])) { + unset($method_weights[$method_id]); + } + } + else { + unset($method_weights[$method_id]); + } + } + variable_set("language_negotiation_$type", $method_weights); +} - $negotiation_info[LANGUAGE_NEGOTIATION_USER] = array( - 'callbacks' => array('negotiation' => 'language_from_user'), - 'file' => $file, - 'weight' => -4, - 'name' => t('Account preference for site'), - 'description' => t("The language setting for the site in the user's account."), - ); +/** + * Rebuild the container to store updated language negotiation settings. + */ +function language_negotiation_rebuild_settings() { + \Drupal::service('plugin.manager.language_negotiation_method')->clearCachedDefinitions(); + PhpStorageFactory::get('service_container')->deleteAll(); +} - $negotiation_info[LANGUAGE_NEGOTIATION_BROWSER] = array( - 'callbacks' => array('negotiation' => 'language_from_browser'), - 'file' => $file, - 'weight' => -2, - 'cache' => 0, - 'name' => t('Browser'), - 'description' => t("Language from the browser's language settings."), - 'config' => 'admin/config/regional/language/detection/browser', - ); +/** + * Returns the ID of the language type's first language negotiation method. + * + * @param $type + * The language type. + * + * @return + * The identifier of the first language negotiation method for the given + * language type, or the default method if none exists. + * + * @deprecated as of 8.0, use + * \Drupal::languageManager()->getFirstNegotiationMethod() instead. + */ +function language_negotiation_method_get_first($type) { + return \Drupal::service('language_negotiator')->getPrimaryNegotiationMethod($type); +} - $negotiation_info[LANGUAGE_NEGOTIATION_INTERFACE] = array( - 'types' => array(Language::TYPE_CONTENT), - 'callbacks' => array('negotiation' => 'language_from_interface'), - 'file' => $file, - 'weight' => 8, - 'name' => t('Interface'), - 'description' => t('Use the detected interface language.'), - ); +/** + * Checks whether a language negotiation method is enabled for a language type. + * + * @param $method_id + * The language negotiation method ID. + * @param $type + * (optional) The language type. If none is passed, all the configurable + * language types will be inspected. + * + * @return + * TRUE if the method is enabled for at least one of the given language + * types, or FALSE otherwise. + * + * @deprecated as of 8.0, use + * \Drupal::languageManager()->isNegotiationMethodEnabled() instead. + */ +function language_negotiation_method_enabled($method_id, $type = NULL) { + return \Drupal::service('language_negotiator')->isNegotiationMethodEnabled($method_id, $type); +} - $negotiation_info[LANGUAGE_NEGOTIATION_URL_FALLBACK] = array( - 'types' => array(Language::TYPE_URL), - 'callbacks' => array('negotiation' => 'language_url_fallback'), - 'file' => $file, - 'weight' => 8, - 'name' => t('URL fallback'), - 'description' => t('Use an already detected language for URLs if none is found.'), - ); +/** + * Reads language prefixes and uses the langcode if no prefix is set. + */ +function language_negotiation_url_prefixes() { + return \Drupal::config('language.negotiation')->get('url.prefixes'); +} - $negotiation_info[LANGUAGE_NEGOTIATION_USER_ADMIN] = array( - 'types' => array(Language::TYPE_INTERFACE), - 'callbacks' => array('negotiation' => 'language_from_user_admin'), - 'file' => $file, - 'weight' => 10, - 'name' => t('Account preference for administration pages'), - 'description' => t("The language setting for account administration pages in the user's account."), - ); +/** + * Update the list of prefixes from the installed languages. + */ +function language_negotiation_url_prefixes_update() { + $prefixes = language_negotiation_url_prefixes(); + foreach (language_list() as $language) { + // The prefix for this language should be updated if it's not assigned yet + // or the prefix is set to the empty string. + if (empty($prefixes[$language->id])) { + // For the default language, set the prefix to the empty string, + // otherwise use the langcode. + $prefixes[$language->id] = !empty($language->default) ? '' : $language->id; + } + // Otherwise we keep the configured prefix. + } + language_negotiation_url_prefixes_save($prefixes); +} - return $negotiation_info; +/** + * Saves language prefix settings. + */ +function language_negotiation_url_prefixes_save(array $prefixes) { + \Drupal::config('language.negotiation') + ->set('url.prefixes', $prefixes) + ->save(); } /** - * Include negotiation backend functionality. + * Reads language domains. */ -function language_negotiation_include() { - include_once DRUPAL_ROOT . '/core/includes/language.inc'; - include_once __DIR__ . '/language.negotiation.inc'; +function language_negotiation_url_domains() { + return \Drupal::config('language.negotiation')->get('url.domains'); +} + +/** + * Saves the language domain settings. + */ +function language_negotiation_url_domains_save(array $domains) { + \Drupal::config('language.negotiation') + ->set('url.domains', $domains) + ->save(); } /** * Implements hook_modules_installed(). */ function language_modules_installed($modules) { - include_once DRUPAL_ROOT . '/core/includes/language.inc'; // Load configurability options from configuration. language_types_set(array()); language_negotiation_purge(); @@ -705,8 +829,6 @@ function language_language_insert($language) { return; } - language_negotiation_include(); - // Add language to the list of language domains. $domains = language_negotiation_url_domains(); $domains[$language->id] = ''; @@ -717,8 +839,6 @@ function language_language_insert($language) { * Implements hook_language_delete(). */ function language_language_delete($language) { - language_negotiation_include(); - // Remove language from language prefix list. $prefixes = language_negotiation_url_prefixes(); unset($prefixes[$language->id]); @@ -823,4 +943,5 @@ function language_system_regional_settings_form_submit($form, &$form_state) { $language = $languages[$form_state['values']['site_default_language']]; $language->default = TRUE; language_save($language); + language_negotiation_rebuild_settings(); } diff --git a/core/modules/language/language.negotiation.inc b/core/modules/language/language.negotiation.inc deleted file mode 100644 index f87284d..0000000 --- a/core/modules/language/language.negotiation.inc +++ /dev/null @@ -1,529 +0,0 @@ -id; -} - -/** - * Identify language from the Accept-language HTTP header we got. - * - * The algorithm works as follows: - * - map browser language codes to Drupal language codes. - * - order all browser language codes by qvalue from high to low. - * - add generic browser language codes if they aren't already specified - * but with a slightly lower qvalue. - * - find the most specific Drupal language code with the highest qvalue. - * - if 2 or more languages are having the same qvalue, respect the order of - * them inside the $languages array. - * - * We perform browser accept-language parsing only if page cache is disabled, - * otherwise we would cache a user-specific preference. - * - * @param $languages - * An array of language objects for enabled languages ordered by weight. - * - * @return - * A valid language code on success, FALSE otherwise. - */ -function language_from_browser($languages) { - $accept_language = \Drupal::request()->server->get('HTTP_ACCEPT_LANGUAGE'); - if (empty($accept_language)) { - return FALSE; - } - - // The Accept-Language header contains information about the language - // preferences configured in the user's browser / operating system. RFC 2616 - // (section 14.4) defines the Accept-Language header as follows: - // Accept-Language = "Accept-Language" ":" - // 1#( language-range [ ";" "q" "=" qvalue ] ) - // language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" ) - // Samples: "hu, en-us;q=0.66, en;q=0.33", "hu,en-us;q=0.5" - $browser_langcodes = array(); - if (preg_match_all('@(?<=[, ]|^)([a-zA-Z-]+|\*)(?:;q=([0-9.]+))?(?:$|\s*,\s*)@', trim($accept_language), $matches, PREG_SET_ORDER)) { - // Load custom mappings to support browsers that are sending non standard - // language codes. - $mappings = language_get_browser_drupal_langcode_mappings(); - foreach ($matches as $match) { - if ($mappings) { - $langcode = strtolower($match[1]); - foreach ($mappings as $browser_langcode => $drupal_langcode) { - if ($langcode == $browser_langcode) { - $match[1] = $drupal_langcode; - } - } - } - // We can safely use strtolower() here, tags are ASCII. - // RFC2616 mandates that the decimal part is no more than three digits, - // so we multiply the qvalue by 1000 to avoid floating point comparisons. - $langcode = strtolower($match[1]); - $qvalue = isset($match[2]) ? (float) $match[2] : 1; - // Take the highest qvalue for this langcode. Although the request - // supposedly contains unique langcodes, our mapping possibly resolves - // to the same langcode for different qvalues. Keep the highest. - $browser_langcodes[$langcode] = max( - (int) ($qvalue * 1000), - (isset($browser_langcodes[$langcode]) ? $browser_langcodes[$langcode] : 0) - ); - } - } - - // We should take pristine values from the HTTP headers, but Internet Explorer - // from version 7 sends only specific language tags (eg. fr-CA) without the - // corresponding generic tag (fr) unless explicitly configured. In that case, - // we assume that the lowest value of the specific tags is the value of the - // generic language to be as close to the HTTP 1.1 spec as possible. - // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 and - // http://blogs.msdn.com/b/ie/archive/2006/10/17/accept-language-header-for-internet-explorer-7.aspx - asort($browser_langcodes); - foreach ($browser_langcodes as $langcode => $qvalue) { - // For Chinese languages the generic tag is either zh-hans or zh-hant, so we - // need to handle this separately, we can not split $langcode on the - // first occurrence of '-' otherwise we get a non-existing language zh. - // All other languages use a langcode without a '-', so we can safely split - // on the first occurrence of it. - $generic_tag = ''; - if (strlen($langcode) > 7 && (substr($langcode, 0, 7) == 'zh-hant' || substr($langcode, 0, 7) == 'zh-hans')) { - $generic_tag = substr($langcode, 0, 7); - } - else { - $generic_tag = strtok($langcode, '-'); - } - if (!empty($generic_tag) && !isset($browser_langcodes[$generic_tag])) { - // Add the generic langcode, but make sure it has a lower qvalue as the - // more specific one, so the more specific one gets selected if it's - // defined by both the browser and Drupal. - $browser_langcodes[$generic_tag] = $qvalue - 0.1; - } - } - - // Find the enabled language with the greatest qvalue, following the rules of - // RFC 2616 (section 14.4). If several languages have the same qvalue, prefer - // the one with the greatest weight. - $best_match_langcode = FALSE; - $max_qvalue = 0; - foreach ($languages as $langcode => $language) { - // Language tags are case insensitive (RFC2616, sec 3.10). - $langcode = strtolower($langcode); - - // If nothing matches below, the default qvalue is the one of the wildcard - // language, if set, or is 0 (which will never match). - $qvalue = isset($browser_langcodes['*']) ? $browser_langcodes['*'] : 0; - - // Find the longest possible prefix of the browser-supplied language ('the - // language-range') that matches this site language ('the language tag'). - $prefix = $langcode; - do { - if (isset($browser_langcodes[$prefix])) { - $qvalue = $browser_langcodes[$prefix]; - break; - } - } - while ($prefix = substr($prefix, 0, strrpos($prefix, '-'))); - - // Find the best match. - if ($qvalue > $max_qvalue) { - $best_match_langcode = $language->id; - $max_qvalue = $qvalue; - } - } - - return $best_match_langcode; -} - -/** - * Identify language from the user preferences. - * - * @param $languages - * An array of valid language objects. - * - * @return - * A valid language code on success, FALSE otherwise. - */ -function language_from_user($languages) { - // User preference (only for authenticated users). - $user = \Drupal::currentUser(); - - if ($user->id()) { - $langcode = $user->getPreferredLangcode(); - $default_langcode = language_default()->id; - if (!empty($langcode) && $langcode != $default_langcode && isset($languages[$langcode])) { - return $langcode; - } - } - - // No language preference from the user. - return FALSE; -} - -/** - * Identifies admin language from the user preferences. - * - * @param $languages - * An array of valid language objects. - * - * @param \Symfony\Component\HttpFoundation\Request|null $request - * (optional) The HttpRequest object representing the current request. - * Defaults to NULL. - * - * @return - * A valid language code on success, FALSE otherwise. - */ -function language_from_user_admin(array $languages, Request $request = NULL) { - // User preference (only for authenticated users). - $user = \Drupal::currentUser(); - - if ($user->id()) { - $request_path = $request ? urldecode(trim($request->getPathInfo(), '/')) : _current_path(); - $langcode = $user->getPreferredAdminLangcode(); - $default_langcode = language_default()->id; - if (!empty($langcode) && $langcode != $default_langcode && isset($languages[$langcode]) && path_is_admin($request_path)) { - return $langcode; - } - } - - // No language preference from the user or not on an admin path. - return FALSE; -} - -/** - * Identify language from a request/session parameter. - * - * @param $languages - * An array of valid language objects. - * - * @return - * A valid language code on success, FALSE otherwise. - */ -function language_from_session($languages) { - $param = \Drupal::config('language.negotiation')->get('session.parameter'); - $query = \Drupal::request()->query; - - // Request parameter: we need to update the session parameter only if we have - // an authenticated user. - if ($query->has($param) && isset($languages[$langcode = $query->get($param)])) { - $user = \Drupal::currentUser(); - if ($user->id()) { - $_SESSION[$param] = $langcode; - } - return $langcode; - } - - // Session parameter. - if (isset($_SESSION[$param])) { - return $_SESSION[$param]; - } - - return FALSE; -} - -/** - * Identify language via URL prefix or domain. - * - * @param $languages - * An array of valid language objects. - * - * @param \Symfony\Component\HttpFoundation\Request|null $request - * (optional) The HttpRequest object representing the current request. - * Defaults to NULL. - * - * @return - * A valid language code on success, FALSE otherwise. - */ -function language_from_url($languages, Request $request = NULL) { - $language_url = FALSE; - - if (!language_negotiation_method_enabled(LANGUAGE_NEGOTIATION_URL) || !$request) { - return $language_url; - } - - switch (\Drupal::config('language.negotiation')->get('url.source')) { - case LANGUAGE_NEGOTIATION_URL_PREFIX: - - $request_path = urldecode(trim($request->getPathInfo(), '/')); - list($language, $path) = language_url_split_prefix($request_path, $languages); - - if ($language !== FALSE) { - $language_url = $language->id; - } - break; - - case LANGUAGE_NEGOTIATION_URL_DOMAIN: - // Get only the host, not the port. - $http_host= \Drupal::request()->server->get('HTTP_HOST'); - if (strpos($http_host, ':') !== FALSE) { - $http_host_tmp = explode(':', $http_host); - $http_host = current($http_host_tmp); - } - $domains = language_negotiation_url_domains(); - foreach ($languages as $language) { - // Skip the check if the language doesn't have a domain. - if (!empty($domains[$language->id])) { - // Ensure that there is exactly one protocol in the URL when checking - // the hostname. - $host = 'http://' . str_replace(array('http://', 'https://'), '', $domains[$language->id]); - $host = parse_url($host, PHP_URL_HOST); - if ($http_host == $host) { - $language_url = $language->id; - break; - } - } - } - break; - } - - return $language_url; -} - -/** - * Determines the language to be assigned to URLs when none is detected. - * - * The language negotiation process has a fallback chain that ends with the - * default language negotiation method. Each built-in language type has a - * separate initialization: - * - Interface language, which is the only configurable one, always gets a valid - * value. If no request-specific language is detected, the default language - * will be used. - * - Content language merely inherits the interface language by default. - * - URL language is detected from the requested URL and will be used to rewrite - * URLs appearing in the page being rendered. If no language can be detected, - * there are two possibilities: - * - If the default language has no configured path prefix or domain, then the - * default language is used. This guarantees that (missing) URL prefixes are - * preserved when navigating through the site. - * - If the default language has a configured path prefix or domain, a - * requested URL having an empty prefix or domain is an anomaly that must be - * fixed. This is done by introducing a prefix or domain in the rendered - * page matching the detected interface language. - * - * @param $languages - * (optional) An array of valid language objects. This is passed by - * language_negotiation_method_invoke() to every language method callback, - * but it is not actually needed here. Defaults to NULL. - * - * @param $request - * (optional) The HttpRequest object representing the current request. - * - * @param $language_type - * (optional) The language type to fall back to. Defaults to the interface - * language. - * - * @return - * A valid language code. - */ -function language_url_fallback($language = NULL, $request = NULL, $language_type = Language::TYPE_INTERFACE) { - $default = language_default(); - $prefix = (\Drupal::config('language.negotiation')->get('url.source') == LANGUAGE_NEGOTIATION_URL_PREFIX); - - // If the default language is not configured to convey language information, - // a missing URL language information indicates that URL language should be - // the default one, otherwise we fall back to an already detected language. - $domains = language_negotiation_url_domains(); - $prefixes = language_negotiation_url_prefixes(); - if (($prefix && empty($prefixes[$default->id])) || (!$prefix && empty($domains[$default->id]))) { - return $default->id; - } - else { - $langcode = language($language_type)->id; - return $langcode; - } -} - -/** - * Return links for the URL language switcher block. - * - * Translation links may be provided by other modules. - */ -function language_switcher_url($type, $path) { - $languages = language_list(); - $links = array(); - - foreach ($languages as $language) { - $links[$language->id] = array( - 'href' => $path, - 'title' => $language->name, - 'language' => $language, - 'attributes' => array('class' => array('language-link')), - ); - } - - return $links; -} - -/** - * Return the session language switcher block. - */ -function language_switcher_session($type, $path) { - $param = \Drupal::config('language.negotiation')->get('session.parameter'); - $language_query = isset($_SESSION[$param]) ? $_SESSION[$param] : language($type)->id; - - $languages = language_list(); - $links = array(); - - $query = \Drupal::request()->query->all(); - - foreach ($languages as $language) { - $langcode = $language->id; - $links[$langcode] = array( - 'href' => $path, - 'title' => $language->name, - 'attributes' => array('class' => array('language-link')), - 'query' => $query, - ); - if ($language_query != $langcode) { - $links[$langcode]['query'][$param] = $langcode; - } - else { - $links[$langcode]['attributes']['class'][] = ' session-active'; - } - } - - return $links; -} - -/** - * Reads language prefixes and uses the langcode if no prefix is set. - */ -function language_negotiation_url_prefixes() { - return \Drupal::config('language.negotiation')->get('url.prefixes'); -} - -/** - * Update the list of prefixes from the installed languages. - */ -function language_negotiation_url_prefixes_update() { - $prefixes = language_negotiation_url_prefixes(); - foreach (language_list() as $language) { - // The prefix for this language should be updated if it's not assigned yet - // or the prefix is set to the empty string. - if (empty($prefixes[$language->id])) { - // For the default language, set the prefix to the empty string, - // otherwise use the langcode. - $prefixes[$language->id] = !empty($language->default) ? '' : $language->id; - } - // Otherwise we keep the configured prefix. - } - language_negotiation_url_prefixes_save($prefixes); -} - -/** - * Saves language prefix settings. - */ -function language_negotiation_url_prefixes_save(array $prefixes) { - \Drupal::config('language.negotiation') - ->set('url.prefixes', $prefixes) - ->save(); -} - -/** - * Reads language domains. - */ -function language_negotiation_url_domains() { - return \Drupal::config('language.negotiation')->get('url.domains'); -} - -/** - * Saves the language domain settings. - */ -function language_negotiation_url_domains_save(array $domains) { - \Drupal::config('language.negotiation') - ->set('url.domains', $domains) - ->save(); -} - -/** - * Rewrite URLs for the Session language negotiation method. - */ -function language_url_rewrite_session(&$path, &$options) { - static $query_rewrite, $query_param, $query_value; - - // The following values are not supposed to change during a single page - // request processing. - if (!isset($query_rewrite)) { - $user = \Drupal::currentUser(); - if (!$user->id()) { - $languages = language_list(); - $query_param = String::checkPlain(\Drupal::config('language.negotiation')->get('session.parameter')); - $query = \Drupal::request()->query; - if ($query->has($query_param)) { - $query_value = String::checkPlain(\Drupal::request()->query->get($query_param)); - } - else { - return FALSE; - } - $query_rewrite = isset($languages[$query_value]) && language_negotiation_method_enabled(LANGUAGE_NEGOTIATION_SESSION); - } - else { - $query_rewrite = FALSE; - } - } - - // If the user is anonymous, the user language negotiation method is enabled, - // and the corresponding option has been set, we must preserve any explicit - // user language preference even with cookies disabled. - if ($query_rewrite) { - if (is_string($options['query'])) { - $query = array(); - parse_str($options['query'], $query); - $options['query'] = $query; - } - if (!isset($options['query'][$query_param])) { - $options['query'][$query_param] = $query_value; - } - } -} diff --git a/core/modules/language/language.services.yml b/core/modules/language/language.services.yml index d6599b3..d7d8c37 100644 --- a/core/modules/language/language.services.yml +++ b/core/modules/language/language.services.yml @@ -1,7 +1,19 @@ services: + plugin.manager.language_negotiation_method: + class: Drupal\language\LanguageNegotiationMethodManager + arguments: ['@container.namespaces', '@cache.cache', '@module_handler'] + language_negotiator: + class: Drupal\language\LanguageNegotiator + arguments: ['@language_manager', '@plugin.manager.language_negotiation_method', '@config.factory', '@settings', '@module_handler'] + language_request_subscriber: + class: Drupal\language\EventSubscriber\LanguageRequestSubscriber + tags: + - { name: event_subscriber } + arguments: ['@language_manager', '@language_negotiator', '@string_translation', '@current_user'] path_processor_language: class: Drupal\language\HttpKernel\PathProcessorLanguage - arguments: ['@config.factory', '@settings', '@language_manager'] + arguments: ['@config.factory', '@settings', '@language_manager', '@language_negotiator'] tags: - { name: path_processor_inbound, priority: 300 } - { name: path_processor_outbound, priority: 100 } + diff --git a/core/modules/language/lib/Drupal/language/ConfigurableLanguageManager.php b/core/modules/language/lib/Drupal/language/ConfigurableLanguageManager.php new file mode 100644 index 0000000..3b2a2d8 --- /dev/null +++ b/core/modules/language/lib/Drupal/language/ConfigurableLanguageManager.php @@ -0,0 +1,284 @@ +configData = $config_data; + $this->moduleHandler = $module_handler; + } + + /** + * {@inheritdoc} + */ + public function init() { + if (!$this->initialized) { + foreach ($this->getLanguageTypes() as $type) { + $this->getLanguage($type); + } + $this->initialized = TRUE; + } + } + + /** + * {@inheritdoc} + */ + public function isMultilingual() { + return $this->getLanguageList(Language::STATE_CONFIGURABLE) > 1; + } + + /** + * {@inheritdoc} + */ + public function getLanguageTypes() { + $types = \Drupal::config('system.language.types')->get('all'); + return $types ? $types : parent::getLanguageTypes(); + } + + /** + * {@inheritdoc} + */ + public function getConfigurableLanguageTypes() { + return \Drupal::config('system.language.types')->get('configurable') ?: array(); + } + + /** + * {@inheritdoc} + */ + public function getLanguage($type = Language::TYPE_INTERFACE) { + if (!isset($this->negotiatedLanguages[$type])) { + // Ensure we have a valid value for this language type. + $this->negotiatedLanguages[$type] = parent::getLanguage($type); + + if ($this->negotiator && $this->isMultilingual()) { + if (!$this->initializing) { + $this->initializing = TRUE; + $this->negotiatedLanguages[$type] = $this->negotiator->initializeType($type); + $this->initializing = FALSE; + } + // If the current interface language needs to be retrieved during + // initialization we return the system language. This way string + // translation calls happening during initialization will return the + // original strings which can be translated by calling them again + // afterwards. This can happen for instance while parsing negotiation + // method definitions. + elseif ($type == Language::TYPE_INTERFACE) { + return new Language(array('id' => Language::LANGCODE_SYSTEM)); + } + } + } + + return $this->negotiatedLanguages[$type]; + } + + /** + * {@inheritdoc} + */ + public function reset($type = NULL) { + if (!isset($type)) { + $this->negotiatedLanguages = array(); + $this->initialized = FALSE; + $this->languageList = NULL; + } + elseif (isset($this->negotiatedLanguages[$type])) { + unset($this->negotiatedLanguages[$type]); + } + } + + /** + * {@inheritdoc} + */ + public function setRequest(Request $request) { + $this->request = $request; + } + + /** + * {@inheritdoc} + */ + public function getNegotiator() { + return $this->negotiator; + } + + /** + * {@inheritdoc} + */ + public function setNegotiator(LanguageNegotiatorInterface $negotiator) { + $this->negotiator = $negotiator; + $this->reset(); + $this->init(); + } + + /** + * {@inheritdoc} + */ + public function getDefaultLanguage() { + // @todo convert to CMI https://drupal.org/node/1827038 and + // https://drupal.org/node/2108599. This will need to be injected in + // LanguageServiceProvider::alter() to avoid circular dependencies on the + // config service. + $default_info = variable_get('language_default', Language::$defaultValues); + return new Language($default_info + array('default' => TRUE)); + } + + /** + * {@inheritdoc} + */ + public function getLanguageList($flags = Language::STATE_CONFIGURABLE) { + if (!isset($this->languageList)) { + $default = $this->getDefaultLanguage(); + $this->languageList = array($default->id => $default); + $weight = 0; + foreach ($this->configData['language_info'] as $info) { + $langcode = $info['id']; + $info['default'] = ($langcode == $default->id); + $info['name'] = $info['label']; + $this->languageList[$langcode] = new Language($info); + $weight = max(array($weight, $this->languageList[$langcode]->weight)); + } + // Add the special languages, they will be filtered later if needed. + $this->languageList += $this->getDefaultLockedLanguages($weight); + // Sort the language list by weight. + Language::sort($this->languageList); + } + return parent::getLanguageList($flags); + } + + /** + * {@inheritdoc} + */ + public function getFallbackCandidates($langcode = NULL, array $context = array()) { + if ($this->isMultilingual()) { + // Get languages ordered by weight, add Language::LANGCODE_NOT_SPECIFIED + // at the end. + $candidates = array_keys($this->getLanguageList()); + $candidates[] = Language::LANGCODE_NOT_SPECIFIED; + $candidates = MapArray::copyValuesToKeys($candidates); + + // The first candidate should always be the desired language if specified. + if (!empty($langcode)) { + $candidates = array($langcode => $langcode) + $candidates; + } + + // Let other modules hook in and add/change candidates. + $type = 'language_fallback_candidates'; + $types = array(); + if (!empty($context['operation'])) { + $types[] = $type . '_' . $context['operation']; + } + $types[] = $type; + $this->moduleHandler->alter($types, $candidates, $context); + } + else { + $candidates = array(Language::LANGCODE_DEFAULT); + } + + return $candidates; + } + + /** + * {@inheritdoc} + */ + public function getLanguageSwitchLinks($type, $path) { + $links = FALSE; + + if ($this->negotiator) { + foreach ($this->negotiator->getNegotiationMethods($type) as $method_id => $method) { + $reflector = new \ReflectionClass($method['class']); + + if ($reflector->implementsInterface('\Drupal\language\LanguageSwitcherInterface')) { + $result = $this->negotiator->getNegotiationMethodInstance($method_id)->getLanguageSwitchLinks($this->request, $type, $path); + + if (!empty($result)) { + // Allow modules to provide translations for specific links. + $this->moduleHandler->alter('language_switch_links', $result, $type, $path); + $links = (object) array('links' => $result, 'method_id' => $method_id); + break; + } + } + } + } + + return $links; + } + +} diff --git a/core/modules/language/lib/Drupal/language/ConfigurableLanguageManagerInterface.php b/core/modules/language/lib/Drupal/language/ConfigurableLanguageManagerInterface.php new file mode 100644 index 0000000..5be1a03 --- /dev/null +++ b/core/modules/language/lib/Drupal/language/ConfigurableLanguageManagerInterface.php @@ -0,0 +1,54 @@ +languageManager = $language_manager; + $this->negotiator = $negotiator; $this->translation = $translation; + $this->currentUser = $current_user; } /** @@ -56,7 +77,10 @@ public function __construct(LanguageManager $language_manager, TranslatorInterfa */ public function onKernelRequestLanguage(GetResponseEvent $event) { if ($event->getRequestType() == HttpKernelInterface::MASTER_REQUEST) { - $this->languageManager->setRequest($event->getRequest()); + $request = $event->getRequest(); + $this->negotiator->setContext($this->currentUser, $request); + $this->languageManager->setNegotiator($this->negotiator); + $this->languageManager->setRequest($request); // After the language manager has initialized, set the default langcode // for the string translations. $langcode = $this->languageManager->getLanguage(Language::TYPE_INTERFACE)->id; diff --git a/core/modules/language/lib/Drupal/language/Form/LanguageAddForm.php b/core/modules/language/lib/Drupal/language/Form/LanguageAddForm.php index bca5523..c0c9b6c 100644 --- a/core/modules/language/lib/Drupal/language/Form/LanguageAddForm.php +++ b/core/modules/language/lib/Drupal/language/Form/LanguageAddForm.php @@ -98,6 +98,10 @@ public function submitForm(array &$form, array &$form_state) { } // Save the language and inform the user that it happened. $language = language_save($language); + + // Rebuild the container to update the submitted settings. + language_negotiation_rebuild_settings(); + drupal_set_message($this->t('The language %language has been created and can now be used.', array('%language' => $language->name))); // Tell the user they have the option to add a language switcher block diff --git a/core/modules/language/lib/Drupal/language/Form/LanguageEditForm.php b/core/modules/language/lib/Drupal/language/Form/LanguageEditForm.php index 66e1ed1..fda903f 100644 --- a/core/modules/language/lib/Drupal/language/Form/LanguageEditForm.php +++ b/core/modules/language/lib/Drupal/language/Form/LanguageEditForm.php @@ -54,6 +54,9 @@ public function submitForm(array &$form, array &$form_state) { $language->name = $form_state['values']['name']; $language->direction = $form_state['values']['direction']; language_save($language); + + // Rebuild the container to update the submitted settings. + language_negotiation_rebuild_settings(); $form_state['redirect_route']['route_name'] = 'language.admin_overview'; } diff --git a/core/modules/language/lib/Drupal/language/Form/NegotiationBrowserDeleteForm.php b/core/modules/language/lib/Drupal/language/Form/NegotiationBrowserDeleteForm.php index 1d4260b..3dbba59 100644 --- a/core/modules/language/lib/Drupal/language/Form/NegotiationBrowserDeleteForm.php +++ b/core/modules/language/lib/Drupal/language/Form/NegotiationBrowserDeleteForm.php @@ -66,6 +66,9 @@ public function submitForm(array &$form, array &$form_state) { language_set_browser_drupal_langcode_mappings($mappings); } + // Rebuild the container to update the submitted settings. + language_negotiation_rebuild_settings(); + $form_state['redirect_route']['route_name'] = 'language.negotiation_browser'; } diff --git a/core/modules/language/lib/Drupal/language/Form/NegotiationBrowserForm.php b/core/modules/language/lib/Drupal/language/Form/NegotiationBrowserForm.php index 2271b14..3b8538b 100644 --- a/core/modules/language/lib/Drupal/language/Form/NegotiationBrowserForm.php +++ b/core/modules/language/lib/Drupal/language/Form/NegotiationBrowserForm.php @@ -177,6 +177,7 @@ public function submitForm(array &$form, array &$form_state) { $config = $this->configFactory->get('language.mappings'); $config->setData($mappings); $config->save(); + language_negotiation_rebuild_settings(); } $form_state['redirect_route']['route_name'] = 'language.negotiation'; diff --git a/core/modules/language/lib/Drupal/language/Form/NegotiationSelectedForm.php b/core/modules/language/lib/Drupal/language/Form/NegotiationSelectedForm.php index 614fd3b..db82fc2 100644 --- a/core/modules/language/lib/Drupal/language/Form/NegotiationSelectedForm.php +++ b/core/modules/language/lib/Drupal/language/Form/NegotiationSelectedForm.php @@ -45,6 +45,8 @@ public function submitForm(array &$form, array &$form_state) { ->set('selected_langcode', $form_state['values']['selected_langcode']) ->save(); + language_negotiation_rebuild_settings(); + parent::submitForm($form, $form_state); } diff --git a/core/modules/language/lib/Drupal/language/Form/NegotiationSessionForm.php b/core/modules/language/lib/Drupal/language/Form/NegotiationSessionForm.php index b688b05..35f46ab 100644 --- a/core/modules/language/lib/Drupal/language/Form/NegotiationSessionForm.php +++ b/core/modules/language/lib/Drupal/language/Form/NegotiationSessionForm.php @@ -46,6 +46,8 @@ public function submitForm(array &$form, array &$form_state) { ->set('session.parameter', $form_state['values']['language_negotiation_session_param']) ->save(); + language_negotiation_rebuild_settings(); + parent::submitForm($form, $form_state); } diff --git a/core/modules/language/lib/Drupal/language/Form/NegotiationUrlForm.php b/core/modules/language/lib/Drupal/language/Form/NegotiationUrlForm.php index ac709e3..172e6b0 100644 --- a/core/modules/language/lib/Drupal/language/Form/NegotiationUrlForm.php +++ b/core/modules/language/lib/Drupal/language/Form/NegotiationUrlForm.php @@ -8,6 +8,7 @@ namespace Drupal\language\Form; use Drupal\Core\Form\ConfigFormBase; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl; /** * Configure the URL language negotiation method for this site. @@ -27,14 +28,13 @@ public function getFormId() { public function buildForm(array $form, array &$form_state) { global $base_url; $config = $this->configFactory->get('language.negotiation'); - language_negotiation_include(); $form['language_negotiation_url_part'] = array( '#title' => t('Part of the URL that determines language'), '#type' => 'radios', '#options' => array( - LANGUAGE_NEGOTIATION_URL_PREFIX => t('Path prefix'), - LANGUAGE_NEGOTIATION_URL_DOMAIN => t('Domain'), + LanguageNegotiationUrl::CONFIG_PATH_PREFIX => t('Path prefix'), + LanguageNegotiationUrl::CONFIG_DOMAIN => t('Domain'), ), '#default_value' => $config->get('url.source'), ); @@ -47,7 +47,7 @@ public function buildForm(array $form, array &$form_state) { '#states' => array( 'visible' => array( ':input[name="language_negotiation_url_part"]' => array( - 'value' => (string) LANGUAGE_NEGOTIATION_URL_PREFIX, + 'value' => (string) LanguageNegotiationUrl::CONFIG_PATH_PREFIX, ), ), ), @@ -60,7 +60,7 @@ public function buildForm(array $form, array &$form_state) { '#states' => array( 'visible' => array( ':input[name="language_negotiation_url_part"]' => array( - 'value' => (string) LANGUAGE_NEGOTIATION_URL_DOMAIN, + 'value' => (string) LanguageNegotiationUrl::CONFIG_DOMAIN, ), ), ), @@ -103,7 +103,7 @@ public function validateForm(array &$form, array &$form_state) { $value = $form_state['values']['prefix'][$langcode]; if ($value === '') { - if (!$language->default && $form_state['values']['language_negotiation_url_part'] == LANGUAGE_NEGOTIATION_URL_PREFIX) { + if (!$language->default && $form_state['values']['language_negotiation_url_part'] == LanguageNegotiationUrl::CONFIG_PATH_PREFIX) { // Throw a form error if the prefix is blank for a non-default language, // although it is required for selected negotiation type. $this->setFormError("prefix][$langcode", $form_state, t('The prefix may only be left blank for the default language.')); @@ -127,7 +127,7 @@ public function validateForm(array &$form, array &$form_state) { $value = $form_state['values']['domain'][$langcode]; if ($value === '') { - if (!$language->default && $form_state['values']['language_negotiation_url_part'] == LANGUAGE_NEGOTIATION_URL_DOMAIN) { + if (!$language->default && $form_state['values']['language_negotiation_url_part'] == LanguageNegotiationUrl::CONFIG_DOMAIN) { // Throw a form error if the domain is blank for a non-default language, // although it is required for selected negotiation type. $this->setFormError("domain][$langcode", $form_state, t('The domain may only be left blank for the default language.')); diff --git a/core/modules/language/lib/Drupal/language/HttpKernel/PathProcessorLanguage.php b/core/modules/language/lib/Drupal/language/HttpKernel/PathProcessorLanguage.php index d212c7b..4d57731 100644 --- a/core/modules/language/lib/Drupal/language/HttpKernel/PathProcessorLanguage.php +++ b/core/modules/language/lib/Drupal/language/HttpKernel/PathProcessorLanguage.php @@ -8,12 +8,12 @@ namespace Drupal\language\HttpKernel; use Drupal\Component\Utility\Settings; +use Drupal\Component\Utility\Unicode; use Drupal\Core\Config\ConfigFactory; -use Drupal\Core\Language\Language; -use Drupal\Core\Language\LanguageManager; use Drupal\Core\PathProcessor\InboundPathProcessorInterface; use Drupal\Core\PathProcessor\OutboundPathProcessorInterface; -use Symfony\Component\HttpKernel\HttpKernelInterface; +use Drupal\language\ConfigurableLanguageManagerInterface; +use Drupal\language\LanguageNegotiatorInterface; use Symfony\Component\HttpFoundation\Request; /** @@ -38,129 +38,108 @@ class PathProcessorLanguage implements InboundPathProcessorInterface, OutboundPa /** * Language manager for retrieving the url language type. * - * @var \Drupal\Core\Language\LanguageManager + * @var \Drupal\language\ConfigurableLanguageManagerInterface */ protected $languageManager; /** - * An array of enabled languages. + * The language negotiator. + * + * @var \Drupal\language\LanguageNegotiatorInterface + */ + protected $negotiator; + + /** + * Local cache for language path processors. * * @var array */ - protected $languages; + protected $processors; + /** + * Flag indicating whether the site is multilingual. + * + * @var bool + */ + protected $multilingual; /** * Constructs a PathProcessorLanguage object. * * @param \Drupal\Core\Config\ConfigFactory $config * A config factory object for retrieving configuration settings. - * - * @param array $languages - * An array of languages, keyed by language code, representing the languages - * currently enabled on the site. + * @param \Drupal\Component\Utility\Settings $settings + * The settings instance. + * @param \Drupal\language\ConfigurableLanguageManagerInterface $language_manager + * The configurable language manager. */ - public function __construct(ConfigFactory $config, Settings $settings, LanguageManager $language_manager, array $languages = array()) { + public function __construct(ConfigFactory $config, Settings $settings, ConfigurableLanguageManagerInterface $language_manager, LanguageNegotiatorInterface $negotiator) { $this->config = $config; $this->mixedModeSessions = $settings->get('mixed_mode_sessions', FALSE); $this->languageManager = $language_manager; - if (empty($languages)) { - $languages = language_list(); - } - $this->languages = $languages; + $this->negotiator = $negotiator; } /** - * Implements Drupal\Core\PathProcessor\InboundPathProcessorInterface::processInbound(). + * {@inheritdoc} */ public function processInbound($path, Request $request) { if (!empty($path)) { - $args = explode('/', $path); - $prefix = array_shift($args); - - // Search prefix within enabled languages. - $prefixes = $this->config->get('language.negotiation')->get('url.prefixes'); - foreach ($this->languages as $language) { - if (isset($prefixes[$language->id]) && $prefixes[$language->id] == $prefix) { - // Rebuild $path with the language removed. - return implode('/', $args); - } + $scope = 'inbound'; + if (!isset($this->processors[$scope])) { + $this->initProcessors($scope); + } + foreach ($this->processors[$scope] as $instance) { + $path = $instance->processInbound($path, $request); } } return $path; } /** - * Implements Drupal\Core\PathProcessor\InboundPathProcessorInterface::processOutbound(). + * {@inheritdoc} */ public function processOutbound($path, &$options = array(), Request $request = NULL) { - if (!$this->languageManager->isMultilingual()) { - return $path; - } - $url_scheme = 'http'; - $port = 80; - if ($request) { - $url_scheme = $request->getScheme(); - $port = $request->getPort(); - } - $languages = array_flip(array_keys($this->languages)); - // Language can be passed as an option, or we go for current URL language. - if (!isset($options['language'])) { - $language_url = $this->languageManager->getLanguage(Language::TYPE_URL); - $options['language'] = $language_url; - } - // We allow only enabled languages here. - elseif (is_object($options['language']) && !isset($languages[$options['language']->id])) { - return $path; + if (!isset($this->multilingual)) { + $this->multilingual = $this->languageManager->isMultilingual(); } - $url_source = $this->config->get('language.negotiation')->get('url.source'); - // @todo Go back to using a constant instead of the string 'path_prefix' once we can use a class - // constant. - if ($url_source == 'path_prefix') { - $prefixes = $this->config->get('language.negotiation')->get('url.prefixes'); - if (is_object($options['language']) && !empty($prefixes[$options['language']->id])) { - return empty($path) ? $prefixes[$options['language']->id] : $prefixes[$options['language']->id] . '/' . $path; + if ($this->multilingual) { + $scope = 'outbound'; + if (!isset($this->processors[$scope])) { + $this->initProcessors($scope); + } + // Execute outbound language processors. + $options['mixed_mode_sessions'] = $this->mixedModeSessions; + foreach ($this->processors[$scope] as $instance) { + $path = $instance->processOutbound($path, $options, $request); + } + // No language dependent path allowed in this mode. + if (empty($this->processors[$scope])) { + unset($options['language']); } } - elseif ($url_source == 'domain') { - $domains = $this->config->get('language.negotiation')->get('url.domains'); - if (is_object($options['language']) && !empty($domains[$options['language']->id])) { - - // Save the original base URL. If it contains a port, we need to - // retain it below. - if (!empty($options['base_url'])) { - // The colon in the URL scheme messes up the port checking below. - $normalized_base_url = str_replace(array('https://', 'http://'), '', $options['base_url']); - } - - // Ask for an absolute URL with our modified base URL. - $options['absolute'] = TRUE; - $options['base_url'] = $url_scheme . '://' . $domains[$options['language']->id]; - - // In case either the original base URL or the HTTP host contains a - // port, retain it. - if (isset($normalized_base_url) && strpos($normalized_base_url, ':') !== FALSE) { - list( , $port) = explode(':', $normalized_base_url); - $options['base_url'] .= ':' . $port; - } - elseif ($port != 80) { - $options['base_url'] .= ':' . $port; - } + return $path; + } - if (isset($options['https']) && $this->mixedModeSessions) { - if ($options['https'] === TRUE) { - $options['base_url'] = str_replace('http://', 'https://', $options['base_url']); - } - elseif ($options['https'] === FALSE) { - $options['base_url'] = str_replace('https://', 'http://', $options['base_url']); + /** + * Initializes the local cache for language path processors. + * + * @param string $scope + * The scope of the processors: "inbound" or "outbound". + */ + protected function initProcessors($scope) { + $interface = '\Drupal\Core\PathProcessor\\' . Unicode::ucfirst($scope) . 'PathProcessorInterface'; + $this->processors[$scope] = array(); + foreach ($this->languageManager->getConfigurableLanguageTypes() as $type) { + foreach ($this->negotiator->getNegotiationMethods($type) as $method_id => $method) { + if (!isset($this->processors[$scope][$method_id])) { + $reflector = new \ReflectionClass($method['class']); + if ($reflector->implementsInterface($interface)) { + $this->processors[$scope][$method_id] = $this->negotiator->getNegotiationMethodInstance($method_id); } } - - // Add Drupal's subfolder from the base_path if there is one. - $options['base_url'] .= rtrim(base_path(), '/'); } } - return $path; } } diff --git a/core/modules/language/lib/Drupal/language/LanguageListController.php b/core/modules/language/lib/Drupal/language/LanguageListController.php index 35724b7..b4a2bee 100644 --- a/core/modules/language/lib/Drupal/language/LanguageListController.php +++ b/core/modules/language/lib/Drupal/language/LanguageListController.php @@ -95,8 +95,9 @@ public function buildForm(array $form, array &$form_state) { public function submitForm(array &$form, array &$form_state) { parent::submitForm($form, $form_state); - // Kill the static cache in language_list(). - drupal_static_reset('language_list'); + language_negotiation_rebuild_settings(); + + \Drupal::languageManager()->reset(); // Update weight of locked system languages. language_update_locked_weights(); diff --git a/core/modules/language/lib/Drupal/language/LanguageNegotiationMethodBase.php b/core/modules/language/lib/Drupal/language/LanguageNegotiationMethodBase.php new file mode 100644 index 0000000..27d1993 --- /dev/null +++ b/core/modules/language/lib/Drupal/language/LanguageNegotiationMethodBase.php @@ -0,0 +1,76 @@ +negotiator = $negotiator; + } + + /** + * {@inheritdoc} + */ + public function setLanguageManager(ConfigurableLanguageManagerInterface $language_manager) { + $this->languageManager = $language_manager; + } + + /** + * {@inheritdoc} + */ + public function setConfig(ConfigFactory $config) { + $this->config = $config; + } + + /** + * {@inheritdoc} + */ + public function setCurrentUser(AccountInterface $current_user) { + $this->currentUser = $current_user; + } + +} diff --git a/core/modules/language/lib/Drupal/language/LanguageNegotiationMethodInterface.php b/core/modules/language/lib/Drupal/language/LanguageNegotiationMethodInterface.php new file mode 100644 index 0000000..a46ba60 --- /dev/null +++ b/core/modules/language/lib/Drupal/language/LanguageNegotiationMethodInterface.php @@ -0,0 +1,63 @@ +cacheBackend = $cache_backend; + $this->cacheKeyPrefix = 'language_negotiation_plugins'; + $this->cacheKey = 'language_negotiation_plugins'; + if ($module_handler) { + $this->alterInfo($module_handler, 'language_negotiation_info'); + } + } + + /** + * {@inheritdoc} + */ + public function clearCachedDefinitions() { + $this->definitions = NULL; + $this->cacheBackend->delete($this->cacheKey); + } + +} diff --git a/core/modules/language/lib/Drupal/language/LanguageNegotiator.php b/core/modules/language/lib/Drupal/language/LanguageNegotiator.php new file mode 100644 index 0000000..83435e8 --- /dev/null +++ b/core/modules/language/lib/Drupal/language/LanguageNegotiator.php @@ -0,0 +1,254 @@ +languageManager = $language_manager; + $this->negotiatorManager = $negotiator_manager; + $this->config = $config; + $this->settings = $settings; + $this->moduleHandler = $module_handler; + } + + /** + * {@inheritdoc} + */ + public function setContext(AccountInterface $current_user, Request $request) { + $this->currentUser = $current_user; + $this->request = $request; + $this->negotiatedLanguages = array(); + $this->methods = array(); + } + + /** + * {@inheritdoc} + */ + public function initializeType($type) { + $language = FALSE; + + if ($this->currentUser && $this->request) { + // Execute the language negotiation methods in the order they were set up + // and return the first valid language found. + foreach ($this->getNegotiationForType($type) as $method_id) { + if (!isset($this->negotiatedLanguages[$method_id])) { + $this->negotiatedLanguages[$method_id] = $this->negotiateLanguage($type, $method_id); + } + + // Since objects are references, we need to return a clone to prevent + // the language negotiation method cache from being unintentionally + // altered. The same methods might be used with different language types + // based on configuration. + $language = !empty($this->negotiatedLanguages[$method_id]) ? clone($this->negotiatedLanguages[$method_id]) : FALSE; + + if ($language) { + // Remember the method ID used to detect the language. + $language->method_id = $method_id; + break; + } + } + } + + if (!$language) { + // If no other language was found use the default one. + $language = $this->languageManager->getDefaultLanguage(); + $language->method_id = LanguageNegotiatorInterface::METHOD_ID; + } + + return $language; + } + + /** + * {@inheritdoc} + */ + protected function getNegotiationForType($type) { + // @todo convert to CMI https://drupal.org/node/1827038 and + // https://drupal.org/node/2102477 + return array_keys(variable_get("language_negotiation_$type", array())); + } + + /** + * Performs language negotiation using the specified negotiation method. + * + * @param string $type + * The language type to be initialized. + * @param string $method_id + * The string identifier of the language negotiation method to use to detect + * language. + * + * @return \Drupal\Core\Language\Language|FALSE + * Negotiated language object for given type and method, FALSE otherwise. + */ + protected function negotiateLanguage($type, $method_id) { + $langcode = FALSE; + $method = $this->negotiatorManager->getDefinition($method_id); + + if (!isset($method['types']) || in_array($type, $method['types'])) { + + // Check for a cache mode force from settings.php. + if ($this->settings->get('page_cache_without_database')) { + $cache_enabled = TRUE; + } + else { + // @todo Remove this line once every variable is converted to CMI. + drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES, FALSE); + $cache_enabled = $this->config->get('cache.page.use_internal'); + } + + // If the language negotiation method has no cache preference or this is + // satisfied we can execute the callback. + if ($cache = !isset($method['cache']) || $this->currentUser->isAuthenticated() || $method['cache'] == $cache_enabled) { + $langcode = $this->getNegotiationMethodInstance($method_id)->negotiateLanguage($this->request); + } + } + + $languages = $this->languageManager->getLanguageList(); + return isset($languages[$langcode]) ? $languages[$langcode] : FALSE; + } + + /** + * {@inheritdoc} + */ + public function getNegotiationMethods($type) { + $definitions = $this->negotiatorManager->getDefinitions(); + $ids = $this->getNegotiationForType($type); + return array_intersect_key($definitions, array_flip($ids)); + } + + /** + * {@inheritdoc} + */ + public function getNegotiationMethodInstance($method_id) { + if (!isset($this->methods[$method_id])) { + $instance = $this->negotiatorManager->createInstance($method_id, array()); + $instance->setNegotiator($this); + $instance->setLanguageManager($this->languageManager); + $instance->setConfig($this->config); + $instance->setCurrentUser($this->currentUser); + $this->methods[$method_id] = $instance; + } + return $this->methods[$method_id]; + } + + /** + * {@inheritdoc} + */ + public function getPrimaryNegotiationMethod($type) { + $negotiation = variable_get("language_negotiation_$type", array()); + return empty($negotiation) ? LanguageNegotiatorInterface::METHOD_ID : key($negotiation); + } + + /** + * {@inheritdoc} + */ + public function isNegotiationMethodEnabled($method_id, $type = NULL) { + $enabled = FALSE; + $language_types = !empty($type) ? array($type) : $this->languageManager->getConfigurableLanguageTypes(); + + foreach ($language_types as $type) { + $negotiation = variable_get("language_negotiation_$type", array()); + if (isset($negotiation[$method_id])) { + $enabled = TRUE; + break; + } + } + + return $enabled; + } + +} diff --git a/core/modules/language/lib/Drupal/language/LanguageNegotiatorInterface.php b/core/modules/language/lib/Drupal/language/LanguageNegotiatorInterface.php new file mode 100644 index 0000000..46f7cd7 --- /dev/null +++ b/core/modules/language/lib/Drupal/language/LanguageNegotiatorInterface.php @@ -0,0 +1,92 @@ +get('kernel.config.storage'); + $language_ids = $config_storage->listAll('language.entity'); + $config['language_info'] = $config_storage->readMultiple($language_ids); + + $definition = $container->getDefinition('language_manager'); + $definition->setClass('Drupal\language\ConfigurableLanguageManager') + ->addArgument($config) + ->addArgument(new Reference('state')) + ->addArgument(new Reference('module_handler')); + } + +} diff --git a/core/modules/language/lib/Drupal/language/LanguageSwitcherInterface.php b/core/modules/language/lib/Drupal/language/LanguageSwitcherInterface.php new file mode 100644 index 0000000..d6edd5b --- /dev/null +++ b/core/modules/language/lib/Drupal/language/LanguageSwitcherInterface.php @@ -0,0 +1,32 @@ +languageManager = $language_manager; + } + + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container, array $configuration, $plugin_id, array $plugin_definition) { + return new static( + $configuration, + $plugin_id, + $plugin_definition, + $container->get('language_manager') + ); + } + /** * {@inheritdoc} @@ -38,7 +79,7 @@ public function build() { $build = array(); $path = drupal_is_front_page() ? '' : current_path(); list(, $type) = explode(':', $this->getPluginId()); - $links = language_negotiation_get_switch_links($type, $path); + $links = $this->languageManager->getLanguageSwitchLinks($type, $path); if (isset($links->links)) { $build = array( diff --git a/core/modules/language/lib/Drupal/language/Plugin/Derivative/LanguageBlock.php b/core/modules/language/lib/Drupal/language/Plugin/Derivative/LanguageBlock.php index a329c3b..f1e0775 100644 --- a/core/modules/language/lib/Drupal/language/Plugin/Derivative/LanguageBlock.php +++ b/core/modules/language/lib/Drupal/language/Plugin/Derivative/LanguageBlock.php @@ -17,7 +17,6 @@ class LanguageBlock extends DerivativeBase { * {@inheritdoc} */ public function getDerivativeDefinitions(array $base_plugin_definition) { - include_once DRUPAL_ROOT . '/core/includes/language.inc'; $info = language_types_info(); $configurable_types = language_types_get_configurable(); foreach ($configurable_types as $type) { diff --git a/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationBrowser.php b/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationBrowser.php new file mode 100644 index 0000000..ff02ed3 --- /dev/null +++ b/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationBrowser.php @@ -0,0 +1,49 @@ +languageManager && $request && $request->server->get('HTTP_ACCEPT_LANGUAGE')) { + $http_accept_language = $request->server->get('HTTP_ACCEPT_LANGUAGE'); + $langcodes = array_keys($this->languageManager->getLanguageList()); + $mappings = $this->config->get('language.mappings')->get(); + $langcode = Browser::getLangcode($http_accept_language, $langcodes, $mappings); + } + + return $langcode; + } + +} diff --git a/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationSelected.php b/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationSelected.php new file mode 100644 index 0000000..405fac1 --- /dev/null +++ b/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationSelected.php @@ -0,0 +1,48 @@ +languageManager) { + $languages = $this->languageManager->getLanguageList(); + $langcode = $this->config->get('language.negotiation')->get('selected_langcode'); + if (!isset($languages[$langcode])) { + $langcode = $this->languageManager->getDefaultLanguage()->id; + } + } + + return $langcode; + } + +} diff --git a/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationSession.php b/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationSession.php new file mode 100644 index 0000000..7b557eb --- /dev/null +++ b/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationSession.php @@ -0,0 +1,146 @@ +config->get('language.negotiation')->get('session'); + $param = $config['parameter']; + $langcode = $request && $request->query->get($param) ? $request->query->get($param) : FALSE; + + // We need to update the session parameter with the request value only if we + // have an authenticated user. + if ($langcode && $this->languageManager) { + $languages = $this->languageManager->getLanguageList(); + if ($this->currentUser->isAuthenticated() && isset($languages[$langcode])) { + $_SESSION[$param] = $langcode; + } + } + + // Session parameter. + if (isset($_SESSION[$param])) { + $langcode = $_SESSION[$param]; + } + + return $langcode; + } + + /** + * {@inheritdoc} + */ + public function processOutbound($path, &$options = array(), Request $request = NULL) { + if ($request) { + // The following values are not supposed to change during a single page + // request processing. + if (!isset($this->queryRewrite)) { + if ($this->currentUser->isAnonymous()) { + $languages = $this->languageManager->getLanguageList(); + $config = $this->config->get('language.negotiation')->get('session'); + $this->queryParam = $config['parameter']; + $this->queryValue = $request->query->has($this->queryParam) ? $request->query->get($this->queryParam) : NULL; + $this->queryRewrite = isset($languages[$this->queryValue]) && $this->negotiator->isNegotiationMethodEnabled(LanguageNegotiationSession::METHOD_ID); + } + else { + $this->queryRewrite = FALSE; + } + } + + // If the user is anonymous, the user language negotiation method is + // enabled, and the corresponding option has been set, we must preserve + // any explicit user language preference even with cookies disabled. + if ($this->queryRewrite) { + if (isset($options['query']) && is_string($options['query'])) { + $query = array(); + parse_str($options['query'], $query); + $options['query'] = $query; + } + if (!isset($options['query'][$this->queryParam])) { + $options['query'][$this->queryParam] = $this->queryValue; + } + } + } + return $path; + } + + /** + * {@inheritdoc} + */ + function getLanguageSwitchLinks(Request $request, $type, $path) { + $links = array(); + $config = $this->config->get('language.negotiation')->get('session'); + $param = $config['parameter']; + $language_query = isset($_SESSION[$param]) ? $_SESSION[$param] : $this->languageManager->getLanguage($type)->id; + $query = array(); + parse_str($request->getQueryString(), $query); + + foreach ($this->languageManager->getLanguageList() as $language) { + $langcode = $language->id; + $links[$langcode] = array( + 'href' => $path, + 'title' => $language->name, + 'attributes' => array('class' => array('language-link')), + 'query' => $query, + ); + if ($language_query != $langcode) { + $links[$langcode]['query'][$param] = $langcode; + } + else { + $links[$langcode]['attributes']['class'][] = ' session-active'; + } + } + + return $links; + } + +} diff --git a/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationUI.php b/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationUI.php new file mode 100644 index 0000000..f8bb089 --- /dev/null +++ b/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationUI.php @@ -0,0 +1,38 @@ +languageManager ? $this->languageManager->getLanguage()->id : FALSE; + } + +} diff --git a/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationUrl.php b/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationUrl.php new file mode 100644 index 0000000..cbdc5a4 --- /dev/null +++ b/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationUrl.php @@ -0,0 +1,209 @@ +languageManager) { + $languages = $this->languageManager->getLanguageList(); + $config = $this->config->get('language.negotiation')->get('url'); + + switch ($config['source']) { + case LanguageNegotiationUrl::CONFIG_PATH_PREFIX: + $request_path = urldecode(trim($request->getPathInfo(), '/')); + $path_args = explode('/', $request_path); + $prefix = array_shift($path_args); + + // Search prefix within enabled languages. + $negotiated_language = FALSE; + foreach ($languages as $language) { + if (isset($config['prefixes'][$language->id]) && $config['prefixes'][$language->id] == $prefix) { + $negotiated_language = $language; + break; + } + } + + if ($negotiated_language !== FALSE && $negotiated_language instanceof \Drupal\Core\Language\Language) { + $langcode = $negotiated_language->id; + } + break; + + case LanguageNegotiationUrl::CONFIG_DOMAIN: + // Get only the host, not the port. + $http_host = $request->server->get('HTTP_HOST'); + if (strpos($http_host, ':') !== FALSE) { + $http_host_tmp = explode(':', $http_host); + $http_host = current($http_host_tmp); + } + foreach ($languages as $language) { + // Skip the check if the language doesn't have a domain. + if (!empty($config['domains'][$language->id])) { + // Ensure that there is exactly one protocol in the URL when + // checking the hostname. + $host = 'http://' . str_replace(array('http://', 'https://'), '', $config['domains'][$language->id]); + $host = parse_url($host, PHP_URL_HOST); + if ($http_host == $host) { + $langcode = $language->id; + break; + } + } + } + break; + } + } + + return $langcode; + } + + /** + * Implements Drupal\Core\PathProcessor\InboundPathProcessorInterface::processInbound(). + */ + public function processInbound($path, Request $request) { + $config = $this->config->get('language.negotiation')->get('url'); + $parts = explode('/', $path); + $prefix = array_shift($parts); + + // Search prefix within enabled languages. + foreach ($this->languageManager->getLanguageList() as $language) { + if (isset($config['prefixes'][$language->id]) && $config['prefixes'][$language->id] == $prefix) { + // Rebuild $path with the language removed. + $path = implode('/', $parts); + break; + } + } + + return $path; + } + + /** + * Implements Drupal\Core\PathProcessor\InboundPathProcessorInterface::processOutbound(). + */ + public function processOutbound($path, &$options = array(), Request $request = NULL) { + $url_scheme = 'http'; + $port = 80; + if ($request) { + $url_scheme = $request->getScheme(); + $port = $request->getPort(); + } + $languages = array_flip(array_keys($this->languageManager->getLanguageList())); + // Language can be passed as an option, or we go for current URL language. + if (!isset($options['language'])) { + $language_url = $this->languageManager->getLanguage(Language::TYPE_URL); + $options['language'] = $language_url; + } + // We allow only enabled languages here. + elseif (is_object($options['language']) && !isset($languages[$options['language']->id])) { + return $path; + } + $config = $this->config->get('language.negotiation')->get('url'); + // @todo Go back to using a constant instead of the string 'path_prefix' once we can use a class + // constant. + if ($config['source'] == LanguageNegotiationUrl::CONFIG_PATH_PREFIX) { + if (is_object($options['language']) && !empty($config['prefixes'][$options['language']->id])) { + return empty($path) ? $config['prefixes'][$options['language']->id] : $config['prefixes'][$options['language']->id] . '/' . $path; + } + } + elseif ($config['source'] == LanguageNegotiationUrl::CONFIG_DOMAIN) { + if (is_object($options['language']) && !empty($config['domains'][$options['language']->id])) { + + // Save the original base URL. If it contains a port, we need to + // retain it below. + if (!empty($options['base_url'])) { + // The colon in the URL scheme messes up the port checking below. + $normalized_base_url = str_replace(array('https://', 'http://'), '', $options['base_url']); + } + + // Ask for an absolute URL with our modified base URL. + $options['absolute'] = TRUE; + $options['base_url'] = $url_scheme . '://' . $config['domains'][$options['language']->id]; + + // In case either the original base URL or the HTTP host contains a + // port, retain it. + if (isset($normalized_base_url) && strpos($normalized_base_url, ':') !== FALSE) { + list(, $port) = explode(':', $normalized_base_url); + $options['base_url'] .= ':' . $port; + } + elseif ($port != 80) { + $options['base_url'] .= ':' . $port; + } + + if (isset($options['https']) && !empty($options['mixed_mode_sessions'])) { + if ($options['https'] === TRUE) { + $options['base_url'] = str_replace('http://', 'https://', $options['base_url']); + } + elseif ($options['https'] === FALSE) { + $options['base_url'] = str_replace('https://', 'http://', $options['base_url']); + } + } + + // Add Drupal's subfolder from the base_path if there is one. + $options['base_url'] .= rtrim(base_path(), '/'); + } + } + return $path; + } + + /** + * {@inheritdoc} + */ + function getLanguageSwitchLinks(Request $request, $type, $path) { + $links = array(); + + foreach ($this->languageManager->getLanguageList() as $language) { + $links[$language->id] = array( + 'href' => $path, + 'title' => $language->name, + 'language' => $language, + 'attributes' => array('class' => array('language-link')), + ); + } + + return $links; + } + +} diff --git a/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationUrlFallback.php b/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationUrlFallback.php new file mode 100644 index 0000000..b478e85 --- /dev/null +++ b/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationUrlFallback.php @@ -0,0 +1,76 @@ +languageManager) { + $default = $this->languageManager->getDefaultLanguage(); + $config = $this->config->get('language.negotiation')->get('url'); + $prefix = ($config['source'] == LanguageNegotiationUrl::CONFIG_PATH_PREFIX); + + // If the default language is not configured to convey language + // information, a missing URL language information indicates that URL + // language should be the default one, otherwise we fall back to an + // already detected language. + if (($prefix && empty($config['prefixes'][$default->id])) || (!$prefix && empty($config['domains'][$default->id]))) { + $langcode = $default->id; + } + else { + $langcode = $this->languageManager->getLanguage()->id; + } + } + + return $langcode; + } + +} diff --git a/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationUser.php b/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationUser.php new file mode 100644 index 0000000..199846a --- /dev/null +++ b/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationUser.php @@ -0,0 +1,50 @@ +languageManager && $this->currentUser->isAuthenticated()) { + $preferred_langcode = $this->currentUser->getPreferredLangcode(); + $default_langcode = $this->languageManager->getDefaultLanguage()->id; + $languages = $this->languageManager->getLanguageList(); + if (!empty($preferred_langcode) && $preferred_langcode != $default_langcode && isset($languages[$preferred_langcode])) { + $langcode = $preferred_langcode; + } + } + + // No language preference from the user. + return $langcode; + } + +} diff --git a/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationUserAdmin.php b/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationUserAdmin.php new file mode 100644 index 0000000..310fca4 --- /dev/null +++ b/core/modules/language/lib/Drupal/language/Plugin/LanguageNegotiation/LanguageNegotiationUserAdmin.php @@ -0,0 +1,53 @@ +getPathInfo(), '/')) : _current_path(); + if ($this->languageManager && $this->currentUser->isAuthenticated() && path_is_admin($request_path)) { + $preferred_admin_langcode = $this->currentUser->getPreferredAdminLangcode(); + $default_langcode = $this->languageManager->getDefaultLanguage()->id; + $languages = $this->languageManager->getLanguageList(); + if (!empty($preferred_admin_langcode) && $preferred_admin_langcode != $default_langcode && isset($languages[$preferred_admin_langcode])) { + $langcode = $preferred_admin_langcode; + } + } + + // No language preference from the user or not on an admin path. + return $langcode; + } + +} diff --git a/core/modules/language/lib/Drupal/language/Tests/Condition/LanguageConditionTest.php b/core/modules/language/lib/Drupal/language/Tests/Condition/LanguageConditionTest.php index 19449d8..ed029fa 100644 --- a/core/modules/language/lib/Drupal/language/Tests/Condition/LanguageConditionTest.php +++ b/core/modules/language/lib/Drupal/language/Tests/Condition/LanguageConditionTest.php @@ -26,7 +26,7 @@ class LanguageConditionTest extends DrupalUnitTestBase { /** * The language manager. * - * @var \Drupal\Core\Language\LanguageManager + * @var \Drupal\Core\Language\LanguageManagerInterface */ protected $languageManager; diff --git a/core/modules/language/lib/Drupal/language/Tests/LanguageBrowserDetectionUnitTest.php b/core/modules/language/lib/Drupal/language/Tests/LanguageBrowserDetectionUnitTest.php index 679d6f9..f660eb8 100644 --- a/core/modules/language/lib/Drupal/language/Tests/LanguageBrowserDetectionUnitTest.php +++ b/core/modules/language/lib/Drupal/language/Tests/LanguageBrowserDetectionUnitTest.php @@ -7,8 +7,10 @@ namespace Drupal\language\Tests; -use Drupal\simpletest\WebTestBase; +use Drupal\Component\Utility\Browser; use Drupal\Core\Language\Language; +use Drupal\simpletest\WebTestBase; +use Symfony\Component\HttpFoundation\Request; /** * Test browser language detection. @@ -153,9 +155,9 @@ function testLanguageFromBrowser() { 'zh-cht' => 'zh-hant', ); + $mappings = $this->container->get('config.factory')->get('language.mappings')->get(); foreach ($test_cases as $accept_language => $expected_result) { - \Drupal::request()->server->set('HTTP_ACCEPT_LANGUAGE', $accept_language); - $result = language_from_browser($languages); + $result = Browser::getLangcode($accept_language, array_keys($languages), $mappings); $this->assertIdentical($result, $expected_result, format_string("Language selection '@accept-language' selects '@result', result = '@actual'", array('@accept-language' => $accept_language, '@result' => $expected_result, '@actual' => isset($result) ? $result : 'none'))); } } diff --git a/core/modules/language/lib/Drupal/language/Tests/LanguageConfigurationElementTest.php b/core/modules/language/lib/Drupal/language/Tests/LanguageConfigurationElementTest.php index d5a3c02..12f3670 100644 --- a/core/modules/language/lib/Drupal/language/Tests/LanguageConfigurationElementTest.php +++ b/core/modules/language/lib/Drupal/language/Tests/LanguageConfigurationElementTest.php @@ -85,6 +85,7 @@ public function testDefaultLangcode() { $langcode = language_get_default_langcode('custom_type', 'custom_bundle'); $language_interface = language(Language::TYPE_INTERFACE); $this->assertEqual($langcode, $language_interface->id); + language_negotiation_rebuild_settings(); // Site's default. $old_default = language_default(); diff --git a/core/modules/language/lib/Drupal/language/Tests/LanguageConfigurationTest.php b/core/modules/language/lib/Drupal/language/Tests/LanguageConfigurationTest.php index 1fb8c85..8a0b7d6 100644 --- a/core/modules/language/lib/Drupal/language/Tests/LanguageConfigurationTest.php +++ b/core/modules/language/lib/Drupal/language/Tests/LanguageConfigurationTest.php @@ -72,7 +72,7 @@ function testLanguageConfiguration() { ); $this->drupalPostForm(NULL, $edit, t('Save configuration')); $this->assertOptionSelected('edit-site-default-language', 'fr', 'Default language updated.'); - $this->assertEqual($this->getUrl(), url('admin/config/regional/settings', array('absolute' => TRUE)), 'Correct page redirection.'); + $this->assertEqual($this->getUrl(), url('fr/admin/config/regional/settings', array('absolute' => TRUE)), 'Correct page redirection.'); // Check if a valid language prefix is added after changing the default // language. @@ -156,10 +156,10 @@ function testLanguageConfigurationWeight() { */ protected function checkConfigurableLanguageWeight($state = 'by default') { // Reset language list. - drupal_static_reset('language_list'); + \Drupal::languageManager()->reset(); $max_configurable_language_weight = $this->getHighestConfigurableLanguageWeight(); $replacements = array('@event' => $state); - foreach (language_list(Language::STATE_LOCKED) as $locked_language) { + foreach (\Drupal::languageManager()->getLanguageList(Language::STATE_LOCKED) as $locked_language) { $replacements['%language'] = $locked_language->name; $this->assertTrue($locked_language->weight > $max_configurable_language_weight, format_string('System language %language has higher weight than configurable languages @event', $replacements)); } diff --git a/core/modules/language/lib/Drupal/language/Tests/LanguageFallbackTest.php b/core/modules/language/lib/Drupal/language/Tests/LanguageFallbackTest.php index 4123fc0..f70210e 100644 --- a/core/modules/language/lib/Drupal/language/Tests/LanguageFallbackTest.php +++ b/core/modules/language/lib/Drupal/language/Tests/LanguageFallbackTest.php @@ -89,7 +89,7 @@ public function testCandidates() { /** * Returns the language manager service. * - * @return \Drupal\Core\Language\LanguageManager + * @return \Drupal\Core\Language\LanguageManagerInterface * The language manager. */ protected function getLanguageManager() { diff --git a/core/modules/language/lib/Drupal/language/Tests/LanguageListTest.php b/core/modules/language/lib/Drupal/language/Tests/LanguageListTest.php index 8b2190d..9d0c916 100644 --- a/core/modules/language/lib/Drupal/language/Tests/LanguageListTest.php +++ b/core/modules/language/lib/Drupal/language/Tests/LanguageListTest.php @@ -72,11 +72,11 @@ function testLanguageList() { ); $this->drupalPostForm(NULL, $edit, t('Save configuration')); $this->assertNoOptionSelected('edit-site-default-language', 'en', 'Default language updated.'); - $this->assertEqual($this->getUrl(), url($path, array('absolute' => TRUE)), 'Correct page redirection.'); + $this->assertEqual($this->getUrl(), url($langcode . '/' . $path, array('absolute' => TRUE)), 'Correct page redirection.'); // Ensure we can't delete the default language. $this->drupalGet('admin/config/regional/language/delete/' . $langcode); - $this->assertEqual($this->getUrl(), url('admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.'); + $this->assertEqual($this->getUrl(), url($langcode . '/admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.'); $this->assertText(t('The default language cannot be deleted.'), 'Failed to delete the default language.'); // Ensure 'Edit' link works. @@ -89,7 +89,7 @@ function testLanguageList() { ); $this->drupalPostForm('admin/config/regional/language/edit/' . $langcode, $edit, t('Save language')); $this->assertRaw($name, 'The language has been updated.'); - $this->assertEqual($this->getUrl(), url('admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.'); + $this->assertEqual($this->getUrl(), url($langcode . '/admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.'); // Change back the default language. $edit = array( @@ -104,7 +104,7 @@ function testLanguageList() { $this->drupalGet('admin/config/regional/language/delete/' . $langcode); // First test the 'cancel' link. $this->clickLink(t('Cancel')); - $this->assertEqual($this->getUrl(), url('admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.'); + $this->assertEqual($this->getUrl(), url('en/admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.'); $this->assertRaw($name, 'The language was not deleted.'); // Delete the language for real. This a confirm form, we do not need any // fields changed. @@ -112,19 +112,17 @@ function testLanguageList() { // We need raw here because %language and %langcode will add HTML. $t_args = array('%language' => $name, '%langcode' => $langcode); $this->assertRaw(t('The %language (%langcode) language has been removed.', $t_args), 'The test language has been removed.'); - $this->assertEqual($this->getUrl(), url('admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.'); + $this->assertEqual($this->getUrl(), url('en/admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.'); // Verify that language is no longer found. $this->drupalGet('admin/config/regional/language/delete/' . $langcode); $this->assertResponse(404, 'Language no longer found.'); // Make sure the "language_count" state has been updated correctly. - drupal_static_reset('language_list'); + $this->container->get('language_manager')->reset(); $languages = language_list(); - $language_count = $this->container->get('state')->get('language_count') ?: 1; - $this->assertEqual($language_count, count($languages), 'Language count is correct.'); // Delete French. $this->drupalPostForm('admin/config/regional/language/delete/fr', array(), t('Delete')); // Get the count of languages. - drupal_static_reset('language_list'); + $this->container->get('language_manager')->reset(); $languages = language_list(); // We need raw here because %language and %langcode will add HTML. $t_args = array('%language' => 'French', '%langcode' => 'fr'); @@ -134,8 +132,6 @@ function testLanguageList() { $this->drupalGet('admin/config/regional/language/delete/fr'); $this->assertResponse(404, 'Language no longer found.'); // Make sure the "language_count" state has not changed. - $language_count = $this->container->get('state')->get('language_count') ?: 1; - $this->assertEqual($language_count, count($languages), 'Language count is correct.'); // Ensure we can delete the English language. Right now English is the only // language so we must add a new language and make it the default before @@ -149,7 +145,7 @@ function testLanguageList() { 'direction' => '0', ); $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language')); - $this->assertEqual($this->getUrl(), url('admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.'); + $this->assertEqual($this->getUrl(), url('en/admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.'); $this->assertText($name, 'Name found.'); // Check if we can change the default language. @@ -162,7 +158,7 @@ function testLanguageList() { ); $this->drupalPostForm(NULL, $edit, t('Save configuration')); $this->assertNoOptionSelected('edit-site-default-language', 'en', 'Default language updated.'); - $this->assertEqual($this->getUrl(), url($path, array('absolute' => TRUE)), 'Correct page redirection.'); + $this->assertEqual($this->getUrl(), url($langcode . '/' . $path, array('absolute' => TRUE)), 'Correct page redirection.'); $this->drupalPostForm('admin/config/regional/language/delete/en', array(), t('Delete')); // We need raw here because %language and %langcode will add HTML. diff --git a/core/modules/language/lib/Drupal/language/Tests/LanguageNegotiationInfoTest.php b/core/modules/language/lib/Drupal/language/Tests/LanguageNegotiationInfoTest.php index 6cff106..4ce068c 100644 --- a/core/modules/language/lib/Drupal/language/Tests/LanguageNegotiationInfoTest.php +++ b/core/modules/language/lib/Drupal/language/Tests/LanguageNegotiationInfoTest.php @@ -8,6 +8,7 @@ namespace Drupal\language\Tests; use Drupal\Core\Language\Language; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUI; use Drupal\simpletest\WebTestBase; /** @@ -32,7 +33,6 @@ public static function getInfo() { function setUp() { parent::setUp(); - require_once DRUPAL_ROOT .'/core/includes/language.inc'; $admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages', 'view the administration theme')); $this->drupalLogin($admin_user); $this->drupalPostForm('admin/config/regional/language/add', array('predefined_langcode' => 'it'), t('Add language')); @@ -62,7 +62,7 @@ function testInfoAlterations() { // Enable some core and custom language negotiation methods. The test // language type is supposed to be configurable. $test_type = 'test_language_type'; - $interface_method_id = LANGUAGE_NEGOTIATION_INTERFACE; + $interface_method_id = LanguageNegotiationUI::METHOD_ID; $test_method_id = 'test_language_negotiation_method'; $form_field = $type . '[enabled]['. $interface_method_id .']'; $edit = array( @@ -96,7 +96,7 @@ function testInfoAlterations() { // Check language negotiation results. $this->drupalGet(''); $last = \Drupal::state()->get('language_test.language_negotiation_last'); - foreach (language_types_get_all() as $type) { + foreach (\Drupal::languageManager()->getLanguageTypes() as $type) { $langcode = $last[$type]; $value = $type == Language::TYPE_CONTENT || strpos($type, 'test') !== FALSE ? 'it' : 'en'; $this->assertEqual($langcode, $value, format_string('The negotiated language for %type is %language', array('%type' => $type, '%language' => $value))); @@ -107,7 +107,7 @@ function testInfoAlterations() { $this->languageNegotiationUpdate('uninstall'); // Check that only the core language types are available. - foreach (language_types_get_all() as $type) { + foreach (\Drupal::languageManager()->getLanguageTypes() as $type) { $this->assertTrue(strpos($type, 'test') === FALSE, format_string('The %type language is still available', array('%type' => $type))); } @@ -139,15 +139,13 @@ protected function languageNegotiationUpdate($op = 'install') { // Install/uninstall language_test only if we did not already before. if ($last_op != $op) { call_user_func(array($this->container->get('module_handler'), $op), $modules); - // Reset hook implementation cache. - $this->container->get('module_handler')->resetImplementations(); + $last_op = $op; } - - drupal_static_reset('language_types_info'); - drupal_static_reset('language_negotiation_info'); - $function = "language_modules_{$op}ed"; - if (function_exists($function)) { - $function($modules); + else { + $function = "language_modules_{$op}ed"; + if (function_exists($function)) { + $function($modules); + } } $this->drupalGet('admin/config/regional/language/detection'); diff --git a/core/modules/language/lib/Drupal/language/Tests/LanguageUILanguageNegotiationTest.php b/core/modules/language/lib/Drupal/language/Tests/LanguageUILanguageNegotiationTest.php index 7c037b5..da95293 100644 --- a/core/modules/language/lib/Drupal/language/Tests/LanguageUILanguageNegotiationTest.php +++ b/core/modules/language/lib/Drupal/language/Tests/LanguageUILanguageNegotiationTest.php @@ -7,6 +7,11 @@ namespace Drupal\language\Tests; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationBrowser; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationSelected; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUser; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUserAdmin; use Drupal\simpletest\WebTestBase; use Drupal\Core\Language\Language; use Symfony\Component\HttpFoundation\Request; @@ -53,7 +58,7 @@ class LanguageUILanguageNegotiationTest extends WebTestBase { public static function getInfo() { return array( 'name' => 'UI language negotiation', - 'description' => 'Test UI language switching by URL path prefix and domain.', + 'description' => 'Test UI language switching.', 'group' => 'Language', ); } @@ -64,7 +69,6 @@ function setUp() { $this->request = Request::create('http://example.com/'); $this->container->set('request', $this->request); - require_once DRUPAL_ROOT . '/core/includes/language.inc'; $admin_user = $this->drupalCreateUser(array('administer languages', 'translate interface', 'access administration pages', 'administer blocks')); $this->drupalLogin($admin_user); } @@ -106,7 +110,7 @@ function testUILanguageNegotiation() { // into database when seen by t(). Without doing this, our target string // is for some reason not found when doing translate search. This might // be some bug. - drupal_static_reset('language_list'); + $this->container->get('language_manager')->reset(); $languages = language_list(); variable_set('language_default', (array) $languages['vi']); // First visit this page to make sure our target string is searchable. @@ -142,17 +146,14 @@ function testUILanguageNegotiation() { ); $this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations')); - // Configure URL language rewrite. - variable_set('language_negotiation_url_type', Language::TYPE_INTERFACE); - // Configure selected language negotiation to use zh-hans. $edit = array('selected_langcode' => $langcode); $this->drupalPostForm('admin/config/regional/language/detection/selected', $edit, t('Save configuration')); $test = array( - 'language_negotiation' => array(LANGUAGE_NEGOTIATION_SELECTED), + 'language_negotiation' => array(LanguageNegotiationSelected::METHOD_ID), 'path' => 'admin/config', 'expect' => $language_string, - 'expected_method_id' => LANGUAGE_NEGOTIATION_SELECTED, + 'expected_method_id' => LanguageNegotiationSelected::METHOD_ID, 'http_header' => $http_header_browser_fallback, 'message' => 'SELECTED: UI language is switched based on selected language.', ); @@ -160,11 +161,12 @@ function testUILanguageNegotiation() { // An invalid language is selected. \Drupal::config('language.negotiation')->set('selected_langcode', NULL)->save(); + language_negotiation_rebuild_settings(); $test = array( - 'language_negotiation' => array(LANGUAGE_NEGOTIATION_SELECTED), + 'language_negotiation' => array(LanguageNegotiationSelected::METHOD_ID), 'path' => 'admin/config', 'expect' => $default_string, - 'expected_method_id' => LANGUAGE_NEGOTIATION_SELECTED, + 'expected_method_id' => LanguageNegotiationSelected::METHOD_ID, 'http_header' => $http_header_browser_fallback, 'message' => 'SELECTED > DEFAULT: UI language is switched based on selected language.', ); @@ -172,11 +174,12 @@ function testUILanguageNegotiation() { // No selected language is available. \Drupal::config('language.negotiation')->set('selected_langcode', $langcode_unknown)->save(); + language_negotiation_rebuild_settings(); $test = array( - 'language_negotiation' => array(LANGUAGE_NEGOTIATION_SELECTED), + 'language_negotiation' => array(LanguageNegotiationSelected::METHOD_ID), 'path' => 'admin/config', 'expect' => $default_string, - 'expected_method_id' => LANGUAGE_NEGOTIATION_SELECTED, + 'expected_method_id' => LanguageNegotiationSelected::METHOD_ID, 'http_header' => $http_header_browser_fallback, 'message' => 'SELECTED > DEFAULT: UI language is switched based on selected language.', ); @@ -185,46 +188,46 @@ function testUILanguageNegotiation() { $tests = array( // Default, browser preference should have no influence. array( - 'language_negotiation' => array(LANGUAGE_NEGOTIATION_URL, LANGUAGE_NEGOTIATION_SELECTED), + 'language_negotiation' => array(LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationSelected::METHOD_ID), 'path' => 'admin/config', 'expect' => $default_string, - 'expected_method_id' => LANGUAGE_NEGOTIATION_SELECTED, + 'expected_method_id' => LanguageNegotiationSelected::METHOD_ID, 'http_header' => $http_header_browser_fallback, 'message' => 'URL (PATH) > DEFAULT: no language prefix, UI language is default and the browser language preference setting is not used.', ), // Language prefix. array( - 'language_negotiation' => array(LANGUAGE_NEGOTIATION_URL, LANGUAGE_NEGOTIATION_SELECTED), + 'language_negotiation' => array(LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationSelected::METHOD_ID), 'path' => "$langcode/admin/config", 'expect' => $language_string, - 'expected_method_id' => LANGUAGE_NEGOTIATION_URL, + 'expected_method_id' => LanguageNegotiationUrl::METHOD_ID, 'http_header' => $http_header_browser_fallback, 'message' => 'URL (PATH) > DEFAULT: with language prefix, UI language is switched based on path prefix', ), // Default, go by browser preference. array( - 'language_negotiation' => array(LANGUAGE_NEGOTIATION_URL, LANGUAGE_NEGOTIATION_BROWSER), + 'language_negotiation' => array(LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationBrowser::METHOD_ID), 'path' => 'admin/config', 'expect' => $language_browser_fallback_string, - 'expected_method_id' => LANGUAGE_NEGOTIATION_BROWSER, + 'expected_method_id' => LanguageNegotiationBrowser::METHOD_ID, 'http_header' => $http_header_browser_fallback, 'message' => 'URL (PATH) > BROWSER: no language prefix, UI language is determined by browser language preference', ), // Prefix, switch to the language. array( - 'language_negotiation' => array(LANGUAGE_NEGOTIATION_URL, LANGUAGE_NEGOTIATION_BROWSER), + 'language_negotiation' => array(LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationBrowser::METHOD_ID), 'path' => "$langcode/admin/config", 'expect' => $language_string, - 'expected_method_id' => LANGUAGE_NEGOTIATION_URL, + 'expected_method_id' => LanguageNegotiationUrl::METHOD_ID, 'http_header' => $http_header_browser_fallback, 'message' => 'URL (PATH) > BROWSER: with language prefix, UI language is based on path prefix', ), // Default, browser language preference is not one of site's lang. array( - 'language_negotiation' => array(LANGUAGE_NEGOTIATION_URL, LANGUAGE_NEGOTIATION_BROWSER, LANGUAGE_NEGOTIATION_SELECTED), + 'language_negotiation' => array(LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationBrowser::METHOD_ID, LanguageNegotiationSelected::METHOD_ID), 'path' => 'admin/config', 'expect' => $default_string, - 'expected_method_id' => LANGUAGE_NEGOTIATION_SELECTED, + 'expected_method_id' => LanguageNegotiationSelected::METHOD_ID, 'http_header' => $http_header_blah, 'message' => 'URL (PATH) > BROWSER > DEFAULT: no language prefix and browser language preference set to unknown language should use default language', ), @@ -235,7 +238,7 @@ function testUILanguageNegotiation() { } // Unknown language prefix should return 404. - variable_set('language_negotiation_' . Language::TYPE_INTERFACE, language_language_negotiation_info()); + variable_set('language_negotiation_' . Language::TYPE_INTERFACE, array_flip(array_keys(language_negotiation_info()))); $this->drupalGet("$langcode_unknown/admin/config", array(), $http_header_browser_fallback); $this->assertResponse(404, "Unknown language path prefix should return 404"); @@ -245,10 +248,10 @@ function testUILanguageNegotiation() { $account->save(); $test = array( - 'language_negotiation' => array(LANGUAGE_NEGOTIATION_USER, LANGUAGE_NEGOTIATION_SELECTED), + 'language_negotiation' => array(LanguageNegotiationUser::METHOD_ID, LanguageNegotiationSelected::METHOD_ID), 'path' => 'admin/config', 'expect' => $default_string, - 'expected_method_id' => LANGUAGE_NEGOTIATION_SELECTED, + 'expected_method_id' => LanguageNegotiationSelected::METHOD_ID, 'http_header' => array(), 'message' => 'USER > DEFAULT: no preferred user language setting, the UI language is default', ); @@ -260,10 +263,10 @@ function testUILanguageNegotiation() { $account->save(); $test = array( - 'language_negotiation' => array(LANGUAGE_NEGOTIATION_USER, LANGUAGE_NEGOTIATION_SELECTED), + 'language_negotiation' => array(LanguageNegotiationUser::METHOD_ID, LanguageNegotiationSelected::METHOD_ID), 'path' => 'admin/config', 'expect' => $default_string, - 'expected_method_id' => LANGUAGE_NEGOTIATION_SELECTED, + 'expected_method_id' => LanguageNegotiationSelected::METHOD_ID, 'http_header' => array(), 'message' => 'USER > DEFAULT: invalid preferred user language setting, the UI language is default', ); @@ -274,10 +277,10 @@ function testUILanguageNegotiation() { $account->save(); $test = array( - 'language_negotiation' => array(LANGUAGE_NEGOTIATION_USER, LANGUAGE_NEGOTIATION_SELECTED), + 'language_negotiation' => array(LanguageNegotiationUser::METHOD_ID, LanguageNegotiationSelected::METHOD_ID), 'path' => 'admin/config', 'expect' => $language_string, - 'expected_method_id' => LANGUAGE_NEGOTIATION_USER, + 'expected_method_id' => LanguageNegotiationUser::METHOD_ID, 'http_header' => array(), 'message' => 'USER > DEFAULT: defined prefereed user language setting, the UI language is based on user setting', ); @@ -288,10 +291,10 @@ function testUILanguageNegotiation() { $account->save(); $test = array( - 'language_negotiation' => array(LANGUAGE_NEGOTIATION_USER_ADMIN, LANGUAGE_NEGOTIATION_SELECTED), + 'language_negotiation' => array(LanguageNegotiationUserAdmin::METHOD_ID, LanguageNegotiationSelected::METHOD_ID), 'path' => 'admin/config', 'expect' => $default_string, - 'expected_method_id' => LANGUAGE_NEGOTIATION_SELECTED, + 'expected_method_id' => LanguageNegotiationSelected::METHOD_ID, 'http_header' => array(), 'message' => 'USER ADMIN > DEFAULT: no preferred user admin language setting, the UI language is default', ); @@ -302,10 +305,10 @@ function testUILanguageNegotiation() { $account->save(); $test = array( - 'language_negotiation' => array(LANGUAGE_NEGOTIATION_USER_ADMIN, LANGUAGE_NEGOTIATION_SELECTED), + 'language_negotiation' => array(LanguageNegotiationUserAdmin::METHOD_ID, LanguageNegotiationSelected::METHOD_ID), 'path' => 'admin/config', 'expect' => $default_string, - 'expected_method_id' => LANGUAGE_NEGOTIATION_SELECTED, + 'expected_method_id' => LanguageNegotiationSelected::METHOD_ID, 'http_header' => array(), 'message' => 'USER ADMIN > DEFAULT: invalid preferred user admin language setting, the UI language is default', ); @@ -316,50 +319,14 @@ function testUILanguageNegotiation() { $account->save(); $test = array( - 'language_negotiation' => array(LANGUAGE_NEGOTIATION_USER_ADMIN, LANGUAGE_NEGOTIATION_SELECTED), + 'language_negotiation' => array(LanguageNegotiationUserAdmin::METHOD_ID, LanguageNegotiationSelected::METHOD_ID), 'path' => 'admin/config', 'expect' => $language_string, - 'expected_method_id' => LANGUAGE_NEGOTIATION_USER_ADMIN, + 'expected_method_id' => LanguageNegotiationUserAdmin::METHOD_ID, 'http_header' => array(), 'message' => 'USER ADMIN > DEFAULT: defined prefereed user admin language setting, the UI language is based on user setting', ); $this->runTest($test); - - // Setup for domain negotiation, first configure the language to have domain - // URL. - $edit = array("domain[$langcode]" => $language_domain); - $this->drupalPostForm("admin/config/regional/language/detection/url", $edit, t('Save configuration')); - // Set the site to use domain language negotiation. - - $tests = array( - // Default domain, browser preference should have no influence. - array( - 'language_negotiation' => array(LANGUAGE_NEGOTIATION_URL, LANGUAGE_NEGOTIATION_SELECTED), - 'language_negotiation_url_part' => LANGUAGE_NEGOTIATION_URL_DOMAIN, - 'path' => 'admin/config', - 'expect' => $default_string, - 'expected_method_id' => LANGUAGE_NEGOTIATION_SELECTED, - 'http_header' => $http_header_browser_fallback, - 'message' => 'URL (DOMAIN) > DEFAULT: default domain should get default language', - ), - // Language domain specific URL, we set the 'HTTP_HOST' property of - // \Drupal::request()->server in \Drupal\language_test\LanguageTestManager - // to simulate this. - array( - 'language_negotiation' => array(LANGUAGE_NEGOTIATION_URL, LANGUAGE_NEGOTIATION_SELECTED), - 'language_negotiation_url_part' => LANGUAGE_NEGOTIATION_URL_DOMAIN, - 'language_test_domain' => $language_domain . ':88', - 'path' => 'admin/config', - 'expect' => $language_string, - 'expected_method_id' => LANGUAGE_NEGOTIATION_URL, - 'http_header' => $http_header_browser_fallback, - 'message' => 'URL (DOMAIN) > DEFAULT: domain example.cn should switch to Chinese', - ), - ); - - foreach ($tests as $test) { - $this->runTest($test); - } } protected function runTest($test) { @@ -371,6 +338,7 @@ protected function runTest($test) { \Drupal::config('language.negotiation') ->set('url.source', $test['language_negotiation_url_part']) ->save(); + language_negotiation_rebuild_settings(); } if (!empty($test['language_test_domain'])) { \Drupal::state()->set('language_test.domain', $test['language_test_domain']); @@ -449,7 +417,7 @@ function testLanguageDomain() { // Change the domain for the Italian language. $edit = array( - 'language_negotiation_url_part' => LANGUAGE_NEGOTIATION_URL_DOMAIN, + 'language_negotiation_url_part' => LanguageNegotiationUrl::CONFIG_DOMAIN, 'domain[it]' => 'it.example.com', ); $this->drupalPostForm('admin/config/regional/language/detection/url', $edit, t('Save configuration')); diff --git a/core/modules/language/lib/Drupal/language/Tests/LanguageUrlRewritingTest.php b/core/modules/language/lib/Drupal/language/Tests/LanguageUrlRewritingTest.php index 07ee9a9..847348e 100644 --- a/core/modules/language/lib/Drupal/language/Tests/LanguageUrlRewritingTest.php +++ b/core/modules/language/lib/Drupal/language/Tests/LanguageUrlRewritingTest.php @@ -7,6 +7,7 @@ namespace Drupal\language\Tests; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl; use Drupal\simpletest\WebTestBase; use Symfony\Component\HttpFoundation\Request; @@ -46,8 +47,6 @@ function setUp() { $edit = array('language_interface[enabled][language-url]' => 1); $this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings')); - // Reset static caching. - drupal_static_reset('language_list'); } /** @@ -105,7 +104,7 @@ private function checkUrl($language, $message1, $message2) { function testDomainNameNegotiationPort() { $language_domain = 'example.fr'; $edit = array( - 'language_negotiation_url_part' => LANGUAGE_NEGOTIATION_URL_DOMAIN, + 'language_negotiation_url_part' => LanguageNegotiationUrl::CONFIG_DOMAIN, 'domain[fr]' => $language_domain ); $this->drupalPostForm('admin/config/regional/language/detection/url', $edit, t('Save configuration')); @@ -115,11 +114,11 @@ function testDomainNameNegotiationPort() { // Enable domain configuration. \Drupal::config('language.negotiation') - ->set('url.source', LANGUAGE_NEGOTIATION_URL_DOMAIN) + ->set('url.source', LanguageNegotiationUrl::CONFIG_DOMAIN) ->save(); // Reset static caching. - drupal_static_reset('language_list'); + $this->container->get('language_manager')->reset(); // In case index.php is part of the URLs, we need to adapt the asserted // URLs as well. diff --git a/core/modules/language/tests/Drupal/language/Tests/LanguageNegotiationUrlTest.php b/core/modules/language/tests/Drupal/language/Tests/LanguageNegotiationUrlTest.php new file mode 100644 index 0000000..37409fa --- /dev/null +++ b/core/modules/language/tests/Drupal/language/Tests/LanguageNegotiationUrlTest.php @@ -0,0 +1,165 @@ + 'Language negotiation URL', + 'description' => 'Tests the URL/domain Language negotiation plugin', + 'group' => 'Language', + ); + } + + /** + * {@inheritdoc} + */ + public function setUp() { + + // Set up some languages to be used by the language-based path processor. + $languages = array( + 'de' => (object) array( + 'id' => 'de', + ), + 'en' => (object) array( + 'id' => 'en', + ), + ); + + // Create a language manager stub. + $language_manager = $this->getMockBuilder('Drupal\language\ConfigurableLanguageManagerInterface') + ->getMock(); + $language_manager->expects($this->any()) + ->method('getLanguage') + ->will($this->returnValue($languages['en'])); + $language_manager->expects($this->any()) + ->method('getLanguageList') + ->will($this->returnValue($languages)); + $this->languageManager = $language_manager; + + // Create a user stub. + $this->user = $this->getMockBuilder('Drupal\Core\Session\AccountInterface') + ->getMock(); + } + + /** + * Test domain language negotiation. + * + * @dataProvider providerTestDomain + */ + public function testDomain($http_host, $domains, $expected_langcode) { + $config_data = array( + 'source' => LanguageNegotiationUrl::CONFIG_DOMAIN, + 'domains' => $domains, + ); + + $config_object = $this->getMockBuilder('Drupal\Core\Config\Config') + ->disableOriginalConstructor() + ->getMock(); + $config_object->expects($this->any()) + ->method('get') + ->with('url') + ->will($this->returnValue($config_data)); + + $config = $this->getMockBuilder('Drupal\Core\Config\ConfigFactory') + ->disableOriginalConstructor() + ->getMock(); + $config->expects($this->any()) + ->method('get') + ->with('language.negotiation') + ->will($this->returnValue($config_object)); + + $request = Request::create('', 'GET', array(), array(), array(), array('HTTP_HOST' => $http_host)); + $method = new LanguageNegotiationUrl(); + $method->setLanguageManager($this->languageManager); + $method->setConfig($config); + $method->setCurrentUser($this->user); + $this->assertEquals($expected_langcode, $method->negotiateLanguage($request)); + } + + /** + * Provides data for the domain test. + * + * @return array + * An array of data for checking domain negotation. + */ + public function providerTestDomain() { + + $domain_configuration[] = array( + 'http_host' => 'example.de', + 'domains' => array( + 'de' => 'http://example.de', + ), + 'expected_langocde' => 'de', + ); + // No configuration. + $domain_configuration[] = array( + 'http_host' => 'example.de', + 'domains' => array(), + 'expected_langocde' => FALSE, + ); + // HTTP host with a port. + $domain_configuration[] = array( + 'http_host' => 'example.de:8080', + 'domains' => array( + 'de' => 'http://example.de', + ), + 'expected_langocde' => 'de', + ); + // Domain configuration with https://. + $domain_configuration[] = array( + 'http_host' => 'example.de', + 'domains' => array( + 'de' => 'https://example.de', + ), + 'expected_langocde' => 'de', + ); + // Non-matching HTTP host. + $domain_configuration[] = array( + 'http_host' => 'example.com', + 'domains' => array( + 'de' => 'http://example.com', + ), + 'expected_langocde' => 'de', + ); + // Testing a non-existing language. + $domain_configuration[] = array( + 'http_host' => 'example.com', + 'domains' => array( + 'it' => 'http://example.it', + ), + 'expected_langocde' => FALSE, + ); + // Multiple domain configurations. + $domain_configuration[] = array( + 'http_host' => 'example.com', + 'domains' => array( + 'de' => 'http://example.de', + 'en' => 'http://example.com', + ), + 'expected_langocde' => 'en', + ); + return $domain_configuration; + } +} diff --git a/core/modules/language/tests/language_elements_test/language_elements_test.info.yml b/core/modules/language/tests/language_elements_test/language_elements_test.info.yml index 254c5f6..9fc44c1 100644 --- a/core/modules/language/tests/language_elements_test/language_elements_test.info.yml +++ b/core/modules/language/tests/language_elements_test/language_elements_test.info.yml @@ -4,4 +4,4 @@ description: 'Support module for the language form elements tests.' core: 8.x package: Testing version: VERSION -hidden: true +#hidden: true diff --git a/core/modules/language/tests/language_test/language_test.module b/core/modules/language/tests/language_test/language_test.module index 8e8cbaf..70f349c 100644 --- a/core/modules/language/tests/language_test/language_test.module +++ b/core/modules/language/tests/language_test/language_test.module @@ -5,10 +5,8 @@ * Mock module for language layer tests. */ -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpKernel\HttpKernelInterface; - use Drupal\Core\Language\Language; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUI; /** * Implements hook_page_build(). @@ -56,38 +54,11 @@ function language_test_language_types_info_alter(array &$language_types) { } /** - * Implements hook_language_negotiation_info(). - */ -function language_test_language_negotiation_info() { - if (\Drupal::state()->get('language_test.language_negotiation_info')) { - $info = array( - 'callbacks' => array( - 'negotiation' => 'language_test_language_negotiation_method', - ), - 'file' => drupal_get_path('module', 'language_test') .'/language_test.module', - 'weight' => -10, - 'description' => t('This is a test language negotiation method.'), - ); - - return array( - 'test_language_negotiation_method' => array( - 'name' => t('Test'), - 'types' => array(Language::TYPE_CONTENT, 'test_language_type', 'fixed_test_language_type'), - ) + $info, - 'test_language_negotiation_method_ts' => array( - 'name' => t('Type-specific test'), - 'types' => array('test_language_type'), - ) + $info, - ); - } -} - -/** * Implements hook_language_negotiation_info_alter(). */ function language_test_language_negotiation_info_alter(array &$negotiation_info) { if (\Drupal::state()->get('language_test.language_negotiation_info_alter')) { - unset($negotiation_info[LANGUAGE_NEGOTIATION_INTERFACE]); + unset($negotiation_info[LanguageNegotiationUI::METHOD_ID]); } } @@ -96,21 +67,13 @@ function language_test_language_negotiation_info_alter(array &$negotiation_info) */ function language_test_store_language_negotiation() { $last = array(); - print_r(language_types_get_all()); - foreach (language_types_get_all() as $type) { + foreach (Drupal::languageManager()->getLanguageTypes() as $type) { $last[$type] = language($type)->id; } \Drupal::state()->set('language_test.language_negotiation_last', $last); } /** - * Provides a test language negotiation method. - */ -function language_test_language_negotiation_method($languages) { - return 'it'; -} - -/** * Implements hook_language_fallback_candidates_alter(). */ function language_test_language_fallback_candidates_alter(array &$candidates, array $context) { diff --git a/core/modules/language/tests/language_test/lib/Drupal/language_test/LanguageTestManager.php b/core/modules/language/tests/language_test/lib/Drupal/language_test/LanguageTestManager.php deleted file mode 100644 index 3c460b6..0000000 --- a/core/modules/language/tests/language_test/lib/Drupal/language_test/LanguageTestManager.php +++ /dev/null @@ -1,28 +0,0 @@ -get('language_test.domain')) { - \Drupal::request()->server->set('HTTP_HOST', $test_domain); - } - return parent::init(); - } - -} diff --git a/core/modules/language/tests/language_test/lib/Drupal/language_test/LanguageTestServiceProvider.php b/core/modules/language/tests/language_test/lib/Drupal/language_test/LanguageTestServiceProvider.php deleted file mode 100644 index 39aef04..0000000 --- a/core/modules/language/tests/language_test/lib/Drupal/language_test/LanguageTestServiceProvider.php +++ /dev/null @@ -1,28 +0,0 @@ -getDefinition('language_manager'); - $definition->setClass('Drupal\language_test\LanguageTestManager'); - } - -} - diff --git a/core/modules/language/tests/language_test/lib/Drupal/language_test/Plugin/LanguageNegotiation/LanguageNegotiationTest.php b/core/modules/language/tests/language_test/lib/Drupal/language_test/Plugin/LanguageNegotiation/LanguageNegotiationTest.php new file mode 100644 index 0000000..8787ff4 --- /dev/null +++ b/core/modules/language/tests/language_test/lib/Drupal/language_test/Plugin/LanguageNegotiation/LanguageNegotiationTest.php @@ -0,0 +1,38 @@ +translateFilterValues(); $langcode = $filter_values['langcode']; - drupal_static_reset('language_list'); + $this->languageManager->reset(); $languages = language_list(); $langname = isset($langcode) ? $languages[$langcode]->name : "- None -"; diff --git a/core/modules/locale/lib/Drupal/locale/Form/TranslateFormBase.php b/core/modules/locale/lib/Drupal/locale/Form/TranslateFormBase.php index ea4c9ce..5e94cf6 100644 --- a/core/modules/locale/lib/Drupal/locale/Form/TranslateFormBase.php +++ b/core/modules/locale/lib/Drupal/locale/Form/TranslateFormBase.php @@ -161,7 +161,7 @@ protected function translateFilters() { $filters = array(); // Get all languages, except English. - drupal_static_reset('language_list'); + $this->languageManager->reset(); $languages = language_list(); $language_options = array(); foreach ($languages as $langcode => $language) { diff --git a/core/modules/locale/lib/Drupal/locale/Tests/LocaleContentTest.php b/core/modules/locale/lib/Drupal/locale/Tests/LocaleContentTest.php index 87febe4..1c2c597 100644 --- a/core/modules/locale/lib/Drupal/locale/Tests/LocaleContentTest.php +++ b/core/modules/locale/lib/Drupal/locale/Tests/LocaleContentTest.php @@ -47,7 +47,6 @@ function testMachineNameLTR() { $edit = array(); $edit['predefined_langcode'] = 'ar'; $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language')); - drupal_static_reset('language_list'); $edit = array( 'site_default_language' => 'ar', @@ -84,7 +83,6 @@ function testContentTypeLanguageConfiguration() { 'direction' => '0', ); $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language')); - drupal_static_reset('language_list'); // Set the content type to use multilingual support. $this->drupalGet("admin/structure/types/manage/{$type2->type}"); @@ -95,7 +93,7 @@ function testContentTypeLanguageConfiguration() { $this->drupalPostForm("admin/structure/types/manage/{$type2->type}", $edit, t('Save content type')); $this->assertRaw(t('The content type %type has been updated.', array('%type' => $type2->name))); $this->drupalLogout(); - drupal_static_reset('language_list'); + \Drupal::languageManager()->reset(); // Verify language selection is not present on the node add form. $this->drupalLogin($web_user); @@ -152,13 +150,12 @@ function testContentTypeDirLang() { $edit = array(); $edit['predefined_langcode'] = 'ar'; $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language')); - drupal_static_reset('language_list'); + \Drupal::languageManager()->reset(); // Install Spanish language. $edit = array(); $edit['predefined_langcode'] = 'es'; $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language')); - drupal_static_reset('language_list'); // Set the content type to use multilingual support. $this->drupalGet("admin/structure/types/manage/{$type->type}"); @@ -222,7 +219,6 @@ function testNodeAdminLanguageFilter() { // Enable multiple languages. $this->drupalPostForm('admin/config/regional/language/edit/en', array('locale_translate_english' => TRUE), t('Save language')); $this->drupalPostForm('admin/config/regional/language/add', array('predefined_langcode' => 'zh-hant'), t('Add language')); - drupal_static_reset('language_list'); // Create two nodes: English and Chinese. $node_en = $this->drupalCreateNode(array('langcode' => 'en')); diff --git a/core/modules/locale/lib/Drupal/locale/Tests/LocaleTranslationUiTest.php b/core/modules/locale/lib/Drupal/locale/Tests/LocaleTranslationUiTest.php index d02f763..a9ce77f 100644 --- a/core/modules/locale/lib/Drupal/locale/Tests/LocaleTranslationUiTest.php +++ b/core/modules/locale/lib/Drupal/locale/Tests/LocaleTranslationUiTest.php @@ -223,7 +223,7 @@ function testJavaScriptTranslation() { 'direction' => '0', ); $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language')); - drupal_static_reset('language_list'); + $this->container->get('language_manager')->reset(); // Build the JavaScript translation file. diff --git a/core/modules/locale/lib/Drupal/locale/Tests/LocaleUninstallTest.php b/core/modules/locale/lib/Drupal/locale/Tests/LocaleUninstallTest.php index cd8ec73..9367df9 100644 --- a/core/modules/locale/lib/Drupal/locale/Tests/LocaleUninstallTest.php +++ b/core/modules/locale/lib/Drupal/locale/Tests/LocaleUninstallTest.php @@ -7,6 +7,8 @@ namespace Drupal\locale\Tests; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationSelected; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl; use Drupal\simpletest\WebTestBase; use Drupal\Core\Language\Language; use Drupal\Component\Utility\String; @@ -90,14 +92,14 @@ function testUninstallProcess() { // Change language negotiation options. drupal_load('module', 'locale'); - \Drupal::config('system.language.types')->set('configurable', language_types_get_default() + array('language_custom' => TRUE))->save(); - variable_set('language_negotiation_' . Language::TYPE_INTERFACE, language_language_negotiation_info()); - variable_set('language_negotiation_' . Language::TYPE_CONTENT, language_language_negotiation_info()); - variable_set('language_negotiation_' . Language::TYPE_URL, language_language_negotiation_info()); + \Drupal::config('system.language.types')->set('configurable', $this->container->get('language_manager')->getTypeDefaults() + array('language_custom' => TRUE))->save(); + variable_set('language_negotiation_' . Language::TYPE_INTERFACE, array_flip(array_keys(language_negotiation_info()))); + variable_set('language_negotiation_' . Language::TYPE_CONTENT, array_flip(array_keys(language_negotiation_info()))); + variable_set('language_negotiation_' . Language::TYPE_URL, array_flip(array_keys(language_negotiation_info()))); // Change language negotiation settings. \Drupal::config('language.negotiation') - ->set('url.source', LANGUAGE_NEGOTIATION_URL_PREFIX) + ->set('url.source', LanguageNegotiationUrl::CONFIG_PATH_PREFIX) ->set('session.parameter', TRUE) ->save(); @@ -113,18 +115,13 @@ function testUninstallProcess() { // Check JavaScript files deletion. $this->assertTrue($result = !file_exists($js_file), String::format('JavaScript file deleted: %file', array('%file' => $result ? $js_file : 'found'))); - // Check language count. - $language_count = $this->container->get('state')->get('language_count') ?: 1; - $this->assertEqual($language_count, 1, String::format('Language count: %count', array('%count' => $language_count))); - // Check language negotiation. - require_once DRUPAL_ROOT . '/core/includes/language.inc'; - $this->assertTrue(count(language_types_get_all()) == count(language_types_get_default()), 'Language types reset'); - $language_negotiation = language_negotiation_method_get_first(Language::TYPE_INTERFACE) == LANGUAGE_NEGOTIATION_SELECTED; + $this->assertTrue(count($this->container->get('language_manager')->getLanguageTypes()) == count($this->container->get('language_manager')->getTypeDefaults()), 'Language types reset'); + $language_negotiation = language_negotiation_method_get_first(Language::TYPE_INTERFACE) == LanguageNegotiationSelected::METHOD_ID; $this->assertTrue($language_negotiation, String::format('Interface language negotiation: %setting', array('%setting' => $language_negotiation ? 'none' : 'set'))); - $language_negotiation = language_negotiation_method_get_first(Language::TYPE_CONTENT) == LANGUAGE_NEGOTIATION_SELECTED; + $language_negotiation = language_negotiation_method_get_first(Language::TYPE_CONTENT) == LanguageNegotiationSelected::METHOD_ID; $this->assertTrue($language_negotiation, String::format('Content language negotiation: %setting', array('%setting' => $language_negotiation ? 'none' : 'set'))); - $language_negotiation = language_negotiation_method_get_first(Language::TYPE_URL) == LANGUAGE_NEGOTIATION_SELECTED; + $language_negotiation = language_negotiation_method_get_first(Language::TYPE_URL) == LanguageNegotiationSelected::METHOD_ID; $this->assertTrue($language_negotiation, String::format('URL language negotiation: %setting', array('%setting' => $language_negotiation ? 'none' : 'set'))); // Check language negotiation method settings. diff --git a/core/modules/locale/lib/Drupal/locale/Tests/LocaleUpdateBase.php b/core/modules/locale/lib/Drupal/locale/Tests/LocaleUpdateBase.php index 1d88e2b..01d7361 100644 --- a/core/modules/locale/lib/Drupal/locale/Tests/LocaleUpdateBase.php +++ b/core/modules/locale/lib/Drupal/locale/Tests/LocaleUpdateBase.php @@ -74,7 +74,7 @@ protected function setTranslationsDirectory($path) { protected function addLanguage($langcode) { $edit = array('predefined_langcode' => $langcode); $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language')); - drupal_static_reset('language_list'); + $this->container->get('language_manager')->reset(); $this->assertTrue(language_load($langcode), String::format('Language %langcode added.', array('%langcode' => $langcode))); } diff --git a/core/modules/locale/locale.bulk.inc b/core/modules/locale/locale.bulk.inc index 5256244..eb0dfe4 100644 --- a/core/modules/locale/locale.bulk.inc +++ b/core/modules/locale/locale.bulk.inc @@ -21,7 +21,7 @@ * @deprecated Use \Drupal\locale\Form\LocaleForm::import() */ function locale_translate_import_form($form, &$form_state) { - drupal_static_reset('language_list'); + Drupal::languageManager()->reset(); $languages = language_list(); // Initialize a language list to the ones available, including English if we diff --git a/core/modules/locale/locale.install b/core/modules/locale/locale.install index 5c98791..96446b1 100644 --- a/core/modules/locale/locale.install +++ b/core/modules/locale/locale.install @@ -6,6 +6,7 @@ */ use Drupal\Core\Language\Language; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationSelected; /** * Implements hook_install(). @@ -500,20 +501,10 @@ function locale_update_8004() { $types = update_variable_get('language_types', NULL); if (!empty($types)) { foreach ($types as $type => $configurable) { - // Rename the negotiation and language switch callback keys. + // Change the structure of the language negotiation configuration. $negotiation = update_variable_get('language_negotiation_' . $type, NULL); if (!empty($negotiation)) { - foreach ($negotiation as &$method) { - if (isset($method['callbacks']['language'])) { - $method['callbacks']['negotiation'] = $method['callbacks']['language']; - unset($method['callbacks']['language']); - } - if (isset($method['callbacks']['switcher'])) { - $method['callbacks']['language_switch'] = $method['callbacks']['switcher']; - unset($method['callbacks']['switcher']); - } - } - update_variable_set('language_negotiation_' . $type, $negotiation); + update_variable_set('language_negotiation_' . $type, array_keys($negotiation)); } // Rename the language negotiation methods weight variable. @@ -646,16 +637,11 @@ function locale_update_8005() { } /** - * Convert language_negotiation_* variables to use the new callbacks. + * Convert language_negotiation_* variables. * * @ingroup config_upgrade */ function locale_update_8007() { - $variable_names = array( - 'language_negotiation_language_interface', - 'language_negotiation_language_content', - 'language_negotiation_language_url', - ); // Add all language type weight variables. As the function language_types() // is not available its functionality is rebuild. $language_types = update_variable_get('language_types', array( @@ -664,20 +650,9 @@ function locale_update_8007() { Language::TYPE_URL => FALSE, )); foreach ($language_types as $language_type => $configurable) { - $variable_names[] = 'language_negotiation_methods_weight_' . $language_type; + $variable_names['language_negotiation_' . $language_type] = 'language_negotiation_methods_weight_' . $language_type; } - $callback_map = array( - 'locale_language_from_url' => 'language_from_url', - 'locale_language_switcher_url' => 'language_switcher_url', - 'locale_language_url_rewrite_url' => 'language_url_rewrite_url', - 'locale_language_from_session' => 'language_from_session', - 'locale_language_switcher_session' => 'language_switcher_session', - 'locale_language_url_rewrite_session' => 'language_url_rewrite_session', - 'locale_language_from_user' => 'language_from_user', - 'locale_language_from_browser' => 'language_from_browser', - 'locale_language_url_fallback' => 'language_url_fallback', - 'locale_language_from_interface' => 'language_from_interface', - ); + $type_map = array( 'locale-interface' => 'language-interface', 'locale-url' => 'language-url', @@ -686,37 +661,24 @@ function locale_update_8007() { 'locale-user' => 'language-user', 'locale-session' => 'language-session', ); - foreach ($variable_names as $variable_name) { - $value = update_variable_get($variable_name); + foreach ($variable_names as $variable_name => $weight_variable_name) { + $value = update_variable_get($weight_variable_name); // Skip processing if the variable is not stored in the db. if ($value === NULL) { + update_variable_del($variable_name); continue; } - $new_value = $value; - foreach ($value as $type => $type_settings) { - // Convert the file. - if (isset($type_settings['file']) && (strpos($type_settings['file'], 'core/includes/locale.inc') !== FALSE)) { - $new_value[$type]['file'] = 'core/modules/language/language.negotiation.inc'; - } - // Convert the callbacks. - if (is_array($type_settings) && isset($type_settings['callbacks'])) { - foreach ($type_settings['callbacks'] as $key => $callback) { - if (isset($callback_map[$callback])) { - $new_value[$type]['callbacks'][$key] = $callback_map[$callback]; - } - } - } + $new_value = array(); + foreach ($value as $type => $weight) { // Convert the type. if (isset($type_map[$type])) { - $new_value[$type_map[$type]] = $new_value[$type]; - unset($new_value[$type]); + $type = $type_map[$type]; } + $new_value[$type] = $weight; } - // If necessary maintain the order of the values / keys of the variable. - if (stristr($variable_name, 'language_negotiation_methods_weight_') !== FALSE) { - asort($new_value); - } + asort($new_value); update_variable_set($variable_name, $new_value); + update_variable_del($weight_variable_name); } } @@ -845,25 +807,11 @@ function locale_update_8011() { * Renames language_default language negotiation method to language_selected. */ function locale_update_8013() { - // @todo We only need language.inc here because LANGUAGE_NEGOTIATION_SELECTED - // is defined there. Remove this line once that has been converted to a class - // constant. - require_once DRUPAL_ROOT . '/core/includes/language.inc'; - $weight = update_variable_get('language_negotiation_methods_weight_language_interface', NULL); + $weight = update_variable_get('language_negotiation_language_interface', NULL); if ($weight !== NULL) { - $weight[LANGUAGE_NEGOTIATION_SELECTED] = $weight['language-default']; + $weight[LanguageNegotiationSelected::METHOD_ID] = $weight['language-default']; unset($weight['language-default']); - update_variable_set('language_negotiation_methods_weight_language_interface', $weight); - } - - $negotiation_interface = update_variable_get('language_negotiation_language_interface', NULL); - if ($negotiation_interface !== NULL) { - if (isset($negotiation_interface['language-default'])) { - $negotiation_interface[LANGUAGE_NEGOTIATION_SELECTED] = $negotiation_interface['language-default']; - $negotiation_interface[LANGUAGE_NEGOTIATION_SELECTED]['callbacks']['negotiation'] = 'language_from_selected'; - unset($negotiation_interface['language-default']); - update_variable_set('language_negotiation_language_interface', $negotiation_interface); - } + update_variable_set('language_negotiation_language_interface', $weight); } } diff --git a/core/modules/node/lib/Drupal/node/Tests/NodeFieldMultilingualTestCase.php b/core/modules/node/lib/Drupal/node/Tests/NodeFieldMultilingualTestCase.php index f535182..a363043 100644 --- a/core/modules/node/lib/Drupal/node/Tests/NodeFieldMultilingualTestCase.php +++ b/core/modules/node/lib/Drupal/node/Tests/NodeFieldMultilingualTestCase.php @@ -7,6 +7,7 @@ namespace Drupal\node\Tests; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl; use Drupal\simpletest\WebTestBase; use Drupal\Core\Language\Language; @@ -99,7 +100,7 @@ function testMultilingualNodeForm() { $this->assertTrue($node->language()->id == $langcode && $node->body->value == $body_value, 'Field language correctly changed.'); // Enable content language URL detection. - language_negotiation_set(Language::TYPE_CONTENT, array(LANGUAGE_NEGOTIATION_URL => 0)); + language_negotiation_set(Language::TYPE_CONTENT, array(LanguageNegotiationUrl::METHOD_ID => 0)); // Test multilingual field language fallback logic. $this->drupalGet("it/node/{$node->id()}"); diff --git a/core/modules/path/lib/Drupal/path/Tests/PathLanguageTest.php b/core/modules/path/lib/Drupal/path/Tests/PathLanguageTest.php index 4f94f43..0653743 100644 --- a/core/modules/path/lib/Drupal/path/Tests/PathLanguageTest.php +++ b/core/modules/path/lib/Drupal/path/Tests/PathLanguageTest.php @@ -104,7 +104,7 @@ function testAliasTranslation() { $this->container->get('path.alias_manager')->cacheClear(); // Languages are cached on many levels, and we need to clear those caches. - drupal_static_reset('language_list'); + $this->container->get('language_manager')->reset(); $this->rebuildContainer(); $languages = language_list(); @@ -117,7 +117,10 @@ function testAliasTranslation() { $this->drupalGet('fr/' . $edit['path[alias]']); $this->assertText($french_node->body->value, 'Alias for French translation works.'); - // Confirm that the alias is returned by url(). + // Confirm that the alias is returned by url(). Languages are cached on + // many levels, and we need to clear those caches. + $this->container->get('language_manager')->reset(); + $languages = language_list(); $url = $this->container->get('url_generator')->generateFromPath('node/' . $french_node->id(), array('language' => $languages['fr'])); $this->assertTrue(strpos($url, $edit['path[alias]']), 'URL contains the path alias.'); diff --git a/core/modules/system/language.api.php b/core/modules/system/language.api.php index baafb7a..77df1b2 100644 --- a/core/modules/system/language.api.php +++ b/core/modules/system/language.api.php @@ -49,7 +49,7 @@ function hook_language_switch_links_alter(array &$links, $type, $path) { * - fixed: A fixed array of language negotiation method identifiers to use to * initialize this language. If locked is set to TRUE and fixed is set, it * will always use the specified methods in the given priority order. If not - * present and locked is TRUE then LANGUAGE_NEGOTIATION_INTERFACE will be + * present and locked is TRUE then language-interface will be * used. * * @todo Rename the 'fixed' key to something more meaningful, for instance @@ -88,55 +88,6 @@ function hook_language_types_info_alter(array &$language_types) { } /** - * Define language negotiation methods. - * - * @return - * An associative array of language negotiation method definitions. The keys - * are method identifiers, and the values are associative arrays defining - * each method, with the following elements: - * - types: An array of allowed language types. If a language negotiation - * method does not specify which language types it should be used with, it - * will be available for all the configurable language types. - * - callbacks: An associative array of functions that will be called to - * perform various tasks. Possible elements are: - * - negotiation: (required) Name of the callback function that determines - * the language value. - * - language_switch: (optional) Name of the callback function that - * determines links for a language switcher block associated with this - * method. See language_switcher_url() for an example. - * - url_rewrite: (optional) Name of the callback function that provides URL - * rewriting, if needed by this method. - * - file: The file where callback functions are defined (this file will be - * included before the callbacks are invoked). - * - weight: The default weight of the method. - * - name: The translated human-readable name for the method. - * - description: A translated longer description of the method. - * - config: An internal path pointing to the method's configuration page. - * - cache: The value Drupal's page cache should be set to for the current - * method to be invoked. - * - * @see hook_language_negotiation_info_alter() - * @ingroup language_negotiation - */ -function hook_language_negotiation_info() { - return array( - 'custom_language_negotiation_method' => array( - 'callbacks' => array( - 'negotiation' => 'custom_negotiation_callback', - 'language_switch' => 'custom_language_switch_callback', - 'url_rewrite' => 'custom_url_rewrite_callback', - ), - 'file' => drupal_get_path('module', 'custom') . '/custom.module', - 'weight' => -4, - 'types' => array('custom_language_type'), - 'name' => t('Custom language negotiation method'), - 'description' => t('This is a custom language negotiation method.'), - 'cache' => 0, - ), - ); -} - -/** * Perform alterations on language negotiation methods. * * @param $negotiation_info diff --git a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityLanguageTestBase.php b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityLanguageTestBase.php index 2e60246..f8660dd 100644 --- a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityLanguageTestBase.php +++ b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityLanguageTestBase.php @@ -15,6 +15,18 @@ */ abstract class EntityLanguageTestBase extends EntityUnitTestBase { + /** + * The language manager service. + * + * @var \Drupal\Core\Language\LanguageManagerInterface + */ + protected $languageManager; + + /** + * The available language codes. + * + * @var array + */ protected $langcodes; /** @@ -36,6 +48,8 @@ function setUp() { parent::setUp(); + $this->languageManager = $this->container->get('language_manager'); + $this->installSchema('system', 'variable'); $this->installSchema('entity_test', array( 'entity_test_mul', diff --git a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityTranslationTest.php b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityTranslationTest.php index a084ebf..4aaee48 100644 --- a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityTranslationTest.php +++ b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityTranslationTest.php @@ -446,7 +446,7 @@ function testEntityTranslationAPI() { * Tests language fallback applied to field and entity translations. */ function testLanguageFallback() { - $current_langcode = $this->container->get('language_manager')->getLanguage(Language::TYPE_CONTENT)->id; + $current_langcode = $this->languageManager->getLanguage(Language::TYPE_CONTENT)->id; $this->langcodes[] = $current_langcode; $values = array(); @@ -473,7 +473,7 @@ function testLanguageFallback() { $this->assertEqual($translation->language()->id, $default_langcode, 'The current translation language matches the expected one.'); // Check that language fallback respects language weight by default. - $languages = language_list(); + $languages = $this->languageManager->getLanguageList(); $languages[$langcode]->weight = -1; language_save($languages[$langcode]); $translation = $this->entityManager->getTranslationFromContext($entity, $langcode2); diff --git a/core/modules/system/lib/Drupal/system/Tests/Plugin/CacheDecoratorLanguageTest.php b/core/modules/system/lib/Drupal/system/Tests/Plugin/CacheDecoratorLanguageTest.php index 10de2a8..2e734ef 100644 --- a/core/modules/system/lib/Drupal/system/Tests/Plugin/CacheDecoratorLanguageTest.php +++ b/core/modules/system/lib/Drupal/system/Tests/Plugin/CacheDecoratorLanguageTest.php @@ -69,6 +69,7 @@ public function setUp() { $custom_strings[$definition['label']] = $langcode . ' ' . $definition['label']; } $this->addCustomTranslations($langcode, array('' => $custom_strings)); + $this->rebuildContainer(); } // Write test settings.php with new translations. $this->writeCustomTranslations(); diff --git a/core/modules/system/lib/Drupal/system/Tests/Theme/TwigTransTest.php b/core/modules/system/lib/Drupal/system/Tests/Theme/TwigTransTest.php index 48d1e1f..8ce7d1a 100644 --- a/core/modules/system/lib/Drupal/system/Tests/Theme/TwigTransTest.php +++ b/core/modules/system/lib/Drupal/system/Tests/Theme/TwigTransTest.php @@ -84,7 +84,7 @@ protected function setUp() { $this->drupalPostForm('admin/config/regional/settings', $edit, t('Save configuration')); // Reset the static cache of the language list. - drupal_static_reset('language_list'); + $this->container->get('language_manager')->reset(); // Check that lolspeak is the default language for the site. $this->assertEqual(language_default()->id, 'xx', 'Lolspeak is the default language'); @@ -251,6 +251,7 @@ protected function installLanguages() { drupal_unlink($filename); } } + $this->container->get('language_manager')->reset(); } /** diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermLanguageTest.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermLanguageTest.php index 9201129..f71160b 100644 --- a/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermLanguageTest.php +++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermLanguageTest.php @@ -79,6 +79,9 @@ function testTermLanguage() { } function testDefaultTermLanguage() { + // @todo: Why is this necessary? + language_negotiation_rebuild_settings(); + // Configure the vocabulary to not hide the language selector, and make the // default language of the terms fixed. $edit = array( diff --git a/core/modules/tour/lib/Drupal/tour/Tests/TourTest.php b/core/modules/tour/lib/Drupal/tour/Tests/TourTest.php index fcae023..d671af3 100644 --- a/core/modules/tour/lib/Drupal/tour/Tests/TourTest.php +++ b/core/modules/tour/lib/Drupal/tour/Tests/TourTest.php @@ -108,6 +108,7 @@ public function testTourFunctionality() { // Enable Italian language and navigate to it/tour-test1 and verify italian // version of tip is found. language_save(new Language(array('id' => 'it'))); + language_negotiation_rebuild_settings(); $this->drupalGet('it/tour-test-1'); $elements = $this->xpath('//li[@data-id=:data_id and ./h2[contains(., :text)]]', array( diff --git a/core/modules/user/lib/Drupal/user/AccountFormController.php b/core/modules/user/lib/Drupal/user/AccountFormController.php index 4983b0f..d7cd1fc 100644 --- a/core/modules/user/lib/Drupal/user/AccountFormController.php +++ b/core/modules/user/lib/Drupal/user/AccountFormController.php @@ -10,7 +10,10 @@ use Drupal\Core\Entity\ContentEntityFormController; use Drupal\Core\Entity\EntityManagerInterface; use Drupal\Core\Language\Language; -use Drupal\Core\Language\LanguageManager; +use Drupal\Core\Language\LanguageManagerInterface; +use Drupal\language\ConfigurableLanguageManagerInterface; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUserAdmin; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationSelected; use Symfony\Component\DependencyInjection\ContainerInterface; /** @@ -21,7 +24,7 @@ /** * The language manager. * - * @var \Drupal\Core\Language\LanguageManager + * @var \Drupal\Core\Language\LanguageManagerInterface */ protected $languageManager; @@ -30,10 +33,10 @@ * * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager * The entity manager. - * @param \Drupal\Core\Language\LanguageManager $language_manager + * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager * The language manager. */ - public function __construct(EntityManagerInterface $entity_manager, LanguageManager $language_manager) { + public function __construct(EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager) { parent::__construct($entity_manager); $this->languageManager = $language_manager; } @@ -215,8 +218,11 @@ public function form(array $form, array &$form_state) { $user_preferred_admin_langcode = $register ? $language_interface->id : $account->getPreferredAdminLangcode(); // Is default the interface language? - include_once DRUPAL_ROOT . '/core/includes/language.inc'; - $interface_language_is_default = language_negotiation_method_get_first(Language::TYPE_INTERFACE) != LANGUAGE_NEGOTIATION_SELECTED; + $interface_language_is_default = FALSE; + if ($this->languageManager instanceof ConfigurableLanguageManagerInterface) { + $negotiator = $this->languageManager->getNegotiator(); + $interface_language_is_default = $negotiator->getPrimaryNegotiationMethod(Language::TYPE_INTERFACE) != LanguageNegotiationSelected::METHOD_ID; + } $form['language'] = array( '#type' => $this->languageManager->isMultilingual() ? 'details' : 'container', '#title' => $this->t('Language settings'), @@ -239,7 +245,7 @@ public function form(array $form, array &$form_state) { if ($this->moduleHandler->moduleExists('language') && $this->languageManager->isMultilingual()) { foreach (language_types_info() as $type_key => $language_type) { $negotiation_settings = variable_get("language_negotiation_{$type_key}", array()); - if ($show_admin_language = isset($negotiation_settings[LANGUAGE_NEGOTIATION_USER_ADMIN])) { + if ($show_admin_language = isset($negotiation_settings[LanguageNegotiationUserAdmin::METHOD_ID])) { break; } } diff --git a/core/tests/Drupal/Tests/Core/PathProcessor/PathProcessorTest.php b/core/tests/Drupal/Tests/Core/PathProcessor/PathProcessorTest.php index f49184f..10e3366 100644 --- a/core/tests/Drupal/Tests/Core/PathProcessor/PathProcessorTest.php +++ b/core/tests/Drupal/Tests/Core/PathProcessor/PathProcessorTest.php @@ -8,6 +8,8 @@ namespace Drupal\Tests\Core\PathProcessor; use Drupal\Component\Utility\Settings; +use Drupal\Core\Language\Language; +use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl; use Drupal\Core\PathProcessor\PathProcessorAlias; use Drupal\Core\PathProcessor\PathProcessorDecode; use Drupal\Core\PathProcessor\PathProcessorFront; @@ -19,6 +21,8 @@ /** * Tests path processor functionality. + * + * @group PathApi */ class PathProcessorTest extends UnitTestCase { @@ -45,12 +49,44 @@ public function setUp() { } $this->languages = $languages; + // Create a stub configuration. + $language_prefixes = array_keys($this->languages); + $config = array( + 'url' => array( + 'prefixes' => array_combine($language_prefixes, $language_prefixes) + ) + ); + + // Create a URL-based language negotiation method definition. + $method_definitions = array( + LanguageNegotiationUrl::METHOD_ID => array( + 'class' => '\Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl', + ), + ); + + // Create a URL-based language negotiation method. + $method_instance = new LanguageNegotiationUrl($config); + // Create a language manager stub. - $language_manager = $this->getMock('Drupal\Core\Language\LanguageManager'); + $language_manager = $this->getMockBuilder('Drupal\Core\Language\LanguageManagerInterface') + ->getMock(); $language_manager->expects($this->any()) ->method('getLanguage') ->will($this->returnValue($languages['en'])); + $language_manager->expects($this->any()) + ->method('getLanguageList') + ->will($this->returnValue($this->languages)); + $language_manager->expects($this->any()) + ->method('getConfigurableLanguageTypes') + ->will($this->returnValue(array(Language::TYPE_INTERFACE))); + $language_manager->expects($this->any()) + ->method('getNegotiationMethods') + ->will($this->returnValue($method_definitions)); + $language_manager->expects($this->any()) + ->method('getNegotiationMethodInstance') + ->will($this->returnValue($method_instance)); + $method_instance->setLanguageManager($language_manager); $this->languageManager = $language_manager; } @@ -79,15 +115,11 @@ function testProcessInbound() { // Create a stub config factory with all config settings that will be checked // during this test. - $language_prefixes = array_keys($this->languages); $config_factory_stub = $this->getConfigFactoryStub( array( 'system.site' => array( 'page.front' => 'user' ), - 'language.negotiation' => array( - 'url.prefixes' => array_combine($language_prefixes, $language_prefixes) - ) ) ); @@ -95,7 +127,7 @@ function testProcessInbound() { $alias_processor = new PathProcessorAlias($alias_manager); $decode_processor = new PathProcessorDecode(); $front_processor = new PathProcessorFront($config_factory_stub); - $language_processor = new PathProcessorLanguage($config_factory_stub, new Settings(array()), $this->languageManager, $this->languages); + $language_processor = new PathProcessorLanguage($config_factory_stub, new Settings(array()), $this->languageManager); // First, test the processor manager with the processors in the incorrect // order. The alias processor will run before the language processor, meaning diff --git a/core/tests/Drupal/Tests/Core/Plugin/DefaultPluginManagerTest.php b/core/tests/Drupal/Tests/Core/Plugin/DefaultPluginManagerTest.php index 3e86b66..0e60267 100644 --- a/core/tests/Drupal/Tests/Core/Plugin/DefaultPluginManagerTest.php +++ b/core/tests/Drupal/Tests/Core/Plugin/DefaultPluginManagerTest.php @@ -113,7 +113,9 @@ public function testDefaultPluginManagerWithEmptyCache() { ->with($cid . ':en', $this->expectedDefinitions); $language = new Language(array('id' => 'en')); - $language_manager = $this->getMock('Drupal\Core\Language\LanguageManager'); + $language_manager = $this->getMockBuilder('Drupal\Core\Language\LanguageManager') + ->disableOriginalConstructor() + ->getMock(); $language_manager->expects($this->once()) ->method('getLanguage') ->with(Language::TYPE_INTERFACE) @@ -144,7 +146,9 @@ public function testDefaultPluginManagerWithFilledCache() { ->method('set'); $language = new Language(array('id' => 'en')); - $language_manager = $this->getMock('Drupal\Core\Language\LanguageManager'); + $language_manager = $this->getMockBuilder('Drupal\Core\Language\LanguageManager') + ->disableOriginalConstructor() + ->getMock(); $language_manager->expects($this->once()) ->method('getLanguage') ->with(Language::TYPE_INTERFACE) @@ -173,7 +177,9 @@ public function testCacheClearWithTags() { ->method('deleteMultiple'); $language = new Language(array('id' => 'en')); - $language_manager = $this->getMock('Drupal\Core\Language\LanguageManager'); + $language_manager = $this->getMockBuilder('Drupal\Core\Language\LanguageManager') + ->disableOriginalConstructor() + ->getMock(); $language_manager->expects($this->once()) ->method('getLanguage') ->with(Language::TYPE_INTERFACE) diff --git a/core/tests/Drupal/Tests/Core/Utility/LinkGeneratorTest.php b/core/tests/Drupal/Tests/Core/Utility/LinkGeneratorTest.php index 6b7334f..3e6c72f 100644 --- a/core/tests/Drupal/Tests/Core/Utility/LinkGeneratorTest.php +++ b/core/tests/Drupal/Tests/Core/Utility/LinkGeneratorTest.php @@ -79,7 +79,10 @@ protected function setUp() { $this->urlGenerator = $this->getMock('\Drupal\Core\Routing\UrlGenerator', array(), array(), '', FALSE); $this->moduleHandler = $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface'); - $this->languageManager = $this->getMock('Drupal\Core\Language\LanguageManager'); + $this->languageManager = $this->getMockBuilder('Drupal\Core\Language\LanguageManager') + ->disableOriginalConstructor() + ->getMock(); + $this->linkGenerator = new LinkGenerator($this->urlGenerator, $this->moduleHandler, $this->languageManager); }