locale.module 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  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. * This submit handler needs to run before entity_form_submit_build_entity()
  368. * is invoked by node_form_submit_build_node(), because it alters the values of
  369. * attached fields. Therefore, it cannot be a hook_node_submit() implementation.
  370. */
  371. function locale_field_node_form_submit($form, &$form_state) {
  372. locale_field_entity_form_submit('node', $form, $form_state);
  373. }
  374. /**
  375. * Implements hook_form_FORM_ID_alter().
  376. */
  377. function locale_form_comment_form_alter(&$form, &$form_state, $form_id) {
  378. // If a content type has multilingual support we set the content language as
  379. // comment language.
  380. if ($form['language']['#value'] == LANGUAGE_NONE && locale_multilingual_node_type($form['#node']->type)) {
  381. global $language_content;
  382. $form['language']['#value'] = $language_content->language;
  383. $submit_callback = 'locale_field_comment_form_submit';
  384. array_unshift($form['actions']['preview']['#submit'], $submit_callback);
  385. array_unshift($form['#submit'], $submit_callback);
  386. }
  387. }
  388. /**
  389. * Form submit handler for comment_form().
  390. *
  391. * This submit handler needs to run before entity_form_submit_build_entity()
  392. * is invoked by comment_form_submit_build_comment(), because it alters the
  393. * values of attached fields.
  394. */
  395. function locale_field_comment_form_submit($form, &$form_state) {
  396. locale_field_entity_form_submit('comment', $form, $form_state);
  397. }
  398. /**
  399. * Handles field language on submit for the given entity type.
  400. *
  401. * Checks if Locale is registered as a translation handler and handle possible
  402. * language changes.
  403. */
  404. function locale_field_entity_form_submit($entity_type, $form, &$form_state ) {
  405. if (field_has_translation_handler($entity_type, 'locale')) {
  406. $entity = (object) $form_state['values'];
  407. $current_language = entity_language($entity_type, $entity);
  408. list(, , $bundle) = entity_extract_ids($entity_type, $entity);
  409. foreach (field_info_instances($entity_type, $bundle) as $instance) {
  410. $field_name = $instance['field_name'];
  411. $field = field_info_field($field_name);
  412. $previous_language = $form[$field_name]['#language'];
  413. // Handle a possible language change: new language values are inserted,
  414. // previous ones are deleted.
  415. if ($field['translatable'] && $previous_language != $current_language) {
  416. $form_state['values'][$field_name][$current_language] = $entity->{$field_name}[$previous_language];
  417. $form_state['values'][$field_name][$previous_language] = array();
  418. }
  419. }
  420. }
  421. }
  422. /**
  423. * Implements hook_theme().
  424. */
  425. function locale_theme() {
  426. return array(
  427. 'locale_languages_overview_form' => array(
  428. 'render element' => 'form',
  429. ),
  430. 'locale_languages_configure_form' => array(
  431. 'render element' => 'form',
  432. ),
  433. 'locale_date_format_form' => array(
  434. 'render element' => 'form',
  435. ),
  436. );
  437. }
  438. /**
  439. * Implements hook_field_language_alter().
  440. */
  441. function locale_field_language_alter(&$display_language, $context) {
  442. // Do not apply core language fallback rules if they are disabled or if Locale
  443. // is not registered as a translation handler.
  444. if (variable_get('locale_field_language_fallback', TRUE) && field_has_translation_handler($context['entity_type'], 'locale')) {
  445. locale_field_language_fallback($display_language, $context['entity'], $context['language']);
  446. }
  447. }
  448. /**
  449. * Applies language fallback rules to the fields attached to the given entity.
  450. *
  451. * Core language fallback rules simply check if fields have a field translation
  452. * for the requested language code. If so the requested language is returned,
  453. * otherwise all the fallback candidates are inspected to see if there is a
  454. * field translation available in another language.
  455. * By default this is called by locale_field_language_alter(), but this
  456. * behavior can be disabled by setting the 'locale_field_language_fallback'
  457. * variable to FALSE.
  458. *
  459. * @param $display_language
  460. * A reference to an array of language codes keyed by field name.
  461. * @param $entity
  462. * The entity to be displayed.
  463. * @param $langcode
  464. * The language code $entity has to be displayed in.
  465. */
  466. function locale_field_language_fallback(&$display_language, $entity, $langcode) {
  467. // Lazily init fallback candidates to avoid unnecessary calls.
  468. $fallback_candidates = NULL;
  469. $field_languages = array();
  470. foreach ($display_language as $field_name => $field_language) {
  471. // If the requested language is defined for the current field use it,
  472. // otherwise search for a fallback value among the fallback candidates.
  473. if (isset($entity->{$field_name}[$langcode])) {
  474. $display_language[$field_name] = $langcode;
  475. }
  476. elseif (!empty($entity->{$field_name})) {
  477. if (!isset($fallback_candidates)) {
  478. require_once DRUPAL_ROOT . '/includes/language.inc';
  479. $fallback_candidates = language_fallback_get_candidates();
  480. }
  481. foreach ($fallback_candidates as $fallback_language) {
  482. if (isset($entity->{$field_name}[$fallback_language])) {
  483. $display_language[$field_name] = $fallback_language;
  484. break;
  485. }
  486. }
  487. }
  488. }
  489. }
  490. /**
  491. * Implements hook_entity_info_alter().
  492. */
  493. function locale_entity_info_alter(&$entity_info) {
  494. $entity_info['node']['translation']['locale'] = TRUE;
  495. if (isset($entity_info['comment'])) {
  496. $entity_info['comment']['translation']['locale'] = TRUE;
  497. }
  498. }
  499. /**
  500. * Implements hook_language_types_info().
  501. *
  502. * Defines the three core language types:
  503. * - Interface language is the only configurable language type in core. It is
  504. * used by t() as the default language if none is specified.
  505. * - Content language is by default non-configurable and inherits the interface
  506. * language negotiated value. It is used by the Field API to determine the
  507. * display language for fields if no explicit value is specified.
  508. * - URL language is by default non-configurable and is determined through the
  509. * URL language provider or the URL fallback provider if no language can be
  510. * detected. It is used by l() as the default language if none is specified.
  511. */
  512. function locale_language_types_info() {
  513. require_once DRUPAL_ROOT . '/includes/locale.inc';
  514. return array(
  515. LANGUAGE_TYPE_INTERFACE => array(
  516. 'name' => t('User interface text'),
  517. '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.'),
  518. ),
  519. LANGUAGE_TYPE_CONTENT => array(
  520. 'name' => t('Content'),
  521. 'description' => t('Order of language detection methods for content. If a version of content is available in the detected language, it will be displayed.'),
  522. 'fixed' => array(LOCALE_LANGUAGE_NEGOTIATION_INTERFACE),
  523. ),
  524. LANGUAGE_TYPE_URL => array(
  525. 'fixed' => array(LOCALE_LANGUAGE_NEGOTIATION_URL, LOCALE_LANGUAGE_NEGOTIATION_URL_FALLBACK),
  526. ),
  527. );
  528. }
  529. /**
  530. * Implements hook_language_negotiation_info().
  531. */
  532. function locale_language_negotiation_info() {
  533. $file = 'includes/locale.inc';
  534. $providers = array();
  535. $providers[LOCALE_LANGUAGE_NEGOTIATION_URL] = array(
  536. 'types' => array(LANGUAGE_TYPE_CONTENT, LANGUAGE_TYPE_INTERFACE, LANGUAGE_TYPE_URL),
  537. 'callbacks' => array(
  538. 'language' => 'locale_language_from_url',
  539. 'switcher' => 'locale_language_switcher_url',
  540. 'url_rewrite' => 'locale_language_url_rewrite_url',
  541. ),
  542. 'file' => $file,
  543. 'weight' => -8,
  544. 'name' => t('URL'),
  545. 'description' => t('Determine the language from the URL (Path prefix or domain).'),
  546. 'config' => 'admin/config/regional/language/configure/url',
  547. );
  548. $providers[LOCALE_LANGUAGE_NEGOTIATION_SESSION] = array(
  549. 'callbacks' => array(
  550. 'language' => 'locale_language_from_session',
  551. 'switcher' => 'locale_language_switcher_session',
  552. 'url_rewrite' => 'locale_language_url_rewrite_session',
  553. ),
  554. 'file' => $file,
  555. 'weight' => -6,
  556. 'name' => t('Session'),
  557. 'description' => t('Determine the language from a request/session parameter.'),
  558. 'config' => 'admin/config/regional/language/configure/session',
  559. );
  560. $providers[LOCALE_LANGUAGE_NEGOTIATION_USER] = array(
  561. 'callbacks' => array('language' => 'locale_language_from_user'),
  562. 'file' => $file,
  563. 'weight' => -4,
  564. 'name' => t('User'),
  565. 'description' => t("Follow the user's language preference."),
  566. );
  567. $providers[LOCALE_LANGUAGE_NEGOTIATION_BROWSER] = array(
  568. 'callbacks' => array('language' => 'locale_language_from_browser'),
  569. 'file' => $file,
  570. 'weight' => -2,
  571. 'cache' => 0,
  572. 'name' => t('Browser'),
  573. 'description' => t("Determine the language from the browser's language settings."),
  574. );
  575. $providers[LOCALE_LANGUAGE_NEGOTIATION_INTERFACE] = array(
  576. 'types' => array(LANGUAGE_TYPE_CONTENT),
  577. 'callbacks' => array('language' => 'locale_language_from_interface'),
  578. 'file' => $file,
  579. 'weight' => 8,
  580. 'name' => t('Interface'),
  581. 'description' => t('Use the detected interface language.'),
  582. );
  583. $providers[LOCALE_LANGUAGE_NEGOTIATION_URL_FALLBACK] = array(
  584. 'types' => array(LANGUAGE_TYPE_URL),
  585. 'callbacks' => array('language' => 'locale_language_url_fallback'),
  586. 'file' => $file,
  587. 'weight' => 8,
  588. 'name' => t('URL fallback'),
  589. 'description' => t('Use an already detected language for URLs if none is found.'),
  590. );
  591. return $providers;
  592. }
  593. /**
  594. * Implements hook_modules_enabled().
  595. */
  596. function locale_modules_enabled($modules) {
  597. include_once DRUPAL_ROOT . '/includes/language.inc';
  598. language_types_set();
  599. language_negotiation_purge();
  600. }
  601. /**
  602. * Implements hook_modules_disabled().
  603. */
  604. function locale_modules_disabled($modules) {
  605. locale_modules_enabled($modules);
  606. }
  607. // ---------------------------------------------------------------------------------
  608. // Locale core functionality
  609. /**
  610. * Provides interface translation services.
  611. *
  612. * This function is called from t() to translate a string if needed.
  613. *
  614. * @param $string
  615. * A string to look up translation for. If omitted, all the
  616. * cached strings will be returned in all languages already
  617. * used on the page.
  618. * @param $context
  619. * The context of this string.
  620. * @param $langcode
  621. * Language code to use for the lookup.
  622. */
  623. function locale($string = NULL, $context = NULL, $langcode = NULL) {
  624. global $language;
  625. // Use the advanced drupal_static() pattern, since this is called very often.
  626. static $drupal_static_fast;
  627. if (!isset($drupal_static_fast)) {
  628. $drupal_static_fast['locale'] = &drupal_static(__FUNCTION__);
  629. }
  630. $locale_t = &$drupal_static_fast['locale'];
  631. if (!isset($string)) {
  632. // Return all cached strings if no string was specified
  633. return $locale_t;
  634. }
  635. $langcode = isset($langcode) ? $langcode : $language->language;
  636. // Store database cached translations in a static variable. Only build the
  637. // cache after $language has been set to avoid an unnecessary cache rebuild.
  638. if (!isset($locale_t[$langcode]) && isset($language)) {
  639. $locale_t[$langcode] = array();
  640. // Disabling the usage of string caching allows a module to watch for
  641. // the exact list of strings used on a page. From a performance
  642. // perspective that is a really bad idea, so we have no user
  643. // interface for this. Be careful when turning this option off!
  644. if (variable_get('locale_cache_strings', 1) == 1) {
  645. if ($cache = cache_get('locale:' . $langcode, 'cache')) {
  646. $locale_t[$langcode] = $cache->data;
  647. }
  648. elseif (lock_acquire('locale_cache_' . $langcode)) {
  649. // Refresh database stored cache of translations for given language.
  650. // We only store short strings used in current version, to improve
  651. // performance and consume less memory.
  652. $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)));
  653. foreach ($result as $data) {
  654. $locale_t[$langcode][$data->context][$data->source] = (empty($data->translation) ? TRUE : $data->translation);
  655. }
  656. cache_set('locale:' . $langcode, $locale_t[$langcode]);
  657. lock_release('locale_cache_' . $langcode);
  658. }
  659. }
  660. }
  661. // If we have the translation cached, skip checking the database
  662. if (!isset($locale_t[$langcode][$context][$string])) {
  663. // We do not have this translation cached, so get it from the DB.
  664. $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(
  665. ':language' => $langcode,
  666. ':source' => $string,
  667. ':context' => (string) $context,
  668. ))->fetchObject();
  669. if ($translation) {
  670. // We have the source string at least.
  671. // Cache translation string or TRUE if no translation exists.
  672. $locale_t[$langcode][$context][$string] = (empty($translation->translation) ? TRUE : $translation->translation);
  673. if ($translation->version != VERSION) {
  674. // This is the first use of this string under current Drupal version. Save version
  675. // and clear cache, to include the string into caching next time. Saved version is
  676. // also a string-history information for later pruning of the tables.
  677. db_update('locales_source')
  678. ->fields(array('version' => VERSION))
  679. ->condition('lid', $translation->lid)
  680. ->execute();
  681. cache_clear_all('locale:', 'cache', TRUE);
  682. }
  683. }
  684. else {
  685. // We don't have the source string, cache this as untranslated.
  686. db_merge('locales_source')
  687. ->insertFields(array(
  688. 'location' => request_uri(),
  689. 'version' => VERSION,
  690. ))
  691. ->key(array(
  692. 'source' => $string,
  693. 'context' => (string) $context,
  694. 'textgroup' => 'default',
  695. ))
  696. ->execute();
  697. $locale_t[$langcode][$context][$string] = TRUE;
  698. // Clear locale cache so this string can be added in a later request.
  699. cache_clear_all('locale:', 'cache', TRUE);
  700. }
  701. }
  702. return ($locale_t[$langcode][$context][$string] === TRUE ? $string : $locale_t[$langcode][$context][$string]);
  703. }
  704. /**
  705. * Reset static variables used by locale().
  706. */
  707. function locale_reset() {
  708. drupal_static_reset('locale');
  709. }
  710. /**
  711. * Returns plural form index for a specific number.
  712. *
  713. * The index is computed from the formula of this language.
  714. *
  715. * @param $count
  716. * Number to return plural for.
  717. * @param $langcode
  718. * Optional language code to translate to a language other than
  719. * what is used to display the page.
  720. *
  721. * @return
  722. * The numeric index of the plural variant to use for this $langcode and
  723. * $count combination or -1 if the language was not found or does not have a
  724. * plural formula.
  725. */
  726. function locale_get_plural($count, $langcode = NULL) {
  727. global $language;
  728. // Used to locally cache the plural formulas for all languages.
  729. $plural_formulas = &drupal_static(__FUNCTION__, array());
  730. // Used to store precomputed plural indexes corresponding to numbers
  731. // individually for each language.
  732. $plural_indexes = &drupal_static(__FUNCTION__ . ':plurals', array());
  733. $langcode = $langcode ? $langcode : $language->language;
  734. if (!isset($plural_indexes[$langcode][$count])) {
  735. // Retrieve and statically cache the plural formulas for all languages.
  736. if (empty($plural_formulas)) {
  737. foreach (language_list() as $installed_language) {
  738. $plural_formulas[$installed_language->language] = $installed_language->formula;
  739. }
  740. }
  741. // If there is a plural formula for the language, evaluate it for the given
  742. // $count and statically cache the result for the combination of language
  743. // and count, since the result will always be identical.
  744. if (!empty($plural_formulas[$langcode])) {
  745. // $n is used inside the expression in the eval().
  746. $n = $count;
  747. $plural_indexes[$langcode][$count] = @eval('return intval(' . $plural_formulas[$langcode] . ');');
  748. }
  749. // In case there is no plural formula for English (no imported translation
  750. // for English), use a default formula.
  751. elseif ($langcode == 'en') {
  752. $plural_indexes[$langcode][$count] = (int) ($count != 1);
  753. }
  754. // Otherwise, return -1 (unknown).
  755. else {
  756. $plural_indexes[$langcode][$count] = -1;
  757. }
  758. }
  759. return $plural_indexes[$langcode][$count];
  760. }
  761. /**
  762. * Returns a language name
  763. */
  764. function locale_language_name($lang) {
  765. $list = &drupal_static(__FUNCTION__);
  766. if (!isset($list)) {
  767. $list = locale_language_list();
  768. }
  769. return ($lang && isset($list[$lang])) ? $list[$lang] : t('All');
  770. }
  771. /**
  772. * Returns array of language names
  773. *
  774. * @param $field
  775. * 'name' => names in current language, localized
  776. * 'native' => native names
  777. * @param $all
  778. * Boolean to return all languages or only enabled ones
  779. */
  780. function locale_language_list($field = 'name', $all = FALSE) {
  781. if ($all) {
  782. $languages = language_list();
  783. }
  784. else {
  785. $languages = language_list('enabled');
  786. $languages = $languages[1];
  787. }
  788. $list = array();
  789. foreach ($languages as $language) {
  790. $list[$language->language] = ($field == 'name') ? t($language->name) : $language->$field;
  791. }
  792. return $list;
  793. }
  794. /**
  795. * Implements hook_modules_installed().
  796. */
  797. function locale_modules_installed($modules) {
  798. locale_system_update($modules);
  799. }
  800. /**
  801. * Implements hook_themes_enabled().
  802. *
  803. * @todo This is technically wrong. We must not import upon enabling, but upon
  804. * initial installation. The theme system is missing an installation hook.
  805. */
  806. function locale_themes_enabled($themes) {
  807. locale_system_update($themes);
  808. }
  809. /**
  810. * Imports translations when new modules or themes are installed.
  811. *
  812. * This function will either import translation for the component change
  813. * right away, or start a batch if more files need to be imported.
  814. *
  815. * @param $components
  816. * An array of component (theme and/or module) names to import
  817. * translations for.
  818. */
  819. function locale_system_update($components) {
  820. include_once DRUPAL_ROOT . '/includes/locale.inc';
  821. if ($batch = locale_batch_by_component($components)) {
  822. batch_set($batch);
  823. }
  824. }
  825. /**
  826. * Implements hook_js_alter().
  827. *
  828. * This function checks all JavaScript files currently added via drupal_add_js()
  829. * and invokes parsing if they have not yet been parsed for Drupal.t()
  830. * and Drupal.formatPlural() calls. Also refreshes the JavaScript translation
  831. * file if necessary, and adds it to the page.
  832. */
  833. function locale_js_alter(&$javascript) {
  834. global $language;
  835. $dir = 'public://' . variable_get('locale_js_directory', 'languages');
  836. $parsed = variable_get('javascript_parsed', array());
  837. $files = $new_files = FALSE;
  838. // Require because locale_js_alter() could be called without locale_init().
  839. require_once DRUPAL_ROOT . '/includes/locale.inc';
  840. foreach ($javascript as $item) {
  841. if ($item['type'] == 'file') {
  842. $files = TRUE;
  843. $filepath = $item['data'];
  844. if (!in_array($filepath, $parsed)) {
  845. // Don't parse our own translations files.
  846. if (substr($filepath, 0, strlen($dir)) != $dir) {
  847. _locale_parse_js_file($filepath);
  848. $parsed[] = $filepath;
  849. $new_files = TRUE;
  850. }
  851. }
  852. }
  853. }
  854. // If there are any new source files we parsed, invalidate existing
  855. // JavaScript translation files for all languages, adding the refresh
  856. // flags into the existing array.
  857. if ($new_files) {
  858. $parsed += _locale_invalidate_js();
  859. }
  860. // If necessary, rebuild the translation file for the current language.
  861. if (!empty($parsed['refresh:' . $language->language])) {
  862. // Don't clear the refresh flag on failure, so that another try will
  863. // be performed later.
  864. if (_locale_rebuild_js()) {
  865. unset($parsed['refresh:' . $language->language]);
  866. }
  867. // Store any changes after refresh was attempted.
  868. variable_set('javascript_parsed', $parsed);
  869. }
  870. // If no refresh was attempted, but we have new source files, we need
  871. // to store them too. This occurs if current page is in English.
  872. elseif ($new_files) {
  873. variable_set('javascript_parsed', $parsed);
  874. }
  875. // Add the translation JavaScript file to the page.
  876. if ($files && !empty($language->javascript)) {
  877. // Add the translation JavaScript file to the page.
  878. $file = $dir . '/' . $language->language . '_' . $language->javascript . '.js';
  879. $javascript[$file] = drupal_js_defaults($file);
  880. }
  881. }
  882. /**
  883. * Implements hook_css_alter().
  884. *
  885. * This function checks all CSS files currently added via drupal_add_css() and
  886. * and checks to see if a related right to left CSS file should be included.
  887. */
  888. function locale_css_alter(&$css) {
  889. global $language;
  890. // If the current language is RTL, add the CSS file with the RTL overrides.
  891. if ($language->direction == LANGUAGE_RTL) {
  892. foreach ($css as $data => $item) {
  893. // Only provide RTL overrides for files.
  894. if ($item['type'] == 'file') {
  895. $rtl_path = str_replace('.css', '-rtl.css', $item['data']);
  896. if (file_exists($rtl_path) && !isset($css[$rtl_path])) {
  897. // Replicate the same item, but with the RTL path and a little larger
  898. // weight so that it appears directly after the original CSS file.
  899. $item['data'] = $rtl_path;
  900. $item['weight'] += 0.01;
  901. $css[$rtl_path] = $item;
  902. }
  903. }
  904. }
  905. }
  906. }
  907. /**
  908. * Implement hook_library_alter().
  909. *
  910. * Provides the language support for the jQuery UI Date Picker.
  911. */
  912. function locale_library_alter(&$libraries, $module) {
  913. if ($module == 'system' && isset($libraries['ui.datepicker'])) {
  914. global $language;
  915. // locale.datepicker.js should be added in the JS_LIBRARY group, so that
  916. // this attach behavior will execute early. JS_LIBRARY is the default for
  917. // hook_library_info_alter(), thus does not have to be specified explicitly.
  918. $datepicker = drupal_get_path('module', 'locale') . '/locale.datepicker.js';
  919. $libraries['ui.datepicker']['js'][$datepicker] = array();
  920. $libraries['ui.datepicker']['js'][] = array(
  921. 'data' => array(
  922. 'jquery' => array(
  923. 'ui' => array(
  924. 'datepicker' => array(
  925. 'isRTL' => $language->direction == LANGUAGE_RTL,
  926. 'firstDay' => variable_get('date_first_day', 0),
  927. ),
  928. ),
  929. ),
  930. ),
  931. 'type' => 'setting',
  932. );
  933. }
  934. }
  935. // ---------------------------------------------------------------------------------
  936. // Language switcher block
  937. /**
  938. * Implements hook_block_info().
  939. */
  940. function locale_block_info() {
  941. include_once DRUPAL_ROOT . '/includes/language.inc';
  942. $block = array();
  943. $info = language_types_info();
  944. foreach (language_types_configurable(FALSE) as $type) {
  945. $block[$type] = array(
  946. 'info' => t('Language switcher (@type)', array('@type' => $info[$type]['name'])),
  947. // Not worth caching.
  948. 'cache' => DRUPAL_NO_CACHE,
  949. );
  950. }
  951. return $block;
  952. }
  953. /**
  954. * Implements hook_block_view().
  955. *
  956. * Displays a language switcher. Only show if we have at least two languages.
  957. */
  958. function locale_block_view($type) {
  959. if (drupal_multilingual()) {
  960. $path = drupal_is_front_page() ? '<front>' : $_GET['q'];
  961. $links = language_negotiation_get_switch_links($type, $path);
  962. if (isset($links->links)) {
  963. drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
  964. $class = "language-switcher-{$links->provider}";
  965. $variables = array('links' => $links->links, 'attributes' => array('class' => array($class)));
  966. $block['content'] = theme('links__locale_block', $variables);
  967. $block['subject'] = t('Languages');
  968. return $block;
  969. }
  970. }
  971. }
  972. /**
  973. * Implements hook_url_outbound_alter().
  974. *
  975. * Rewrite outbound URLs with language based prefixes.
  976. */
  977. function locale_url_outbound_alter(&$path, &$options, $original_path) {
  978. // Only modify internal URLs.
  979. if (!$options['external'] && drupal_multilingual()) {
  980. static $drupal_static_fast;
  981. if (!isset($drupal_static_fast)) {
  982. $drupal_static_fast['callbacks'] = &drupal_static(__FUNCTION__);
  983. }
  984. $callbacks = &$drupal_static_fast['callbacks'];
  985. if (!isset($callbacks)) {
  986. $callbacks = array();
  987. include_once DRUPAL_ROOT . '/includes/language.inc';
  988. foreach (language_types_configurable() as $type) {
  989. // Get URL rewriter callbacks only from enabled language providers.
  990. $negotiation = variable_get("language_negotiation_$type", array());
  991. foreach ($negotiation as $id => $provider) {
  992. if (isset($provider['callbacks']['url_rewrite'])) {
  993. if (isset($provider['file'])) {
  994. require_once DRUPAL_ROOT . '/' . $provider['file'];
  995. }
  996. // Avoid duplicate callback entries.
  997. $callbacks[$provider['callbacks']['url_rewrite']] = TRUE;
  998. }
  999. }
  1000. }
  1001. $callbacks = array_keys($callbacks);
  1002. }
  1003. foreach ($callbacks as $callback) {
  1004. $callback($path, $options);
  1005. }
  1006. // No language dependent path allowed in this mode.
  1007. if (empty($callbacks)) {
  1008. unset($options['language']);
  1009. }
  1010. }
  1011. }