language.inc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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']['negotiation'] = '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. * ?>
  95. * @endcode
  96. *
  97. * For more information, see
  98. * @link http://drupal.org/node/1497272 Language Negotiation API @endlink
  99. */
  100. /**
  101. * Returns all the defined language types.
  102. *
  103. * @return
  104. * An array of language type names. The name will be used as the global
  105. * variable name the language value will be stored in.
  106. */
  107. function language_types_info() {
  108. $language_types = &drupal_static(__FUNCTION__);
  109. if (!isset($language_types)) {
  110. $language_types = module_invoke_all('language_types_info');
  111. // Let other modules alter the list of language types.
  112. drupal_alter('language_types_info', $language_types);
  113. }
  114. return $language_types;
  115. }
  116. /**
  117. * Returns only the configurable language types.
  118. *
  119. * A language type maybe configurable or fixed. A fixed language type is a type
  120. * whose language negotiation providers are module-defined and not altered
  121. * through the user interface.
  122. *
  123. * @param $stored
  124. * Optional. By default retrieves values from the 'language_types' variable to
  125. * avoid unnecessary hook invocations.
  126. * If set to FALSE retrieves values from the actual language type definitions.
  127. * This allows to react to alterations performed on the definitions by modules
  128. * installed after the 'language_types' variable is set.
  129. *
  130. * @return
  131. * An array of language type names.
  132. */
  133. function language_types_configurable($stored = TRUE) {
  134. $configurable = &drupal_static(__FUNCTION__);
  135. if ($stored && !isset($configurable)) {
  136. $types = variable_get('language_types', drupal_language_types());
  137. $configurable = array_keys(array_filter($types));
  138. }
  139. if (!$stored) {
  140. $result = array();
  141. foreach (language_types_info() as $type => $info) {
  142. if (!isset($info['fixed'])) {
  143. $result[] = $type;
  144. }
  145. }
  146. return $result;
  147. }
  148. return $configurable;
  149. }
  150. /**
  151. * Disables the given language types.
  152. *
  153. * @param $types
  154. * An array of language types.
  155. */
  156. function language_types_disable($types) {
  157. $enabled_types = variable_get('language_types', drupal_language_types());
  158. foreach ($types as $type) {
  159. unset($enabled_types[$type]);
  160. }
  161. variable_set('language_types', $enabled_types);
  162. }
  163. /**
  164. * Updates the language type configuration.
  165. */
  166. function language_types_set() {
  167. // Ensure that we are getting the defined language negotiation information. An
  168. // invocation of module_enable() or module_disable() could outdate the cached
  169. // information.
  170. drupal_static_reset('language_types_info');
  171. drupal_static_reset('language_negotiation_info');
  172. // Determine which language types are configurable and which not by checking
  173. // whether the 'fixed' key is defined. Non-configurable (fixed) language types
  174. // have their language negotiation settings stored there.
  175. $defined_providers = language_negotiation_info();
  176. foreach (language_types_info() as $type => $info) {
  177. if (isset($info['fixed'])) {
  178. $language_types[$type] = FALSE;
  179. $negotiation = array();
  180. foreach ($info['fixed'] as $weight => $id) {
  181. if (isset($defined_providers[$id])) {
  182. $negotiation[$id] = $weight;
  183. }
  184. }
  185. language_negotiation_set($type, $negotiation);
  186. }
  187. else {
  188. $language_types[$type] = TRUE;
  189. }
  190. }
  191. // Save language types.
  192. variable_set('language_types', $language_types);
  193. // Ensure that subsequent calls of language_types_configurable() return the
  194. // updated language type information.
  195. drupal_static_reset('language_types_configurable');
  196. }
  197. /**
  198. * Checks whether a language negotiation provider is enabled for a language type.
  199. *
  200. * This has two possible behaviors:
  201. * - If $provider_id is given return its ID if enabled, FALSE otherwise.
  202. * - If no ID is passed the first enabled language negotiation provider is
  203. * returned.
  204. *
  205. * @param $type
  206. * The language negotiation provider type.
  207. * @param $provider_id
  208. * The language negotiation provider ID.
  209. *
  210. * @return
  211. * The provider ID if it is enabled, FALSE otherwise.
  212. */
  213. function language_negotiation_get($type, $provider_id = NULL) {
  214. $negotiation = variable_get("language_negotiation_$type", array());
  215. if (empty($negotiation)) {
  216. return empty($provider_id) ? LANGUAGE_NEGOTIATION_DEFAULT : FALSE;
  217. }
  218. if (empty($provider_id)) {
  219. return key($negotiation);
  220. }
  221. if (isset($negotiation[$provider_id])) {
  222. return $provider_id;
  223. }
  224. return FALSE;
  225. }
  226. /**
  227. * Checks if the language negotiation provider is enabled for any language type.
  228. *
  229. * @param $provider_id
  230. * The language negotiation provider ID.
  231. *
  232. * @return
  233. * TRUE if there is at least one language type for which the given language
  234. * provider is enabled, FALSE otherwise.
  235. */
  236. function language_negotiation_get_any($provider_id) {
  237. foreach (language_types_configurable() as $type) {
  238. if (language_negotiation_get($type, $provider_id)) {
  239. return TRUE;
  240. }
  241. }
  242. return FALSE;
  243. }
  244. /**
  245. * Returns the language switch links for the given language.
  246. *
  247. * @param $type
  248. * The language negotiation type.
  249. * @param $path
  250. * The internal path the switch links will be relative to.
  251. *
  252. * @return
  253. * A keyed array of links ready to be themed.
  254. */
  255. function language_negotiation_get_switch_links($type, $path) {
  256. $links = FALSE;
  257. $negotiation = variable_get("language_negotiation_$type", array());
  258. // Only get the languages if we have more than one.
  259. if (count(language_list()) >= 2) {
  260. $language = language_initialize($type);
  261. }
  262. foreach ($negotiation as $id => $provider) {
  263. if (isset($provider['callbacks']['switcher'])) {
  264. if (isset($provider['file'])) {
  265. require_once DRUPAL_ROOT . '/' . $provider['file'];
  266. }
  267. $callback = $provider['callbacks']['switcher'];
  268. $result = $callback($type, $path);
  269. // Add support for WCAG 2.0's Language of Parts to add language identifiers.
  270. // http://www.w3.org/TR/UNDERSTANDING-WCAG20/meaning-other-lang-id.html
  271. foreach ($result as $langcode => $link) {
  272. $result[$langcode]['attributes']['lang'] = $langcode;
  273. }
  274. if (!empty($result)) {
  275. // Allow modules to provide translations for specific links.
  276. drupal_alter('language_switch_links', $result, $type, $path);
  277. $links = (object) array('links' => $result, 'provider' => $id);
  278. break;
  279. }
  280. }
  281. }
  282. return $links;
  283. }
  284. /**
  285. * Removes any unused language negotation providers from the configuration.
  286. */
  287. function language_negotiation_purge() {
  288. // Ensure that we are getting the defined language negotiation information. An
  289. // invocation of module_enable() or module_disable() could outdate the cached
  290. // information.
  291. drupal_static_reset('language_negotiation_info');
  292. drupal_static_reset('language_types_info');
  293. $defined_providers = language_negotiation_info();
  294. foreach (language_types_info() as $type => $type_info) {
  295. $weight = 0;
  296. $negotiation = array();
  297. foreach (variable_get("language_negotiation_$type", array()) as $id => $provider) {
  298. if (isset($defined_providers[$id])) {
  299. $negotiation[$id] = $weight++;
  300. }
  301. }
  302. language_negotiation_set($type, $negotiation);
  303. }
  304. }
  305. /**
  306. * Saves a list of language negotiation providers.
  307. *
  308. * @param $type
  309. * The language negotiation type.
  310. * @param $language_providers
  311. * An array of language negotiation provider weights keyed by provider ID.
  312. * @see language_provider_weight()
  313. */
  314. function language_negotiation_set($type, $language_providers) {
  315. // Save only the necessary fields.
  316. $provider_fields = array('callbacks', 'file', 'cache');
  317. $negotiation = array();
  318. $providers_weight = array();
  319. $defined_providers = language_negotiation_info();
  320. $default_types = language_types_configurable(FALSE);
  321. // Initialize the providers weight list.
  322. foreach ($language_providers as $id => $provider) {
  323. $providers_weight[$id] = language_provider_weight($provider);
  324. }
  325. // Order providers list by weight.
  326. asort($providers_weight);
  327. foreach ($providers_weight as $id => $weight) {
  328. if (isset($defined_providers[$id])) {
  329. $provider = $defined_providers[$id];
  330. // If the provider does not express any preference about types, make it
  331. // available for any configurable type.
  332. $types = array_flip(isset($provider['types']) ? $provider['types'] : $default_types);
  333. // Check whether the provider is defined and has the right type.
  334. if (isset($types[$type])) {
  335. $provider_data = array();
  336. foreach ($provider_fields as $field) {
  337. if (isset($provider[$field])) {
  338. $provider_data[$field] = $provider[$field];
  339. }
  340. }
  341. $negotiation[$id] = $provider_data;
  342. }
  343. }
  344. }
  345. variable_set("language_negotiation_$type", $negotiation);
  346. }
  347. /**
  348. * Returns all the defined language negotiation providers.
  349. *
  350. * @return
  351. * An array of language negotiation providers.
  352. */
  353. function language_negotiation_info() {
  354. $language_providers = &drupal_static(__FUNCTION__);
  355. if (!isset($language_providers)) {
  356. // Collect all the module-defined language negotiation providers.
  357. $language_providers = module_invoke_all('language_negotiation_info');
  358. // Add the default language negotiation provider.
  359. $language_providers[LANGUAGE_NEGOTIATION_DEFAULT] = array(
  360. 'callbacks' => array('language' => 'language_from_default'),
  361. 'weight' => 10,
  362. 'name' => t('Default'),
  363. 'description' => t('Use the default site language (@language_name).', array('@language_name' => language_default()->native)),
  364. );
  365. // Let other modules alter the list of language negotiation providers.
  366. drupal_alter('language_negotiation_info', $language_providers);
  367. }
  368. return $language_providers;
  369. }
  370. /**
  371. * Helper function used to cache the language negotiation providers results.
  372. *
  373. * @param $provider_id
  374. * The language negotiation provider's identifier.
  375. * @param $provider
  376. * (optional) An associative array of information about the provider to be
  377. * invoked (see hook_language_negotiation_info() for details). If not passed
  378. * in, it will be loaded through language_negotiation_info().
  379. *
  380. * @return
  381. * A language object representing the language chosen by the provider.
  382. */
  383. function language_provider_invoke($provider_id, $provider = NULL) {
  384. $results = &drupal_static(__FUNCTION__);
  385. if (!isset($results[$provider_id])) {
  386. global $user;
  387. // Get languages grouped by status and select only the enabled ones.
  388. $languages = language_list('enabled');
  389. $languages = $languages[1];
  390. if (!isset($provider)) {
  391. $providers = language_negotiation_info();
  392. $provider = $providers[$provider_id];
  393. }
  394. if (isset($provider['file'])) {
  395. require_once DRUPAL_ROOT . '/' . $provider['file'];
  396. }
  397. // If the language negotiation provider has no cache preference or this is
  398. // satisfied we can execute the callback.
  399. $cache = !isset($provider['cache']) || $user->uid || $provider['cache'] == variable_get('cache', 0);
  400. $callback = isset($provider['callbacks']['language']) ? $provider['callbacks']['language'] : FALSE;
  401. $langcode = $cache && function_exists($callback) ? $callback($languages) : FALSE;
  402. $results[$provider_id] = isset($languages[$langcode]) ? $languages[$langcode] : FALSE;
  403. }
  404. // Since objects are resources, we need to return a clone to prevent the
  405. // language negotiation provider cache from being unintentionally altered. The
  406. // same providers might be used with different language types based on
  407. // configuration.
  408. return !empty($results[$provider_id]) ? clone($results[$provider_id]) : $results[$provider_id];
  409. }
  410. /**
  411. * Returns the passed language negotiation provider weight or a default value.
  412. *
  413. * @param $provider
  414. * A language negotiation provider data structure.
  415. *
  416. * @return
  417. * A numeric weight.
  418. */
  419. function language_provider_weight($provider) {
  420. $default = is_numeric($provider) ? $provider : 0;
  421. return isset($provider['weight']) && is_numeric($provider['weight']) ? $provider['weight'] : $default;
  422. }
  423. /**
  424. * Chooses a language based on language negotiation provider settings.
  425. *
  426. * @param $type
  427. * The language type key to find the language for.
  428. *
  429. * @return
  430. * The negotiated language object.
  431. */
  432. function language_initialize($type) {
  433. // Execute the language negotiation providers in the order they were set up and return the
  434. // first valid language found.
  435. $negotiation = variable_get("language_negotiation_$type", array());
  436. foreach ($negotiation as $provider_id => $provider) {
  437. $language = language_provider_invoke($provider_id, $provider);
  438. if ($language) {
  439. $language->provider = $provider_id;
  440. return $language;
  441. }
  442. }
  443. // If no other language was found use the default one.
  444. $language = language_default();
  445. $language->provider = LANGUAGE_NEGOTIATION_DEFAULT;
  446. return $language;
  447. }
  448. /**
  449. * Returns the default language negotiation provider.
  450. *
  451. * @return
  452. * The default language code.
  453. */
  454. function language_from_default() {
  455. return language_default()->language;
  456. }
  457. /**
  458. * Splits the given path into prefix and actual path.
  459. *
  460. * Parse the given path and return the language object identified by the prefix
  461. * and the actual path.
  462. *
  463. * @param $path
  464. * The path to split.
  465. * @param $languages
  466. * An array of valid languages.
  467. *
  468. * @return
  469. * An array composed of:
  470. * - A language object corresponding to the identified prefix on success,
  471. * FALSE otherwise.
  472. * - The path without the prefix on success, the given path otherwise.
  473. */
  474. function language_url_split_prefix($path, $languages) {
  475. $args = empty($path) ? array() : explode('/', $path);
  476. $prefix = array_shift($args);
  477. // Search prefix within enabled languages.
  478. foreach ($languages as $language) {
  479. if (!empty($language->prefix) && $language->prefix == $prefix) {
  480. // Rebuild $path with the language removed.
  481. return array($language, implode('/', $args));
  482. }
  483. }
  484. return array(FALSE, $path);
  485. }
  486. /**
  487. * Returns the possible fallback languages ordered by language weight.
  488. *
  489. * @param
  490. * (optional) The language type. Defaults to LANGUAGE_TYPE_CONTENT.
  491. *
  492. * @return
  493. * An array of language codes.
  494. */
  495. function language_fallback_get_candidates($type = LANGUAGE_TYPE_CONTENT) {
  496. $fallback_candidates = &drupal_static(__FUNCTION__);
  497. if (!isset($fallback_candidates)) {
  498. $fallback_candidates = array();
  499. // Get languages ordered by weight.
  500. // Use array keys to avoid duplicated entries.
  501. foreach (language_list('weight') as $languages) {
  502. foreach ($languages as $language) {
  503. $fallback_candidates[$language->language] = NULL;
  504. }
  505. }
  506. $fallback_candidates = array_keys($fallback_candidates);
  507. $fallback_candidates[] = LANGUAGE_NONE;
  508. // Let other modules hook in and add/change candidates.
  509. drupal_alter('language_fallback_candidates', $fallback_candidates);
  510. }
  511. return $fallback_candidates;
  512. }
  513. /**
  514. * @} End of "language_negotiation"
  515. */