1. 6.x includes/language.inc
  2. 7.x includes/language.inc

Language Negotiation API.

See also

http://drupal.org/node/1497272

File

includes/language.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Language Negotiation API.
  5. *
  6. * @see http://drupal.org/node/1497272
  7. */
  8. /**
  9. * No language negotiation. The default language is used.
  10. */
  11. define('LANGUAGE_NEGOTIATION_DEFAULT', 'language-default');
  12. /**
  13. * @defgroup language_negotiation Language Negotiation API functionality
  14. * @{
  15. * Functions to customize the language types and the negotiation process.
  16. *
  17. * The language negotiation API is based on two major concepts:
  18. * - Language types: types of translatable data (the types of data that a user
  19. * can view or request).
  20. * - Language negotiation providers: functions for determining which language to
  21. * use to present a particular piece of data to the user.
  22. * Both language types and language negotiation providers are customizable.
  23. *
  24. * Drupal defines three built-in language types:
  25. * - Interface language: The page's main language, used to present translated
  26. * user interface elements such as titles, labels, help text, and messages.
  27. * - Content language: The language used to present content that is available
  28. * in more than one language (see
  29. * @link field_language Field Language API @endlink for details).
  30. * - URL language: The language associated with URLs. When generating a URL,
  31. * this value will be used by url() as a default if no explicit preference is
  32. * provided.
  33. * Modules can define additional language types through
  34. * hook_language_types_info(), and alter existing language type definitions
  35. * through hook_language_types_info_alter().
  36. *
  37. * Language types may be configurable or fixed. The language negotiation
  38. * providers associated with a configurable language type can be explicitly
  39. * set through the user interface. A fixed language type has predetermined
  40. * (module-defined) language negotiation settings and, thus, does not appear in
  41. * the configuration page. Here is a code snippet that makes the content
  42. * language (which by default inherits the interface language's values)
  43. * configurable:
  44. * @code
  45. * function mymodule_language_types_info_alter(&$language_types) {
  46. * unset($language_types[LANGUAGE_TYPE_CONTENT]['fixed']);
  47. * }
  48. * @endcode
  49. *
  50. * Every language type can have a different set of language negotiation
  51. * providers assigned to it. Different language types often share the same
  52. * language negotiation settings, but they can have independent settings if
  53. * needed. If two language types are configured the same way, their language
  54. * switcher configuration will be functionally identical and the same settings
  55. * will act on both language types.
  56. *
  57. * Drupal defines the following built-in language negotiation providers:
  58. * - URL: Determine the language from the URL (path prefix or domain).
  59. * - Session: Determine the language from a request/session parameter.
  60. * - User: Follow the user's language preference.
  61. * - Browser: Determine the language from the browser's language settings.
  62. * - Default language: Use the default site language.
  63. * Language negotiation providers are simple callback functions that implement a
  64. * particular logic to return a language code. For instance, the URL provider
  65. * searches for a valid path prefix or domain name in the current request URL.
  66. * If a language negotiation provider does not return a valid language code, the
  67. * next provider associated to the language type (based on provider weight) is
  68. * invoked.
  69. *
  70. * Modules can define additional language negotiation providers through
  71. * hook_language_negotiation_info(), and alter existing providers through
  72. * hook_language_negotiation_info_alter(). Here is an example snippet that lets
  73. * path prefixes be ignored for administrative paths:
  74. * @code
  75. * function mymodule_language_negotiation_info_alter(&$negotiation_info) {
  76. * // Replace the core function with our own function.
  77. * module_load_include('language', 'inc', 'language.negotiation');
  78. * $negotiation_info[LANGUAGE_NEGOTIATION_URL]['callbacks']['language'] = 'mymodule_from_url';
  79. * $negotiation_info[LANGUAGE_NEGOTIATION_URL]['file'] = drupal_get_path('module', 'mymodule') . '/mymodule.module';
  80. * }
  81. *
  82. * function mymodule_from_url($languages) {
  83. * // Use the core URL language negotiation provider to get a valid language
  84. * // code.
  85. * module_load_include('language', 'inc', 'language.negotiation');
  86. * $langcode = language_from_url($languages);
  87. *
  88. * // If we are on an administrative path, override with the default language.
  89. * if (isset($_GET['q']) && strtok($_GET['q'], '/') == 'admin') {
  90. * return language_default()->langcode;
  91. * }
  92. * return $langcode;
  93. * }
  94. * @endcode
  95. *
  96. * For more information, see
  97. * @link http://drupal.org/node/1497272 Language Negotiation API @endlink
  98. */
  99. /**
  100. * Returns all the defined language types.
  101. *
  102. * @return
  103. * An array of language type names. The name will be used as the global
  104. * variable name the language value will be stored in.
  105. */
  106. function language_types_info() {
  107. $language_types = &drupal_static(__FUNCTION__);
  108. if (!isset($language_types)) {
  109. $language_types = module_invoke_all('language_types_info');
  110. // Let other modules alter the list of language types.
  111. drupal_alter('language_types_info', $language_types);
  112. }
  113. return $language_types;
  114. }
  115. /**
  116. * Returns only the configurable language types.
  117. *
  118. * A language type maybe configurable or fixed. A fixed language type is a type
  119. * whose language negotiation providers are module-defined and not altered
  120. * through the user interface.
  121. *
  122. * @param $stored
  123. * Optional. By default retrieves values from the 'language_types' variable to
  124. * avoid unnecessary hook invocations.
  125. * If set to FALSE retrieves values from the actual language type definitions.
  126. * This allows to react to alterations performed on the definitions by modules
  127. * installed after the 'language_types' variable is set.
  128. *
  129. * @return
  130. * An array of language type names.
  131. */
  132. function language_types_configurable($stored = TRUE) {
  133. $configurable = &drupal_static(__FUNCTION__);
  134. if ($stored && !isset($configurable)) {
  135. $types = variable_get('language_types', drupal_language_types());
  136. $configurable = array_keys(array_filter($types));
  137. }
  138. if (!$stored) {
  139. $result = array();
  140. foreach (language_types_info() as $type => $info) {
  141. if (!isset($info['fixed'])) {
  142. $result[] = $type;
  143. }
  144. }
  145. return $result;
  146. }
  147. return $configurable;
  148. }
  149. /**
  150. * Disables the given language types.
  151. *
  152. * @param $types
  153. * An array of language types.
  154. */
  155. function language_types_disable($types) {
  156. $enabled_types = variable_get('language_types', drupal_language_types());
  157. foreach ($types as $type) {
  158. unset($enabled_types[$type]);
  159. }
  160. variable_set('language_types', $enabled_types);
  161. }
  162. /**
  163. * Updates the language type configuration.
  164. */
  165. function language_types_set() {
  166. // Ensure that we are getting the defined language negotiation information. An
  167. // invocation of module_enable() or module_disable() could outdate the cached
  168. // information.
  169. drupal_static_reset('language_types_info');
  170. drupal_static_reset('language_negotiation_info');
  171. // Determine which language types are configurable and which not by checking
  172. // whether the 'fixed' key is defined. Non-configurable (fixed) language types
  173. // have their language negotiation settings stored there.
  174. $defined_providers = language_negotiation_info();
  175. foreach (language_types_info() as $type => $info) {
  176. if (isset($info['fixed'])) {
  177. $language_types[$type] = FALSE;
  178. $negotiation = array();
  179. foreach ($info['fixed'] as $weight => $id) {
  180. if (isset($defined_providers[$id])) {
  181. $negotiation[$id] = $weight;
  182. }
  183. }
  184. language_negotiation_set($type, $negotiation);
  185. }
  186. else {
  187. $language_types[$type] = TRUE;
  188. }
  189. }
  190. // Save language types.
  191. variable_set('language_types', $language_types);
  192. // Ensure that subsequent calls of language_types_configurable() return the
  193. // updated language type information.
  194. drupal_static_reset('language_types_configurable');
  195. }
  196. /**
  197. * Checks whether a language negotiation provider is enabled for a language type.
  198. *
  199. * This has two possible behaviors:
  200. * - If $provider_id is given return its ID if enabled, FALSE otherwise.
  201. * - If no ID is passed the first enabled language negotiation provider is
  202. * returned.
  203. *
  204. * @param $type
  205. * The language negotiation provider type.
  206. * @param $provider_id
  207. * The language negotiation provider ID.
  208. *
  209. * @return
  210. * The provider ID if it is enabled, FALSE otherwise.
  211. */
  212. function language_negotiation_get($type, $provider_id = NULL) {
  213. $negotiation = variable_get("language_negotiation_$type", array());
  214. if (empty($negotiation)) {
  215. return empty($provider_id) ? LANGUAGE_NEGOTIATION_DEFAULT : FALSE;
  216. }
  217. if (empty($provider_id)) {
  218. return key($negotiation);
  219. }
  220. if (isset($negotiation[$provider_id])) {
  221. return $provider_id;
  222. }
  223. return FALSE;
  224. }
  225. /**
  226. * Checks if the language negotiation provider is enabled for any language type.
  227. *
  228. * @param $provider_id
  229. * The language negotiation provider ID.
  230. *
  231. * @return
  232. * TRUE if there is at least one language type for which the given language
  233. * provider is enabled, FALSE otherwise.
  234. */
  235. function language_negotiation_get_any($provider_id) {
  236. foreach (language_types_configurable() as $type) {
  237. if (language_negotiation_get($type, $provider_id)) {
  238. return TRUE;
  239. }
  240. }
  241. return FALSE;
  242. }
  243. /**
  244. * Returns the language switch links for the given language.
  245. *
  246. * @param $type
  247. * The language negotiation type.
  248. * @param $path
  249. * The internal path the switch links will be relative to.
  250. *
  251. * @return
  252. * A keyed array of links ready to be themed.
  253. */
  254. function language_negotiation_get_switch_links($type, $path) {
  255. $links = FALSE;
  256. $negotiation = variable_get("language_negotiation_$type", array());
  257. // Only get the languages if we have more than one.
  258. if (count(language_list()) >= 2) {
  259. $language = language_initialize($type);
  260. }
  261. foreach ($negotiation as $id => $provider) {
  262. if (isset($provider['callbacks']['switcher'])) {
  263. if (isset($provider['file'])) {
  264. require_once DRUPAL_ROOT . '/' . $provider['file'];
  265. }
  266. $callback = $provider['callbacks']['switcher'];
  267. $result = $callback($type, $path);
  268. // Add support for WCAG 2.0's Language of Parts to add language identifiers.
  269. // http://www.w3.org/TR/UNDERSTANDING-WCAG20/meaning-other-lang-id.html
  270. foreach ($result as $langcode => $link) {
  271. $result[$langcode]['attributes']['xml:lang'] = $langcode;
  272. }
  273. if (!empty($result)) {
  274. // Allow modules to provide translations for specific links.
  275. drupal_alter('language_switch_links', $result, $type, $path);
  276. $links = (object) array('links' => $result, 'provider' => $id);
  277. break;
  278. }
  279. }
  280. }
  281. return $links;
  282. }
  283. /**
  284. * Removes any unused language negotiation providers from the configuration.
  285. */
  286. function language_negotiation_purge() {
  287. // Ensure that we are getting the defined language negotiation information. An
  288. // invocation of module_enable() or module_disable() could outdate the cached
  289. // information.
  290. drupal_static_reset('language_negotiation_info');
  291. drupal_static_reset('language_types_info');
  292. $defined_providers = language_negotiation_info();
  293. foreach (language_types_info() as $type => $type_info) {
  294. $weight = 0;
  295. $negotiation = array();
  296. foreach (variable_get("language_negotiation_$type", array()) as $id => $provider) {
  297. if (isset($defined_providers[$id])) {
  298. $negotiation[$id] = $weight++;
  299. }
  300. }
  301. language_negotiation_set($type, $negotiation);
  302. }
  303. }
  304. /**
  305. * Saves a list of language negotiation providers.
  306. *
  307. * @param $type
  308. * The language negotiation type.
  309. * @param $language_providers
  310. * An array of language negotiation provider weights keyed by provider ID.
  311. * @see language_provider_weight()
  312. */
  313. function language_negotiation_set($type, $language_providers) {
  314. // Save only the necessary fields.
  315. $provider_fields = array('callbacks', 'file', 'cache');
  316. $negotiation = array();
  317. $providers_weight = array();
  318. $defined_providers = language_negotiation_info();
  319. $default_types = language_types_configurable(FALSE);
  320. // Initialize the providers weight list.
  321. foreach ($language_providers as $id => $provider) {
  322. $providers_weight[$id] = language_provider_weight($provider);
  323. }
  324. // Order providers list by weight.
  325. asort($providers_weight);
  326. foreach ($providers_weight as $id => $weight) {
  327. if (isset($defined_providers[$id])) {
  328. $provider = $defined_providers[$id];
  329. // If the provider does not express any preference about types, make it
  330. // available for any configurable type.
  331. $types = array_flip(isset($provider['types']) ? $provider['types'] : $default_types);
  332. // Check whether the provider is defined and has the right type.
  333. if (isset($types[$type])) {
  334. $provider_data = array();
  335. foreach ($provider_fields as $field) {
  336. if (isset($provider[$field])) {
  337. $provider_data[$field] = $provider[$field];
  338. }
  339. }
  340. $negotiation[$id] = $provider_data;
  341. }
  342. }
  343. }
  344. variable_set("language_negotiation_$type", $negotiation);
  345. }
  346. /**
  347. * Returns all the defined language negotiation providers.
  348. *
  349. * @return
  350. * An array of language negotiation providers.
  351. */
  352. function language_negotiation_info() {
  353. $language_providers = &drupal_static(__FUNCTION__);
  354. if (!isset($language_providers)) {
  355. // Collect all the module-defined language negotiation providers.
  356. $language_providers = module_invoke_all('language_negotiation_info');
  357. // Add the default language negotiation provider.
  358. $language_providers[LANGUAGE_NEGOTIATION_DEFAULT] = array(
  359. 'callbacks' => array('language' => 'language_from_default'),
  360. 'weight' => 10,
  361. 'name' => t('Default'),
  362. 'description' => t('Use the default site language (@language_name).', array('@language_name' => language_default()->native)),
  363. );
  364. // Let other modules alter the list of language negotiation providers.
  365. drupal_alter('language_negotiation_info', $language_providers);
  366. }
  367. return $language_providers;
  368. }
  369. /**
  370. * Helper function used to cache the language negotiation providers results.
  371. *
  372. * @param $provider_id
  373. * The language negotiation provider's identifier.
  374. * @param $provider
  375. * (optional) An associative array of information about the provider to be
  376. * invoked (see hook_language_negotiation_info() for details). If not passed
  377. * in, it will be loaded through language_negotiation_info().
  378. *
  379. * @return
  380. * A language object representing the language chosen by the provider.
  381. */
  382. function language_provider_invoke($provider_id, $provider = NULL) {
  383. $results = &drupal_static(__FUNCTION__);
  384. if (!isset($results[$provider_id])) {
  385. global $user;
  386. // Get languages grouped by status and select only the enabled ones.
  387. $languages = language_list('enabled');
  388. $languages = $languages[1];
  389. if (!isset($provider)) {
  390. $providers = language_negotiation_info();
  391. $provider = $providers[$provider_id];
  392. }
  393. if (isset($provider['file'])) {
  394. require_once DRUPAL_ROOT . '/' . $provider['file'];
  395. }
  396. // If the language negotiation provider has no cache preference or this is
  397. // satisfied we can execute the callback.
  398. $cache = !isset($provider['cache']) || $user->uid || $provider['cache'] == variable_get('cache', 0);
  399. $callback = isset($provider['callbacks']['language']) ? $provider['callbacks']['language'] : FALSE;
  400. $langcode = $cache && function_exists($callback) ? $callback($languages) : FALSE;
  401. $results[$provider_id] = isset($languages[$langcode]) ? $languages[$langcode] : FALSE;
  402. }
  403. // Since objects are resources, we need to return a clone to prevent the
  404. // language negotiation provider cache from being unintentionally altered. The
  405. // same providers might be used with different language types based on
  406. // configuration.
  407. return !empty($results[$provider_id]) ? clone($results[$provider_id]) : $results[$provider_id];
  408. }
  409. /**
  410. * Returns the passed language negotiation provider weight or a default value.
  411. *
  412. * @param $provider
  413. * A language negotiation provider data structure.
  414. *
  415. * @return
  416. * A numeric weight.
  417. */
  418. function language_provider_weight($provider) {
  419. $default = is_numeric($provider) ? $provider : 0;
  420. return isset($provider['weight']) && is_numeric($provider['weight']) ? $provider['weight'] : $default;
  421. }
  422. /**
  423. * Chooses a language based on language negotiation provider settings.
  424. *
  425. * @param $type
  426. * The language type key to find the language for.
  427. *
  428. * @return
  429. * The negotiated language object.
  430. */
  431. function language_initialize($type) {
  432. // Execute the language negotiation providers in the order they were set up and return the
  433. // first valid language found.
  434. $negotiation = variable_get("language_negotiation_$type", array());
  435. foreach ($negotiation as $provider_id => $provider) {
  436. $language = language_provider_invoke($provider_id, $provider);
  437. if ($language) {
  438. $language->provider = $provider_id;
  439. return $language;
  440. }
  441. }
  442. // If no other language was found use the default one.
  443. $language = language_default();
  444. $language->provider = LANGUAGE_NEGOTIATION_DEFAULT;
  445. return $language;
  446. }
  447. /**
  448. * Returns the default language negotiation provider.
  449. *
  450. * @return
  451. * The default language code.
  452. */
  453. function language_from_default() {
  454. return language_default()->language;
  455. }
  456. /**
  457. * Splits the given path into prefix and actual path.
  458. *
  459. * Parse the given path and return the language object identified by the prefix
  460. * and the actual path.
  461. *
  462. * @param $path
  463. * The path to split.
  464. * @param $languages
  465. * An array of valid languages.
  466. *
  467. * @return
  468. * An array composed of:
  469. * - A language object corresponding to the identified prefix on success,
  470. * FALSE otherwise.
  471. * - The path without the prefix on success, the given path otherwise.
  472. */
  473. function language_url_split_prefix($path, $languages) {
  474. $args = empty($path) ? array() : explode('/', $path);
  475. $prefix = array_shift($args);
  476. // Search prefix within enabled languages.
  477. foreach ($languages as $language) {
  478. if (!empty($language->prefix) && $language->prefix == $prefix) {
  479. // Rebuild $path with the language removed.
  480. return array($language, implode('/', $args));
  481. }
  482. }
  483. return array(FALSE, $path);
  484. }
  485. /**
  486. * Returns the possible fallback languages ordered by language weight.
  487. *
  488. * @param
  489. * (optional) The language type. Defaults to LANGUAGE_TYPE_CONTENT.
  490. *
  491. * @return
  492. * An array of language codes.
  493. */
  494. function language_fallback_get_candidates($type = LANGUAGE_TYPE_CONTENT) {
  495. $fallback_candidates = &drupal_static(__FUNCTION__);
  496. if (!isset($fallback_candidates)) {
  497. $fallback_candidates = array();
  498. // Get languages ordered by weight.
  499. // Use array keys to avoid duplicated entries.
  500. foreach (language_list('weight') as $languages) {
  501. foreach ($languages as $language) {
  502. $fallback_candidates[$language->language] = NULL;
  503. }
  504. }
  505. $fallback_candidates = array_keys($fallback_candidates);
  506. $fallback_candidates[] = LANGUAGE_NONE;
  507. // Let other modules hook in and add/change candidates.
  508. drupal_alter('language_fallback_candidates', $fallback_candidates);
  509. }
  510. return $fallback_candidates;
  511. }
  512. /**
  513. * @} End of "language_negotiation"
  514. */

Functions

Namesort descending Description
language_fallback_get_candidates Returns the possible fallback languages ordered by language weight.
language_from_default Returns the default language negotiation provider.
language_initialize Chooses a language based on language negotiation provider settings.
language_negotiation_get Checks whether a language negotiation provider is enabled for a language type.
language_negotiation_get_any Checks if the language negotiation provider is enabled for any language type.
language_negotiation_get_switch_links Returns the language switch links for the given language.
language_negotiation_info Returns all the defined language negotiation providers.
language_negotiation_purge Removes any unused language negotiation providers from the configuration.
language_negotiation_set Saves a list of language negotiation providers.
language_provider_invoke Helper function used to cache the language negotiation providers results.
language_provider_weight Returns the passed language negotiation provider weight or a default value.
language_types_configurable Returns only the configurable language types.
language_types_disable Disables the given language types.
language_types_info Returns all the defined language types.
language_types_set Updates the language type configuration.
language_url_split_prefix Splits the given path into prefix and actual path.

Constants

Namesort descending Description
LANGUAGE_NEGOTIATION_DEFAULT No language negotiation. The default language is used.