locale.module 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  1. <?php
  2. /**
  3. * @file
  4. * Add language handling functionality and enables the translation of the
  5. * user interface to languages other than English.
  6. *
  7. * When enabled, multiple languages can be set up. The site interface
  8. * can be displayed in different languages, as well as nodes can have languages
  9. * assigned. The setup of languages and translations is completely web based.
  10. * Gettext portable object files are supported.
  11. */
  12. // ---------------------------------------------------------------------------------
  13. // Hook implementations
  14. /**
  15. * Implements hook_help().
  16. */
  17. function locale_help($path, $arg) {
  18. switch ($path) {
  19. case 'admin/help#locale':
  20. $output = '';
  21. $output .= '<h3>' . t('About') . '</h3>';
  22. $output .= '<p>' . t('The Locale module allows your Drupal site to be presented in languages other than the default English, and to be multilingual. The Locale module works by maintaining a database of translations, and examining text as it is about to be displayed. When a translation of the text is available in the language to be displayed, the translation is displayed rather than the original text. When a translation is unavailable, the original text is displayed, and then stored for review by a translator. For more information, see the online handbook entry for <a href="@locale">Locale module</a>.', array('@locale' => 'http://drupal.org/documentation/modules/locale/')) . '</p>';
  23. $output .= '<h3>' . t('Uses') . '</h3>';
  24. $output .= '<dl>';
  25. $output .= '<dt>' . t('Translating interface text') . '</dt>';
  26. $output .= '<dd>' . t('Translations of text in the Drupal interface may be provided by:');
  27. $output .= '<ul>';
  28. $output .= '<li>' . t("Translating within your site, using the Locale module's integrated <a href='@translate'>translation interface</a>.", array('@translate' => url('admin/config/regional/translate'))) . '</li>';
  29. $output .= '<li>' . t('Importing files from a set of existing translations, known as a translation package. A translation package enables the display of a specific version of Drupal in a specific language, and contains files in the Gettext Portable Object (<em>.po</em>) format. Although not all languages are available for every version of Drupal, translation packages for many languages are available for download from the <a href="@translations">Drupal translations page</a>.', array('@translations' => 'http://localize.drupal.org')) . '</li>';
  30. $output .= '<li>' . t("If an existing translation package does not meet your needs, the Gettext Portable Object (<em>.po</em>) files within a package may be modified, or new <em>.po</em> files may be created, using a desktop Gettext editor. The Locale module's <a href='@import'>import</a> feature allows the translated strings from a new or modified <em>.po</em> file to be added to your site. The Locale module's <a href='@export'>export</a> feature generates files from your site's translated strings, that can either be shared with others or edited offline by a Gettext translation editor.", array('@import' => url('admin/config/regional/translate/import'), '@export' => url('admin/config/regional/translate/export'))) . '</li>';
  31. $output .= '</ul></dd>';
  32. $output .= '<dt>' . t('Configuring a multilingual site') . '</dt>';
  33. $output .= '<dd>' . t("Language negotiation allows your site to automatically change language based on the domain or path used for each request. Users may (optionally) select their preferred language on their <em>My account</em> page, and your site can be configured to honor a web browser's preferred language settings. Site content can be translated using the <a href='@content-help'>Content translation module</a>.", array('@content-help' => url('admin/help/translation'))) . '</dd>';
  34. $output .= '</dl>';
  35. return $output;
  36. case 'admin/config/regional/language':
  37. $output = '<p>' . t('With multiple languages enabled, interface text can be translated, registered users may select their preferred language, and authors can assign a specific language to content. <a href="@translations">Download contributed translations</a> from Drupal.org.', array('@translations' => 'http://localize.drupal.org')) . '</p>';
  38. return $output;
  39. case 'admin/config/regional/language/add':
  40. return '<p>' . t('Add a language to be supported by your site. If your desired language is not available in the <em>Language name</em> drop-down, click <em>Custom language</em> and provide a language code and other details manually. When providing a language code manually, be sure to enter a standardized language code, since this code may be used by browsers to determine an appropriate display language.') . '</p>';
  41. case 'admin/config/regional/language/configure':
  42. $output = '<p>' . t("Define how to decide which language is used to display page elements (primarily text provided by Drupal and modules, such as field labels and help text). This decision is made by evaluating a series of detection methods for languages; the first detection method that gets a result will determine which language is used for that type of text. Define the order of evaluation of language detection methods on this page.") . '</p>';
  43. return $output;
  44. case 'admin/config/regional/language/configure/session':
  45. $output = '<p>' . t('Determine the language from a request/session parameter. Example: "http://example.com?language=de" sets language to German based on the use of "de" within the "language" parameter.') . '</p>';
  46. return $output;
  47. case 'admin/config/regional/translate':
  48. $output = '<p>' . t('This page provides an overview of available translatable strings. Drupal displays translatable strings in text groups; modules may define additional text groups containing other translatable strings. Because text groups provide a method of grouping related strings, they are often used to focus translation efforts on specific areas of the Drupal interface.') . '</p>';
  49. $output .= '<p>' . t('See the <a href="@languages">Languages page</a> for more information on adding support for additional languages.', array('@languages' => url('admin/config/regional/language'))) . '</p>';
  50. return $output;
  51. case 'admin/config/regional/translate/import':
  52. $output = '<p>' . t('This page imports the translated strings contained in an individual Gettext Portable Object (<em>.po</em>) file. Normally distributed as part of a translation package (each translation package may contain several <em>.po</em> files), a <em>.po</em> file may need to be imported after offline editing in a Gettext translation editor. Importing an individual <em>.po</em> file may be a lengthy process.') . '</p>';
  53. $output .= '<p>' . t('Note that the <em>.po</em> files within a translation package are imported automatically (if available) when new modules or themes are enabled, or as new languages are added. Since this page only allows the import of one <em>.po</em> file at a time, it may be simpler to download and extract a translation package into your Drupal installation directory and <a href="@language-add">add the language</a> (which automatically imports all <em>.po</em> files within the package). Translation packages are available for download on the <a href="@translations">Drupal translation page</a>.', array('@language-add' => url('admin/config/regional/language/add'), '@translations' => 'http://localize.drupal.org')) . '</p>';
  54. return $output;
  55. case 'admin/config/regional/translate/export':
  56. return '<p>' . t('This page exports the translated strings used by your site. An export file may be in Gettext Portable Object (<em>.po</em>) form, which includes both the original string and the translation (used to share translations with others), or in Gettext Portable Object Template (<em>.pot</em>) form, which includes the original strings only (used to create new translations with a Gettext translation editor).') . '</p>';
  57. case 'admin/config/regional/translate/translate':
  58. return '<p>' . t('This page allows a translator to search for specific translated and untranslated strings, and is used when creating or editing translations. (Note: For translation tasks involving many strings, it may be more convenient to <a href="@export">export</a> strings for offline editing in a desktop Gettext translation editor.) Searches may be limited to strings found within a specific text group or in a specific language.', array('@export' => url('admin/config/regional/translate/export'))) . '</p>';
  59. case 'admin/structure/block/manage/%/%':
  60. if ($arg[4] == 'locale' && $arg[5] == 'language') {
  61. return '<p>' . t('This block is only shown if <a href="@languages">at least two languages are enabled</a> and <a href="@configuration">language negotiation</a> is set to <em>URL</em> or <em>Session</em>.', array('@languages' => url('admin/config/regional/language'), '@configuration' => url('admin/config/regional/language/configure'))) . '</p>';
  62. }
  63. break;
  64. }
  65. }
  66. /**
  67. * Implements hook_menu().
  68. */
  69. function locale_menu() {
  70. // Manage languages
  71. $items['admin/config/regional/language'] = array(
  72. 'title' => 'Languages',
  73. 'description' => 'Configure languages for content and the user interface.',
  74. 'page callback' => 'drupal_get_form',
  75. 'page arguments' => array('locale_languages_overview_form'),
  76. 'access arguments' => array('administer languages'),
  77. 'file' => 'locale.admin.inc',
  78. 'weight' => -10,
  79. );
  80. $items['admin/config/regional/language/overview'] = array(
  81. 'title' => 'List',
  82. 'weight' => 0,
  83. 'type' => MENU_DEFAULT_LOCAL_TASK,
  84. );
  85. $items['admin/config/regional/language/add'] = array(
  86. 'title' => 'Add language',
  87. 'page callback' => 'locale_languages_add_screen', // two forms concatenated
  88. 'access arguments' => array('administer languages'),
  89. 'weight' => 5,
  90. 'type' => MENU_LOCAL_ACTION,
  91. 'file' => 'locale.admin.inc',
  92. );
  93. $items['admin/config/regional/language/configure'] = array(
  94. 'title' => 'Detection and selection',
  95. 'page callback' => 'drupal_get_form',
  96. 'page arguments' => array('locale_languages_configure_form'),
  97. 'access arguments' => array('administer languages'),
  98. 'weight' => 10,
  99. 'file' => 'locale.admin.inc',
  100. 'type' => MENU_LOCAL_TASK,
  101. );
  102. $items['admin/config/regional/language/configure/url'] = array(
  103. 'title' => 'URL language detection configuration',
  104. 'page callback' => 'drupal_get_form',
  105. 'page arguments' => array('locale_language_providers_url_form'),
  106. 'access arguments' => array('administer languages'),
  107. 'file' => 'locale.admin.inc',
  108. 'type' => MENU_VISIBLE_IN_BREADCRUMB,
  109. );
  110. $items['admin/config/regional/language/configure/session'] = array(
  111. 'title' => 'Session language detection configuration',
  112. 'page callback' => 'drupal_get_form',
  113. 'page arguments' => array('locale_language_providers_session_form'),
  114. 'access arguments' => array('administer languages'),
  115. 'file' => 'locale.admin.inc',
  116. 'type' => MENU_VISIBLE_IN_BREADCRUMB,
  117. );
  118. $items['admin/config/regional/language/edit/%'] = array(
  119. 'title' => 'Edit language',
  120. 'page callback' => 'drupal_get_form',
  121. 'page arguments' => array('locale_languages_edit_form', 5),
  122. 'access arguments' => array('administer languages'),
  123. 'file' => 'locale.admin.inc',
  124. );
  125. $items['admin/config/regional/language/delete/%'] = array(
  126. 'title' => 'Confirm',
  127. 'page callback' => 'drupal_get_form',
  128. 'page arguments' => array('locale_languages_delete_form', 5),
  129. 'access arguments' => array('administer languages'),
  130. 'file' => 'locale.admin.inc',
  131. );
  132. // Translation functionality
  133. $items['admin/config/regional/translate'] = array(
  134. 'title' => 'Translate interface',
  135. 'description' => 'Translate the built in interface and optionally other text.',
  136. 'page callback' => 'locale_translate_overview_screen',
  137. 'access arguments' => array('translate interface'),
  138. 'file' => 'locale.admin.inc',
  139. 'weight' => -5,
  140. );
  141. $items['admin/config/regional/translate/overview'] = array(
  142. 'title' => 'Overview',
  143. 'weight' => 0,
  144. 'type' => MENU_DEFAULT_LOCAL_TASK,
  145. );
  146. $items['admin/config/regional/translate/translate'] = array(
  147. 'title' => 'Translate',
  148. 'weight' => 10,
  149. 'type' => MENU_LOCAL_TASK,
  150. 'page callback' => 'locale_translate_seek_screen', // search results and form concatenated
  151. 'access arguments' => array('translate interface'),
  152. 'file' => 'locale.admin.inc',
  153. );
  154. $items['admin/config/regional/translate/import'] = array(
  155. 'title' => 'Import',
  156. 'page callback' => 'drupal_get_form',
  157. 'page arguments' => array('locale_translate_import_form'),
  158. 'access arguments' => array('translate interface'),
  159. 'weight' => 20,
  160. 'type' => MENU_LOCAL_TASK,
  161. 'file' => 'locale.admin.inc',
  162. );
  163. $items['admin/config/regional/translate/export'] = array(
  164. 'title' => 'Export',
  165. 'page callback' => 'locale_translate_export_screen', // possibly multiple forms concatenated
  166. 'access arguments' => array('translate interface'),
  167. 'weight' => 30,
  168. 'type' => MENU_LOCAL_TASK,
  169. 'file' => 'locale.admin.inc',
  170. );
  171. $items['admin/config/regional/translate/edit/%'] = array(
  172. 'title' => 'Edit string',
  173. 'page callback' => 'drupal_get_form',
  174. 'page arguments' => array('locale_translate_edit_form', 5),
  175. 'access arguments' => array('translate interface'),
  176. 'file' => 'locale.admin.inc',
  177. );
  178. $items['admin/config/regional/translate/delete/%'] = array(
  179. 'title' => 'Delete string',
  180. 'page callback' => 'locale_translate_delete_page',
  181. 'page arguments' => array(5),
  182. 'access arguments' => array('translate interface'),
  183. 'file' => 'locale.admin.inc',
  184. );
  185. // Localize date formats.
  186. $items['admin/config/regional/date-time/locale'] = array(
  187. 'title' => 'Localize',
  188. 'description' => 'Configure date formats for each locale',
  189. 'page callback' => 'locale_date_format_language_overview_page',
  190. 'access arguments' => array('administer site configuration'),
  191. 'type' => MENU_LOCAL_TASK,
  192. 'weight' => -8,
  193. 'file' => 'locale.admin.inc',
  194. );
  195. $items['admin/config/regional/date-time/locale/%/edit'] = array(
  196. 'title' => 'Localize date formats',
  197. 'description' => 'Configure date formats for each locale',
  198. 'page callback' => 'drupal_get_form',
  199. 'page arguments' => array('locale_date_format_form', 5),
  200. 'access arguments' => array('administer site configuration'),
  201. 'file' => 'locale.admin.inc',
  202. );
  203. $items['admin/config/regional/date-time/locale/%/reset'] = array(
  204. 'title' => 'Reset date formats',
  205. 'description' => 'Reset localized date formats to global defaults',
  206. 'page callback' => 'drupal_get_form',
  207. 'page arguments' => array('locale_date_format_reset_form', 5),
  208. 'access arguments' => array('administer site configuration'),
  209. 'file' => 'locale.admin.inc',
  210. );
  211. return $items;
  212. }
  213. /**
  214. * Implements hook_init().
  215. *
  216. * Initialize date formats according to the user's current locale.
  217. */
  218. function locale_init() {
  219. global $conf, $language;
  220. include_once DRUPAL_ROOT . '/includes/locale.inc';
  221. // For each date type (e.g. long, short), get the localized date format
  222. // for the user's current language and override the default setting for it
  223. // in $conf. This should happen on all pages except the date and time formats
  224. // settings page, where we want to display the site default and not the
  225. // localized version.
  226. if (strpos($_GET['q'], 'admin/config/regional/date-time/formats') !== 0) {
  227. $languages = array($language->language);
  228. // Setup appropriate date formats for this locale.
  229. $formats = locale_get_localized_date_format($languages);
  230. foreach ($formats as $format_type => $format) {
  231. $conf[$format_type] = $format;
  232. }
  233. }
  234. }
  235. /**
  236. * Implements hook_permission().
  237. */
  238. function locale_permission() {
  239. return array(
  240. 'administer languages' => array(
  241. 'title' => t('Administer languages'),
  242. ),
  243. 'translate interface' => array(
  244. 'title' => t('Translate interface texts'),
  245. 'restrict access' => TRUE,
  246. ),
  247. );
  248. }
  249. /**
  250. * Implements hook_locale().
  251. */
  252. function locale_locale($op = 'groups') {
  253. switch ($op) {
  254. case 'groups':
  255. return array('default' => t('Built-in interface'));
  256. }
  257. }
  258. /**
  259. * Form builder callback to display language selection widget.
  260. *
  261. * @ingroup forms
  262. * @see locale_form_alter()
  263. */
  264. function locale_language_selector_form(&$form, &$form_state, $user) {
  265. global $language;
  266. $languages = language_list('enabled');
  267. $languages = $languages[1];
  268. // If the user is being created, we set the user language to the page language.
  269. $user_preferred_language = $user->uid ? user_preferred_language($user) : $language;
  270. $names = array();
  271. foreach ($languages as $langcode => $item) {
  272. $name = t($item->name);
  273. $names[$langcode] = $name . ($item->native != $name ? ' (' . $item->native . ')' : '');
  274. }
  275. $form['locale'] = array(
  276. '#type' => 'fieldset',
  277. '#title' => t('Language settings'),
  278. '#weight' => 1,
  279. '#access' => ($form['#user_category'] == 'account' || ($form['#user_category'] == 'register' && user_access('administer users'))),
  280. );
  281. // Get language negotiation settings.
  282. $mode = language_negotiation_get(LANGUAGE_TYPE_INTERFACE) != LANGUAGE_NEGOTIATION_DEFAULT;
  283. $form['locale']['language'] = array(
  284. '#type' => (count($names) <= 5 ? 'radios' : 'select'),
  285. '#title' => t('Language'),
  286. '#default_value' => $user_preferred_language->language,
  287. '#options' => $names,
  288. '#description' => $mode ? t("This account's default language for e-mails, and preferred language for site presentation.") : t("This account's default language for e-mails."),
  289. );
  290. }
  291. /**
  292. * Implements hook_form_FORM_ID_alter().
  293. */
  294. function locale_form_path_admin_form_alter(&$form, &$form_state) {
  295. $form['language'] = array(
  296. '#type' => 'select',
  297. '#title' => t('Language'),
  298. '#options' => array(LANGUAGE_NONE => t('All languages')) + locale_language_list('name'),
  299. '#default_value' => $form['language']['#value'],
  300. '#weight' => -10,
  301. '#description' => t('A path alias set for a specific language will always be used when displaying this page in that language, and takes precedence over path aliases set for <em>All languages</em>.'),
  302. );
  303. }
  304. /**
  305. * Implements hook_form_FORM_ID_alter().
  306. */
  307. function locale_form_node_type_form_alter(&$form, &$form_state) {
  308. if (isset($form['type'])) {
  309. $form['workflow']['language_content_type'] = array(
  310. '#type' => 'radios',
  311. '#title' => t('Multilingual support'),
  312. '#default_value' => variable_get('language_content_type_' . $form['#node_type']->type, 0),
  313. '#options' => array(t('Disabled'), t('Enabled')),
  314. '#description' => t('Enable multilingual support for this content type. If enabled, a language selection field will be added to the editing form, allowing you to select from one of the <a href="!languages">enabled languages</a>. If disabled, new posts are saved with the default language. Existing content will not be affected by changing this option.', array('!languages' => url('admin/config/regional/language'))),
  315. );
  316. }
  317. }
  318. /**
  319. * Return whether the given content type has multilingual support.
  320. *
  321. * @return
  322. * True if multilingual support is enabled.
  323. */
  324. function locale_multilingual_node_type($type_name) {
  325. return (bool) variable_get('language_content_type_' . $type_name, 0);
  326. }
  327. /**
  328. * Implements hook_form_alter().
  329. *
  330. * Adds language fields to user forms.
  331. */
  332. function locale_form_alter(&$form, &$form_state, $form_id) {
  333. // Only alter user forms if there is more than one language.
  334. if (drupal_multilingual()) {
  335. // Display language selector when either creating a user on the admin
  336. // interface or editing a user account.
  337. if ($form_id == 'user_register_form' || ($form_id == 'user_profile_form' && $form['#user_category'] == 'account')) {
  338. locale_language_selector_form($form, $form_state, $form['#user']);
  339. }
  340. }
  341. }
  342. /**
  343. * Implements hook_form_BASE_FORM_ID_alter().
  344. */
  345. function locale_form_node_form_alter(&$form, &$form_state) {
  346. if (isset($form['#node']->type) && locale_multilingual_node_type($form['#node']->type)) {
  347. $form['language'] = array(
  348. '#type' => 'select',
  349. '#title' => t('Language'),
  350. '#default_value' => (isset($form['#node']->language) ? $form['#node']->language : ''),
  351. '#options' => array(LANGUAGE_NONE => t('Language neutral')) + locale_language_list('name'),
  352. );
  353. }
  354. // Node type without language selector: assign the default for new nodes
  355. elseif (!isset($form['#node']->nid)) {
  356. $default = language_default();
  357. $form['language'] = array(
  358. '#type' => 'value',
  359. '#value' => $default->language
  360. );
  361. }
  362. $form['#submit'][] = 'locale_field_node_form_submit';
  363. }
  364. /**
  365. * Form submit handler for node_form().
  366. *
  367. * Checks if Locale is registered as a translation handler and handle possible
  368. * node language changes.
  369. *
  370. * This submit handler needs to run before entity_form_submit_build_entity()
  371. * is invoked by node_form_submit_build_node(), because it alters the values of
  372. * attached fields. Therefore, it cannot be a hook_node_submit() implementation.
  373. */
  374. function locale_field_node_form_submit($form, &$form_state) {
  375. if (field_has_translation_handler('node', 'locale')) {
  376. $node = (object) $form_state['values'];
  377. $current_language = entity_language('node', $node);
  378. list(, , $bundle) = entity_extract_ids('node', $node);
  379. foreach (field_info_instances('node', $bundle) as $instance) {
  380. $field_name = $instance['field_name'];
  381. $field = field_info_field($field_name);
  382. $previous_language = $form[$field_name]['#language'];
  383. // Handle a possible language change: new language values are inserted,
  384. // previous ones are deleted.
  385. if ($field['translatable'] && $previous_language != $current_language) {
  386. $form_state['values'][$field_name][$current_language] = $node->{$field_name}[$previous_language];
  387. $form_state['values'][$field_name][$previous_language] = array();
  388. }
  389. }
  390. }
  391. }
  392. /**
  393. * Implements hook_theme().
  394. */
  395. function locale_theme() {
  396. return array(
  397. 'locale_languages_overview_form' => array(
  398. 'render element' => 'form',
  399. ),
  400. 'locale_languages_configure_form' => array(
  401. 'render element' => 'form',
  402. ),
  403. 'locale_date_format_form' => array(
  404. 'render element' => 'form',
  405. ),
  406. );
  407. }
  408. /**
  409. * Implements hook_field_language_alter().
  410. */
  411. function locale_field_language_alter(&$display_language, $context) {
  412. // Do not apply core language fallback rules if they are disabled or if Locale
  413. // is not registered as a translation handler.
  414. if (variable_get('locale_field_language_fallback', TRUE) && field_has_translation_handler($context['entity_type'], 'locale')) {
  415. locale_field_language_fallback($display_language, $context['entity'], $context['language']);
  416. }
  417. }
  418. /**
  419. * Applies language fallback rules to the fields attached to the given entity.
  420. *
  421. * Core language fallback rules simply check if fields have a field translation
  422. * for the requested language code. If so the requested language is returned,
  423. * otherwise all the fallback candidates are inspected to see if there is a
  424. * field translation available in another language.
  425. * By default this is called by locale_field_language_alter(), but this
  426. * behavior can be disabled by setting the 'locale_field_language_fallback'
  427. * variable to FALSE.
  428. *
  429. * @param $display_language
  430. * A reference to an array of language codes keyed by field name.
  431. * @param $entity
  432. * The entity to be displayed.
  433. * @param $langcode
  434. * The language code $entity has to be displayed in.
  435. */
  436. function locale_field_language_fallback(&$display_language, $entity, $langcode) {
  437. // Lazily init fallback candidates to avoid unnecessary calls.
  438. $fallback_candidates = NULL;
  439. $field_languages = array();
  440. foreach ($display_language as $field_name => $field_language) {
  441. // If the requested language is defined for the current field use it,
  442. // otherwise search for a fallback value among the fallback candidates.
  443. if (isset($entity->{$field_name}[$langcode])) {
  444. $display_language[$field_name] = $langcode;
  445. }
  446. elseif (!empty($entity->{$field_name})) {
  447. if (!isset($fallback_candidates)) {
  448. require_once DRUPAL_ROOT . '/includes/language.inc';
  449. $fallback_candidates = language_fallback_get_candidates();
  450. }
  451. foreach ($fallback_candidates as $fallback_language) {
  452. if (isset($entity->{$field_name}[$fallback_language])) {
  453. $display_language[$field_name] = $fallback_language;
  454. break;
  455. }
  456. }
  457. }
  458. }
  459. }
  460. /**
  461. * Implements hook_entity_info_alter().
  462. */
  463. function locale_entity_info_alter(&$entity_info) {
  464. $entity_info['node']['translation']['locale'] = TRUE;
  465. }
  466. /**
  467. * Implements hook_language_types_info().
  468. *
  469. * Defines the three core language types:
  470. * - Interface language is the only configurable language type in core. It is
  471. * used by t() as the default language if none is specified.
  472. * - Content language is by default non-configurable and inherits the interface
  473. * language negotiated value. It is used by the Field API to determine the
  474. * display language for fields if no explicit value is specified.
  475. * - URL language is by default non-configurable and is determined through the
  476. * URL language provider or the URL fallback provider if no language can be
  477. * detected. It is used by l() as the default language if none is specified.
  478. */
  479. function locale_language_types_info() {
  480. require_once DRUPAL_ROOT . '/includes/locale.inc';
  481. return array(
  482. LANGUAGE_TYPE_INTERFACE => array(
  483. 'name' => t('User interface text'),
  484. 'description' => t('Order of language detection methods for user interface text. If a translation of user interface text is available in the detected language, it will be displayed.'),
  485. ),
  486. LANGUAGE_TYPE_CONTENT => array(
  487. 'name' => t('Content'),
  488. 'description' => t('Order of language detection methods for content. If a version of content is available in the detected language, it will be displayed.'),
  489. 'fixed' => array(LOCALE_LANGUAGE_NEGOTIATION_INTERFACE),
  490. ),
  491. LANGUAGE_TYPE_URL => array(
  492. 'fixed' => array(LOCALE_LANGUAGE_NEGOTIATION_URL, LOCALE_LANGUAGE_NEGOTIATION_URL_FALLBACK),
  493. ),
  494. );
  495. }
  496. /**
  497. * Implements hook_language_negotiation_info().
  498. */
  499. function locale_language_negotiation_info() {
  500. $file = 'includes/locale.inc';
  501. $providers = array();
  502. $providers[LOCALE_LANGUAGE_NEGOTIATION_URL] = array(
  503. 'types' => array(LANGUAGE_TYPE_CONTENT, LANGUAGE_TYPE_INTERFACE, LANGUAGE_TYPE_URL),
  504. 'callbacks' => array(
  505. 'language' => 'locale_language_from_url',
  506. 'switcher' => 'locale_language_switcher_url',
  507. 'url_rewrite' => 'locale_language_url_rewrite_url',
  508. ),
  509. 'file' => $file,
  510. 'weight' => -8,
  511. 'name' => t('URL'),
  512. 'description' => t('Determine the language from the URL (Path prefix or domain).'),
  513. 'config' => 'admin/config/regional/language/configure/url',
  514. );
  515. $providers[LOCALE_LANGUAGE_NEGOTIATION_SESSION] = array(
  516. 'callbacks' => array(
  517. 'language' => 'locale_language_from_session',
  518. 'switcher' => 'locale_language_switcher_session',
  519. 'url_rewrite' => 'locale_language_url_rewrite_session',
  520. ),
  521. 'file' => $file,
  522. 'weight' => -6,
  523. 'name' => t('Session'),
  524. 'description' => t('Determine the language from a request/session parameter.'),
  525. 'config' => 'admin/config/regional/language/configure/session',
  526. );
  527. $providers[LOCALE_LANGUAGE_NEGOTIATION_USER] = array(
  528. 'callbacks' => array('language' => 'locale_language_from_user'),
  529. 'file' => $file,
  530. 'weight' => -4,
  531. 'name' => t('User'),
  532. 'description' => t("Follow the user's language preference."),
  533. );
  534. $providers[LOCALE_LANGUAGE_NEGOTIATION_BROWSER] = array(
  535. 'callbacks' => array('language' => 'locale_language_from_browser'),
  536. 'file' => $file,
  537. 'weight' => -2,
  538. 'cache' => 0,
  539. 'name' => t('Browser'),
  540. 'description' => t("Determine the language from the browser's language settings."),
  541. );
  542. $providers[LOCALE_LANGUAGE_NEGOTIATION_INTERFACE] = array(
  543. 'types' => array(LANGUAGE_TYPE_CONTENT),
  544. 'callbacks' => array('language' => 'locale_language_from_interface'),
  545. 'file' => $file,
  546. 'weight' => 8,
  547. 'name' => t('Interface'),
  548. 'description' => t('Use the detected interface language.'),
  549. );
  550. $providers[LOCALE_LANGUAGE_NEGOTIATION_URL_FALLBACK] = array(
  551. 'types' => array(LANGUAGE_TYPE_URL),
  552. 'callbacks' => array('language' => 'locale_language_url_fallback'),
  553. 'file' => $file,
  554. 'weight' => 8,
  555. 'name' => t('URL fallback'),
  556. 'description' => t('Use an already detected language for URLs if none is found.'),
  557. );
  558. return $providers;
  559. }
  560. /**
  561. * Implements hook_modules_enabled().
  562. */
  563. function locale_modules_enabled($modules) {
  564. include_once DRUPAL_ROOT . '/includes/language.inc';
  565. language_types_set();
  566. language_negotiation_purge();
  567. }
  568. /**
  569. * Implements hook_modules_disabled().
  570. */
  571. function locale_modules_disabled($modules) {
  572. locale_modules_enabled($modules);
  573. }
  574. // ---------------------------------------------------------------------------------
  575. // Locale core functionality
  576. /**
  577. * Provides interface translation services.
  578. *
  579. * This function is called from t() to translate a string if needed.
  580. *
  581. * @param $string
  582. * A string to look up translation for. If omitted, all the
  583. * cached strings will be returned in all languages already
  584. * used on the page.
  585. * @param $context
  586. * The context of this string.
  587. * @param $langcode
  588. * Language code to use for the lookup.
  589. */
  590. function locale($string = NULL, $context = NULL, $langcode = NULL) {
  591. global $language;
  592. // Use the advanced drupal_static() pattern, since this is called very often.
  593. static $drupal_static_fast;
  594. if (!isset($drupal_static_fast)) {
  595. $drupal_static_fast['locale'] = &drupal_static(__FUNCTION__);
  596. }
  597. $locale_t = &$drupal_static_fast['locale'];
  598. if (!isset($string)) {
  599. // Return all cached strings if no string was specified
  600. return $locale_t;
  601. }
  602. $langcode = isset($langcode) ? $langcode : $language->language;
  603. // Store database cached translations in a static variable. Only build the
  604. // cache after $language has been set to avoid an unnecessary cache rebuild.
  605. if (!isset($locale_t[$langcode]) && isset($language)) {
  606. $locale_t[$langcode] = array();
  607. // Disabling the usage of string caching allows a module to watch for
  608. // the exact list of strings used on a page. From a performance
  609. // perspective that is a really bad idea, so we have no user
  610. // interface for this. Be careful when turning this option off!
  611. if (variable_get('locale_cache_strings', 1) == 1) {
  612. if ($cache = cache_get('locale:' . $langcode, 'cache')) {
  613. $locale_t[$langcode] = $cache->data;
  614. }
  615. elseif (lock_acquire('locale_cache_' . $langcode)) {
  616. // Refresh database stored cache of translations for given language.
  617. // We only store short strings used in current version, to improve
  618. // performance and consume less memory.
  619. $result = db_query("SELECT s.source, s.context, t.translation, t.language FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language WHERE s.textgroup = 'default' AND s.version = :version AND LENGTH(s.source) < :length", array(':language' => $langcode, ':version' => VERSION, ':length' => variable_get('locale_cache_length', 75)));
  620. foreach ($result as $data) {
  621. $locale_t[$langcode][$data->context][$data->source] = (empty($data->translation) ? TRUE : $data->translation);
  622. }
  623. cache_set('locale:' . $langcode, $locale_t[$langcode]);
  624. lock_release('locale_cache_' . $langcode);
  625. }
  626. }
  627. }
  628. // If we have the translation cached, skip checking the database
  629. if (!isset($locale_t[$langcode][$context][$string])) {
  630. // We do not have this translation cached, so get it from the DB.
  631. $translation = db_query("SELECT s.lid, t.translation, s.version FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language WHERE s.source = :source AND s.context = :context AND s.textgroup = 'default'", array(
  632. ':language' => $langcode,
  633. ':source' => $string,
  634. ':context' => (string) $context,
  635. ))->fetchObject();
  636. if ($translation) {
  637. // We have the source string at least.
  638. // Cache translation string or TRUE if no translation exists.
  639. $locale_t[$langcode][$context][$string] = (empty($translation->translation) ? TRUE : $translation->translation);
  640. if ($translation->version != VERSION) {
  641. // This is the first use of this string under current Drupal version. Save version
  642. // and clear cache, to include the string into caching next time. Saved version is
  643. // also a string-history information for later pruning of the tables.
  644. db_update('locales_source')
  645. ->fields(array('version' => VERSION))
  646. ->condition('lid', $translation->lid)
  647. ->execute();
  648. cache_clear_all('locale:', 'cache', TRUE);
  649. }
  650. }
  651. else {
  652. // We don't have the source string, cache this as untranslated.
  653. db_merge('locales_source')
  654. ->insertFields(array(
  655. 'location' => request_uri(),
  656. 'version' => VERSION,
  657. ))
  658. ->key(array(
  659. 'source' => $string,
  660. 'context' => (string) $context,
  661. 'textgroup' => 'default',
  662. ))
  663. ->execute();
  664. $locale_t[$langcode][$context][$string] = TRUE;
  665. // Clear locale cache so this string can be added in a later request.
  666. cache_clear_all('locale:', 'cache', TRUE);
  667. }
  668. }
  669. return ($locale_t[$langcode][$context][$string] === TRUE ? $string : $locale_t[$langcode][$context][$string]);
  670. }
  671. /**
  672. * Reset static variables used by locale().
  673. */
  674. function locale_reset() {
  675. drupal_static_reset('locale');
  676. }
  677. /**
  678. * Returns plural form index for a specific number.
  679. *
  680. * The index is computed from the formula of this language.
  681. *
  682. * @param $count
  683. * Number to return plural for.
  684. * @param $langcode
  685. * Optional language code to translate to a language other than
  686. * what is used to display the page.
  687. *
  688. * @return
  689. * The numeric index of the plural variant to use for this $langcode and
  690. * $count combination or -1 if the language was not found or does not have a
  691. * plural formula.
  692. */
  693. function locale_get_plural($count, $langcode = NULL) {
  694. global $language;
  695. // Used to locally cache the plural formulas for all languages.
  696. $plural_formulas = &drupal_static(__FUNCTION__, array());
  697. // Used to store precomputed plural indexes corresponding to numbers
  698. // individually for each language.
  699. $plural_indexes = &drupal_static(__FUNCTION__ . ':plurals', array());
  700. $langcode = $langcode ? $langcode : $language->language;
  701. if (!isset($plural_indexes[$langcode][$count])) {
  702. // Retrieve and statically cache the plural formulas for all languages.
  703. if (empty($plural_formulas)) {
  704. foreach (language_list() as $installed_language) {
  705. $plural_formulas[$installed_language->language] = $installed_language->formula;
  706. }
  707. }
  708. // If there is a plural formula for the language, evaluate it for the given
  709. // $count and statically cache the result for the combination of language
  710. // and count, since the result will always be identical.
  711. if (!empty($plural_formulas[$langcode])) {
  712. // $n is used inside the expression in the eval().
  713. $n = $count;
  714. $plural_indexes[$langcode][$count] = @eval('return intval(' . $plural_formulas[$langcode] . ');');
  715. }
  716. // In case there is no plural formula for English (no imported translation
  717. // for English), use a default formula.
  718. elseif ($langcode == 'en') {
  719. $plural_indexes[$langcode][$count] = (int) ($count != 1);
  720. }
  721. // Otherwise, return -1 (unknown).
  722. else {
  723. $plural_indexes[$langcode][$count] = -1;
  724. }
  725. }
  726. return $plural_indexes[$langcode][$count];
  727. }
  728. /**
  729. * Returns a language name
  730. */
  731. function locale_language_name($lang) {
  732. $list = &drupal_static(__FUNCTION__);
  733. if (!isset($list)) {
  734. $list = locale_language_list();
  735. }
  736. return ($lang && isset($list[$lang])) ? $list[$lang] : t('All');
  737. }
  738. /**
  739. * Returns array of language names
  740. *
  741. * @param $field
  742. * 'name' => names in current language, localized
  743. * 'native' => native names
  744. * @param $all
  745. * Boolean to return all languages or only enabled ones
  746. */
  747. function locale_language_list($field = 'name', $all = FALSE) {
  748. if ($all) {
  749. $languages = language_list();
  750. }
  751. else {
  752. $languages = language_list('enabled');
  753. $languages = $languages[1];
  754. }
  755. $list = array();
  756. foreach ($languages as $language) {
  757. $list[$language->language] = ($field == 'name') ? t($language->name) : $language->$field;
  758. }
  759. return $list;
  760. }
  761. /**
  762. * Implements hook_modules_installed().
  763. */
  764. function locale_modules_installed($modules) {
  765. locale_system_update($modules);
  766. }
  767. /**
  768. * Implements hook_themes_enabled().
  769. *
  770. * @todo This is technically wrong. We must not import upon enabling, but upon
  771. * initial installation. The theme system is missing an installation hook.
  772. */
  773. function locale_themes_enabled($themes) {
  774. locale_system_update($themes);
  775. }
  776. /**
  777. * Imports translations when new modules or themes are installed.
  778. *
  779. * This function will either import translation for the component change
  780. * right away, or start a batch if more files need to be imported.
  781. *
  782. * @param $components
  783. * An array of component (theme and/or module) names to import
  784. * translations for.
  785. */
  786. function locale_system_update($components) {
  787. include_once DRUPAL_ROOT . '/includes/locale.inc';
  788. if ($batch = locale_batch_by_component($components)) {
  789. batch_set($batch);
  790. }
  791. }
  792. /**
  793. * Implements hook_js_alter().
  794. *
  795. * This function checks all JavaScript files currently added via drupal_add_js()
  796. * and invokes parsing if they have not yet been parsed for Drupal.t()
  797. * and Drupal.formatPlural() calls. Also refreshes the JavaScript translation
  798. * file if necessary, and adds it to the page.
  799. */
  800. function locale_js_alter(&$javascript) {
  801. global $language;
  802. $dir = 'public://' . variable_get('locale_js_directory', 'languages');
  803. $parsed = variable_get('javascript_parsed', array());
  804. $files = $new_files = FALSE;
  805. // Require because locale_js_alter() could be called without locale_init().
  806. require_once DRUPAL_ROOT . '/includes/locale.inc';
  807. foreach ($javascript as $item) {
  808. if ($item['type'] == 'file') {
  809. $files = TRUE;
  810. $filepath = $item['data'];
  811. if (!in_array($filepath, $parsed)) {
  812. // Don't parse our own translations files.
  813. if (substr($filepath, 0, strlen($dir)) != $dir) {
  814. _locale_parse_js_file($filepath);
  815. $parsed[] = $filepath;
  816. $new_files = TRUE;
  817. }
  818. }
  819. }
  820. }
  821. // If there are any new source files we parsed, invalidate existing
  822. // JavaScript translation files for all languages, adding the refresh
  823. // flags into the existing array.
  824. if ($new_files) {
  825. $parsed += _locale_invalidate_js();
  826. }
  827. // If necessary, rebuild the translation file for the current language.
  828. if (!empty($parsed['refresh:' . $language->language])) {
  829. // Don't clear the refresh flag on failure, so that another try will
  830. // be performed later.
  831. if (_locale_rebuild_js()) {
  832. unset($parsed['refresh:' . $language->language]);
  833. }
  834. // Store any changes after refresh was attempted.
  835. variable_set('javascript_parsed', $parsed);
  836. }
  837. // If no refresh was attempted, but we have new source files, we need
  838. // to store them too. This occurs if current page is in English.
  839. elseif ($new_files) {
  840. variable_set('javascript_parsed', $parsed);
  841. }
  842. // Add the translation JavaScript file to the page.
  843. if ($files && !empty($language->javascript)) {
  844. // Add the translation JavaScript file to the page.
  845. $file = $dir . '/' . $language->language . '_' . $language->javascript . '.js';
  846. $javascript[$file] = drupal_js_defaults($file);
  847. }
  848. }
  849. /**
  850. * Implements hook_css_alter().
  851. *
  852. * This function checks all CSS files currently added via drupal_add_css() and
  853. * and checks to see if a related right to left CSS file should be included.
  854. */
  855. function locale_css_alter(&$css) {
  856. global $language;
  857. // If the current language is RTL, add the CSS file with the RTL overrides.
  858. if ($language->direction == LANGUAGE_RTL) {
  859. foreach ($css as $data => $item) {
  860. // Only provide RTL overrides for files.
  861. if ($item['type'] == 'file') {
  862. $rtl_path = str_replace('.css', '-rtl.css', $item['data']);
  863. if (file_exists($rtl_path) && !isset($css[$rtl_path])) {
  864. // Replicate the same item, but with the RTL path and a little larger
  865. // weight so that it appears directly after the original CSS file.
  866. $item['data'] = $rtl_path;
  867. $item['weight'] += 0.01;
  868. $css[$rtl_path] = $item;
  869. }
  870. }
  871. }
  872. }
  873. }
  874. /**
  875. * Implement hook_library_alter().
  876. *
  877. * Provides the language support for the jQuery UI Date Picker.
  878. */
  879. function locale_library_alter(&$libraries, $module) {
  880. if ($module == 'system' && isset($libraries['ui.datepicker'])) {
  881. global $language;
  882. // locale.datepicker.js should be added in the JS_LIBRARY group, so that
  883. // this attach behavior will execute early. JS_LIBRARY is the default for
  884. // hook_library_info_alter(), thus does not have to be specified explicitly.
  885. $datepicker = drupal_get_path('module', 'locale') . '/locale.datepicker.js';
  886. $libraries['ui.datepicker']['js'][$datepicker] = array();
  887. $libraries['ui.datepicker']['js'][] = array(
  888. 'data' => array(
  889. 'jquery' => array(
  890. 'ui' => array(
  891. 'datepicker' => array(
  892. 'isRTL' => $language->direction == LANGUAGE_RTL,
  893. 'firstDay' => variable_get('date_first_day', 0),
  894. ),
  895. ),
  896. ),
  897. ),
  898. 'type' => 'setting',
  899. );
  900. }
  901. }
  902. // ---------------------------------------------------------------------------------
  903. // Language switcher block
  904. /**
  905. * Implements hook_block_info().
  906. */
  907. function locale_block_info() {
  908. include_once DRUPAL_ROOT . '/includes/language.inc';
  909. $block = array();
  910. $info = language_types_info();
  911. foreach (language_types_configurable(FALSE) as $type) {
  912. $block[$type] = array(
  913. 'info' => t('Language switcher (@type)', array('@type' => $info[$type]['name'])),
  914. // Not worth caching.
  915. 'cache' => DRUPAL_NO_CACHE,
  916. );
  917. }
  918. return $block;
  919. }
  920. /**
  921. * Implements hook_block_view().
  922. *
  923. * Displays a language switcher. Only show if we have at least two languages.
  924. */
  925. function locale_block_view($type) {
  926. if (drupal_multilingual()) {
  927. $path = drupal_is_front_page() ? '<front>' : $_GET['q'];
  928. $links = language_negotiation_get_switch_links($type, $path);
  929. if (isset($links->links)) {
  930. drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
  931. $class = "language-switcher-{$links->provider}";
  932. $variables = array('links' => $links->links, 'attributes' => array('class' => array($class)));
  933. $block['content'] = theme('links__locale_block', $variables);
  934. $block['subject'] = t('Languages');
  935. return $block;
  936. }
  937. }
  938. }
  939. /**
  940. * Implements hook_url_outbound_alter().
  941. *
  942. * Rewrite outbound URLs with language based prefixes.
  943. */
  944. function locale_url_outbound_alter(&$path, &$options, $original_path) {
  945. // Only modify internal URLs.
  946. if (!$options['external'] && drupal_multilingual()) {
  947. static $drupal_static_fast;
  948. if (!isset($drupal_static_fast)) {
  949. $drupal_static_fast['callbacks'] = &drupal_static(__FUNCTION__);
  950. }
  951. $callbacks = &$drupal_static_fast['callbacks'];
  952. if (!isset($callbacks)) {
  953. $callbacks = array();
  954. include_once DRUPAL_ROOT . '/includes/language.inc';
  955. foreach (language_types_configurable() as $type) {
  956. // Get URL rewriter callbacks only from enabled language providers.
  957. $negotiation = variable_get("language_negotiation_$type", array());
  958. foreach ($negotiation as $id => $provider) {
  959. if (isset($provider['callbacks']['url_rewrite'])) {
  960. if (isset($provider['file'])) {
  961. require_once DRUPAL_ROOT . '/' . $provider['file'];
  962. }
  963. // Avoid duplicate callback entries.
  964. $callbacks[$provider['callbacks']['url_rewrite']] = TRUE;
  965. }
  966. }
  967. }
  968. $callbacks = array_keys($callbacks);
  969. }
  970. foreach ($callbacks as $callback) {
  971. $callback($path, $options);
  972. }
  973. // No language dependent path allowed in this mode.
  974. if (empty($callbacks)) {
  975. unset($options['language']);
  976. }
  977. }
  978. }
  979. /**
  980. * Implements hook_form_FORM_ID_alter().
  981. */
  982. function locale_form_comment_form_alter(&$form, &$form_state, $form_id) {
  983. // If a content type has multilingual support we set the content language as
  984. // comment language.
  985. if ($form['language']['#value'] == LANGUAGE_NONE && locale_multilingual_node_type($form['#node']->type)) {
  986. global $language_content;
  987. $form['language']['#value'] = $language_content->language;
  988. }
  989. }