Projet

Général

Profil

Paste
Télécharger (45,2 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / locale / locale.module @ 01dfd3b5

1
<?php
2

    
3
/**
4
 * @file
5
 *   Add language handling functionality and enables the translation of the
6
 *   user interface to languages other than English.
7
 *
8
 *   When enabled, multiple languages can be set up. The site interface
9
 *   can be displayed in different languages, as well as nodes can have languages
10
 *   assigned. The setup of languages and translations is completely web based.
11
 *   Gettext portable object files are supported.
12
 */
13

    
14
// ---------------------------------------------------------------------------------
15
// Hook implementations
16

    
17
/**
18
 * Implements hook_help().
19
 */
20
function locale_help($path, $arg) {
21
  switch ($path) {
22
    case 'admin/help#locale':
23
      $output = '';
24
      $output .= '<h3>' . t('About') . '</h3>';
25
      $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>';
26
      $output .= '<h3>' . t('Uses') . '</h3>';
27
      $output .= '<dl>';
28
      $output .= '<dt>' . t('Translating interface text') . '</dt>';
29
      $output .= '<dd>' . t('Translations of text in the Drupal interface may be provided by:');
30
      $output .= '<ul>';
31
      $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>';
32
      $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>';
33
      $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>';
34
      $output .= '</ul></dd>';
35
      $output .= '<dt>' . t('Configuring a multilingual site') . '</dt>';
36
      $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>';
37
      $output .= '</dl>';
38
      return $output;
39
    case 'admin/config/regional/language':
40
      $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>';
41
      return $output;
42
    case 'admin/config/regional/language/add':
43
      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>';
44
    case 'admin/config/regional/language/configure':
45
      $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>';
46
      return $output;
47
    case 'admin/config/regional/language/configure/session':
48
      $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>';
49
      return $output;
50
    case 'admin/config/regional/translate':
51
      $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>';
52
      $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>';
53
      return $output;
54
    case 'admin/config/regional/translate/import':
55
      $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>';
56
      $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>';
57
      return $output;
58
    case 'admin/config/regional/translate/export':
59
      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>';
60
    case 'admin/config/regional/translate/translate':
61
      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>';
62
    case 'admin/structure/block/manage/%/%':
63
      if ($arg[4] == 'locale' && $arg[5] == 'language') {
64
        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>';
65
      }
66
      break;
67
  }
68
}
69

    
70
/**
71
 * Implements hook_menu().
72
 */
73
function locale_menu() {
74
  // Manage languages
75
  $items['admin/config/regional/language'] = array(
76
    'title' => 'Languages',
77
    'description' => 'Configure languages for content and the user interface.',
78
    'page callback' => 'drupal_get_form',
79
    'page arguments' => array('locale_languages_overview_form'),
80
    'access arguments' => array('administer languages'),
81
    'file' => 'locale.admin.inc',
82
    'weight' => -10,
83
  );
84
  $items['admin/config/regional/language/overview'] = array(
85
    'title' => 'List',
86
    'weight' => 0,
87
    'type' => MENU_DEFAULT_LOCAL_TASK,
88
  );
89
  $items['admin/config/regional/language/add'] = array(
90
    'title' => 'Add language',
91
    'page callback' => 'locale_languages_add_screen', // two forms concatenated
92
    'access arguments' => array('administer languages'),
93
    'weight' => 5,
94
    'type' => MENU_LOCAL_ACTION,
95
    'file' => 'locale.admin.inc',
96
  );
97
  $items['admin/config/regional/language/configure'] = array(
98
    'title' => 'Detection and selection',
99
    'page callback' => 'drupal_get_form',
100
    'page arguments' => array('locale_languages_configure_form'),
101
    'access arguments' => array('administer languages'),
102
    'weight' => 10,
103
    'file' => 'locale.admin.inc',
104
    'type' => MENU_LOCAL_TASK,
105
  );
106
  $items['admin/config/regional/language/configure/url'] = array(
107
    'title' => 'URL language detection configuration',
108
    'page callback' => 'drupal_get_form',
109
    'page arguments' => array('locale_language_providers_url_form'),
110
    'access arguments' => array('administer languages'),
111
    'file' => 'locale.admin.inc',
112
    'type' => MENU_VISIBLE_IN_BREADCRUMB,
113
  );
114
  $items['admin/config/regional/language/configure/session'] = array(
115
    'title' => 'Session language detection configuration',
116
    'page callback' => 'drupal_get_form',
117
    'page arguments' => array('locale_language_providers_session_form'),
118
    'access arguments' => array('administer languages'),
119
    'file' => 'locale.admin.inc',
120
    'type' => MENU_VISIBLE_IN_BREADCRUMB,
121
  );
122
  $items['admin/config/regional/language/edit/%'] = array(
123
    'title' => 'Edit language',
124
    'page callback' => 'drupal_get_form',
125
    'page arguments' => array('locale_languages_edit_form', 5),
126
    'access arguments' => array('administer languages'),
127
    'file' => 'locale.admin.inc',
128
  );
129
  $items['admin/config/regional/language/delete/%'] = array(
130
    'title' => 'Confirm',
131
    'page callback' => 'drupal_get_form',
132
    'page arguments' => array('locale_languages_delete_form', 5),
133
    'access arguments' => array('administer languages'),
134
    'file' => 'locale.admin.inc',
135
  );
136

    
137
  // Translation functionality
138
  $items['admin/config/regional/translate'] = array(
139
    'title' => 'Translate interface',
140
    'description' => 'Translate the built in interface and optionally other text.',
141
    'page callback' => 'locale_translate_overview_screen',
142
    'access arguments' => array('translate interface'),
143
    'file' => 'locale.admin.inc',
144
    'weight' => -5,
145
  );
146
  $items['admin/config/regional/translate/overview'] = array(
147
    'title' => 'Overview',
148
    'weight' => 0,
149
    'type' => MENU_DEFAULT_LOCAL_TASK,
150
  );
151
  $items['admin/config/regional/translate/translate'] = array(
152
    'title' => 'Translate',
153
    'weight' => 10,
154
    'type' => MENU_LOCAL_TASK,
155
    'page callback' => 'locale_translate_seek_screen', // search results and form concatenated
156
    'access arguments' => array('translate interface'),
157
    'file' => 'locale.admin.inc',
158
  );
159
  $items['admin/config/regional/translate/import'] = array(
160
    'title' => 'Import',
161
    'page callback' => 'drupal_get_form',
162
    'page arguments' => array('locale_translate_import_form'),
163
    'access arguments' => array('translate interface'),
164
    'weight' => 20,
165
    'type' => MENU_LOCAL_TASK,
166
    'file' => 'locale.admin.inc',
167
  );
168
  $items['admin/config/regional/translate/export'] = array(
169
    'title' => 'Export',
170
    'page callback' => 'locale_translate_export_screen',  // possibly multiple forms concatenated
171
    'access arguments' => array('translate interface'),
172
    'weight' => 30,
173
    'type' => MENU_LOCAL_TASK,
174
    'file' => 'locale.admin.inc',
175
  );
176
  $items['admin/config/regional/translate/edit/%'] = array(
177
    'title' => 'Edit string',
178
    'page callback' => 'drupal_get_form',
179
    'page arguments' => array('locale_translate_edit_form', 5),
180
    'access arguments' => array('translate interface'),
181
    'file' => 'locale.admin.inc',
182
  );
183
  $items['admin/config/regional/translate/delete/%'] = array(
184
    'title' => 'Delete string',
185
    'page callback' => 'locale_translate_delete_page',
186
    'page arguments' => array(5),
187
    'access arguments' => array('translate interface'),
188
    'file' => 'locale.admin.inc',
189
  );
190

    
191
  // Localize date formats.
192
  $items['admin/config/regional/date-time/locale'] = array(
193
    'title' => 'Localize',
194
    'description' => 'Configure date formats for each locale',
195
    'page callback' => 'locale_date_format_language_overview_page',
196
    'access arguments' => array('administer site configuration'),
197
    'type' => MENU_LOCAL_TASK,
198
    'weight' => -8,
199
    'file' => 'locale.admin.inc',
200
  );
201
  $items['admin/config/regional/date-time/locale/%/edit'] = array(
202
    'title' => 'Localize date formats',
203
    'description' => 'Configure date formats for each locale',
204
    'page callback' => 'drupal_get_form',
205
    'page arguments' => array('locale_date_format_form', 5),
206
    'access arguments' => array('administer site configuration'),
207
    'file' => 'locale.admin.inc',
208
  );
209
  $items['admin/config/regional/date-time/locale/%/reset'] = array(
210
    'title' => 'Reset date formats',
211
    'description' => 'Reset localized date formats to global defaults',
212
    'page callback' => 'drupal_get_form',
213
    'page arguments' => array('locale_date_format_reset_form', 5),
214
    'access arguments' => array('administer site configuration'),
215
    'file' => 'locale.admin.inc',
216
  );
217

    
218
  return $items;
219
}
220

    
221
/**
222
 * Implements hook_init().
223
 *
224
 * Initialize date formats according to the user's current locale.
225
 */
226
function locale_init() {
227
  global $conf, $language;
228
  include_once DRUPAL_ROOT . '/includes/locale.inc';
229

    
230
  // For each date type (e.g. long, short), get the localized date format
231
  // for the user's current language and override the default setting for it
232
  // in $conf. This should happen on all pages except the date and time formats
233
  // settings page, where we want to display the site default and not the
234
  // localized version.
235
  if (strpos($_GET['q'], 'admin/config/regional/date-time/formats') !== 0) {
236
    $languages = array($language->language);
237

    
238
    // Setup appropriate date formats for this locale.
239
    $formats = locale_get_localized_date_format($languages);
240
    foreach ($formats as $format_type => $format) {
241
      $conf[$format_type] = $format;
242
    }
243
  }
244
}
245

    
246
/**
247
 * Implements hook_permission().
248
 */
249
function locale_permission() {
250
  return array(
251
    'administer languages' => array(
252
      'title' => t('Administer languages'),
253
    ),
254
    'translate interface' => array(
255
      'title' => t('Translate interface texts'),
256
      'restrict access' => TRUE,
257
    ),
258
  );
259
}
260

    
261
/**
262
 * Implements hook_locale().
263
 */
264
function locale_locale($op = 'groups') {
265
  switch ($op) {
266
    case 'groups':
267
      return array('default' => t('Built-in interface'));
268
  }
269
}
270

    
271
/**
272
 * Form builder callback to display language selection widget.
273
 *
274
 * @ingroup forms
275
 * @see locale_form_alter()
276
 */
277
function locale_language_selector_form(&$form, &$form_state, $user) {
278
  global $language;
279
  $languages = language_list('enabled');
280
  $languages = $languages[1];
281

    
282
  // If the user is being created, we set the user language to the page language.
283
  $user_preferred_language = $user->uid ? user_preferred_language($user) : $language;
284

    
285
  $names = array();
286
  foreach ($languages as $langcode => $item) {
287
    $name = t($item->name);
288
    $names[$langcode] = $name . ($item->native != $name ? ' (' . $item->native . ')' : '');
289
  }
290
  $form['locale'] = array(
291
    '#type' => 'fieldset',
292
    '#title' => t('Language settings'),
293
    '#weight' => 1,
294
    '#access' => ($form['#user_category'] == 'account' || ($form['#user_category'] == 'register' && user_access('administer users'))),
295
  );
296

    
297
  // Get language negotiation settings.
298
  $mode = language_negotiation_get(LANGUAGE_TYPE_INTERFACE) != LANGUAGE_NEGOTIATION_DEFAULT;
299
  $form['locale']['language'] = array(
300
    '#type' => (count($names) <= 5 ? 'radios' : 'select'),
301
    '#title' => t('Language'),
302
    '#default_value' => $user_preferred_language->language,
303
    '#options' => $names,
304
    '#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."),
305
  );
306
}
307

    
308
/**
309
 * Implements hook_form_FORM_ID_alter().
310
 */
311
function locale_form_path_admin_form_alter(&$form, &$form_state) {
312
  $form['language'] = array(
313
    '#type' => 'select',
314
    '#title' => t('Language'),
315
    '#options' => array(LANGUAGE_NONE => t('All languages')) + locale_language_list('name'),
316
    '#default_value' => $form['language']['#value'],
317
    '#weight' => -10,
318
    '#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>.'),
319
  );
320
}
321

    
322
/**
323
 * Implements hook_form_FORM_ID_alter().
324
 */
325
function locale_form_node_type_form_alter(&$form, &$form_state) {
326
  if (isset($form['type'])) {
327
    $form['workflow']['language_content_type'] = array(
328
      '#type' => 'radios',
329
      '#title' => t('Multilingual support'),
330
      '#default_value' => variable_get('language_content_type_' . $form['#node_type']->type, 0),
331
      '#options' => array(t('Disabled'), t('Enabled')),
332
      '#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'))),
333
    );
334
  }
335
}
336

    
337
/**
338
 * Return whether the given content type has multilingual support.
339
 *
340
 * @return
341
 *   True if multilingual support is enabled.
342
 */
343
function locale_multilingual_node_type($type_name) {
344
  return (bool) variable_get('language_content_type_' . $type_name, 0);
345
}
346

    
347
/**
348
 * Implements hook_form_alter().
349
 *
350
 * Adds language fields to user forms.
351
 */
352
function locale_form_alter(&$form, &$form_state, $form_id) {
353
  // Only alter user forms if there is more than one language.
354
  if (drupal_multilingual()) {
355
    // Display language selector when either creating a user on the admin
356
    // interface or editing a user account.
357
    if ($form_id == 'user_register_form' || ($form_id == 'user_profile_form' && $form['#user_category'] == 'account')) {
358
      locale_language_selector_form($form, $form_state, $form['#user']);
359
    }
360
  }
361
}
362

    
363
/**
364
 * Implements hook_form_BASE_FORM_ID_alter().
365
 */
366
function locale_form_node_form_alter(&$form, &$form_state) {
367
  if (isset($form['#node']->type) && locale_multilingual_node_type($form['#node']->type)) {
368
    $form['language'] = array(
369
      '#type' => 'select',
370
      '#title' => t('Language'),
371
      '#default_value' => (isset($form['#node']->language) ? $form['#node']->language : ''),
372
      '#options' => array(LANGUAGE_NONE => t('Language neutral')) + locale_language_list('name'),
373
    );
374
  }
375
  // Node type without language selector: assign the default for new nodes
376
  elseif (!isset($form['#node']->nid)) {
377
    $default = language_default();
378
    $form['language'] = array(
379
      '#type' => 'value',
380
      '#value' => $default->language
381
    );
382
  }
383
  $form['#submit'][] = 'locale_field_node_form_submit';
384
}
385

    
386
/**
387
 * Form submit handler for node_form().
388
 *
389
 * This submit handler needs to run before entity_form_submit_build_entity()
390
 * is invoked by node_form_submit_build_node(), because it alters the values of
391
 * attached fields. Therefore, it cannot be a hook_node_submit() implementation.
392
 */
393
function locale_field_node_form_submit($form, &$form_state) {
394
  locale_field_entity_form_submit('node', $form, $form_state);
395
}
396

    
397
/**
398
 * Implements hook_form_FORM_ID_alter().
399
 */
400
function locale_form_comment_form_alter(&$form, &$form_state, $form_id) {
401
  // If a content type has multilingual support we set the content language as
402
  // comment language.
403
  if ($form['language']['#value'] == LANGUAGE_NONE && locale_multilingual_node_type($form['#node']->type)) {
404
    global $language_content;
405
    $form['language']['#value'] = $language_content->language;
406
    $submit_callback = 'locale_field_comment_form_submit';
407
    array_unshift($form['actions']['preview']['#submit'], $submit_callback);
408
    array_unshift($form['#submit'], $submit_callback);
409
  }
410
}
411

    
412
/**
413
 * Form submit handler for comment_form().
414
 *
415
 * This submit handler needs to run before entity_form_submit_build_entity()
416
 * is invoked by comment_form_submit_build_comment(), because it alters the
417
 * values of attached fields.
418
 */
419
function locale_field_comment_form_submit($form, &$form_state) {
420
  locale_field_entity_form_submit('comment', $form, $form_state);
421
}
422

    
423
/**
424
 * Handles field language on submit for the given entity type.
425
 *
426
 * Checks if Locale is registered as a translation handler and handle possible
427
 * language changes.
428
 */
429
function locale_field_entity_form_submit($entity_type, $form, &$form_state ) {
430
  if (field_has_translation_handler($entity_type, 'locale')) {
431
    $entity = (object) $form_state['values'];
432
    $current_language = entity_language($entity_type, $entity);
433
    list(, , $bundle) = entity_extract_ids($entity_type, $entity);
434

    
435
    foreach (field_info_instances($entity_type, $bundle) as $instance) {
436
      $field_name = $instance['field_name'];
437
      $field = field_info_field($field_name);
438
      $previous_language = $form[$field_name]['#language'];
439

    
440
      // Handle a possible language change: new language values are inserted,
441
      // previous ones are deleted.
442
      if ($field['translatable'] && $previous_language != $current_language) {
443
        $form_state['values'][$field_name][$current_language] = $entity->{$field_name}[$previous_language];
444
        $form_state['values'][$field_name][$previous_language] = array();
445
      }
446
    }
447
  }
448
}
449

    
450
/**
451
 * Implements hook_theme().
452
 */
453
function locale_theme() {
454
  return array(
455
    'locale_languages_overview_form' => array(
456
      'render element' => 'form',
457
    ),
458
    'locale_languages_configure_form' => array(
459
      'render element' => 'form',
460
    ),
461
    'locale_date_format_form' => array(
462
      'render element' => 'form',
463
    ),
464
  );
465
}
466

    
467
/**
468
 * Implements hook_field_language_alter().
469
 */
470
function locale_field_language_alter(&$display_language, $context) {
471
  // Do not apply core language fallback rules if they are disabled or if Locale
472
  // is not registered as a translation handler.
473
  if (variable_get('locale_field_language_fallback', TRUE) && field_has_translation_handler($context['entity_type'], 'locale')) {
474
    locale_field_language_fallback($display_language, $context['entity'], $context['language']);
475
  }
476
}
477

    
478
/**
479
 * Applies language fallback rules to the fields attached to the given entity.
480
 *
481
 * Core language fallback rules simply check if fields have a field translation
482
 * for the requested language code. If so the requested language is returned,
483
 * otherwise all the fallback candidates are inspected to see if there is a
484
 * field translation available in another language.
485
 * By default this is called by locale_field_language_alter(), but this
486
 * behavior can be disabled by setting the 'locale_field_language_fallback'
487
 * variable to FALSE.
488
 *
489
 * @param $display_language
490
 *   A reference to an array of language codes keyed by field name.
491
 * @param $entity
492
 *   The entity to be displayed.
493
 * @param $langcode
494
 *   The language code $entity has to be displayed in.
495
 */
496
function locale_field_language_fallback(&$display_language, $entity, $langcode) {
497
  // Lazily init fallback candidates to avoid unnecessary calls.
498
  $fallback_candidates = NULL;
499
  $field_languages = array();
500

    
501
  foreach ($display_language as $field_name => $field_language) {
502
    // If the requested language is defined for the current field use it,
503
    // otherwise search for a fallback value among the fallback candidates.
504
    if (isset($entity->{$field_name}[$langcode])) {
505
      $display_language[$field_name] = $langcode;
506
    }
507
    elseif (!empty($entity->{$field_name})) {
508
      if (!isset($fallback_candidates)) {
509
        require_once DRUPAL_ROOT . '/includes/language.inc';
510
        $fallback_candidates = language_fallback_get_candidates();
511
      }
512
      foreach ($fallback_candidates as $fallback_language) {
513
        if (isset($entity->{$field_name}[$fallback_language])) {
514
          $display_language[$field_name] = $fallback_language;
515
          break;
516
        }
517
      }
518
    }
519
  }
520
}
521

    
522
/**
523
 * Implements hook_entity_info_alter().
524
 */
525
function locale_entity_info_alter(&$entity_info) {
526
  $entity_info['node']['translation']['locale'] = TRUE;
527
  if (isset($entity_info['comment'])) {
528
    $entity_info['comment']['translation']['locale'] = TRUE;
529
  }
530
}
531

    
532
/**
533
 * Implements hook_language_types_info().
534
 *
535
 * Defines the three core language types:
536
 * - Interface language is the only configurable language type in core. It is
537
 *   used by t() as the default language if none is specified.
538
 * - Content language is by default non-configurable and inherits the interface
539
 *   language negotiated value. It is used by the Field API to determine the
540
 *   display language for fields if no explicit value is specified.
541
 * - URL language is by default non-configurable and is determined through the
542
 *   URL language provider or the URL fallback provider if no language can be
543
 *   detected. It is used by l() as the default language if none is specified.
544
 */
545
function locale_language_types_info() {
546
  require_once DRUPAL_ROOT . '/includes/locale.inc';
547
  return array(
548
    LANGUAGE_TYPE_INTERFACE => array(
549
      'name' => t('User interface text'),
550
      '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.'),
551
    ),
552
    LANGUAGE_TYPE_CONTENT => array(
553
      'name' => t('Content'),
554
      'description' => t('Order of language detection methods for content. If a version of content is available in the detected language, it will be displayed.'),
555
      'fixed' => array(LOCALE_LANGUAGE_NEGOTIATION_INTERFACE),
556
    ),
557
    LANGUAGE_TYPE_URL => array(
558
      'fixed' => array(LOCALE_LANGUAGE_NEGOTIATION_URL, LOCALE_LANGUAGE_NEGOTIATION_URL_FALLBACK),
559
    ),
560
  );
561
}
562

    
563
/**
564
 * Implements hook_language_negotiation_info().
565
 */
566
function locale_language_negotiation_info() {
567
  require_once DRUPAL_ROOT . '/includes/locale.inc';
568
  $file = 'includes/locale.inc';
569
  $providers = array();
570

    
571
  $providers[LOCALE_LANGUAGE_NEGOTIATION_URL] = array(
572
    'types' => array(LANGUAGE_TYPE_CONTENT, LANGUAGE_TYPE_INTERFACE, LANGUAGE_TYPE_URL),
573
    'callbacks' => array(
574
      'language' => 'locale_language_from_url',
575
      'switcher' => 'locale_language_switcher_url',
576
      'url_rewrite' => 'locale_language_url_rewrite_url',
577
    ),
578
    'file' => $file,
579
    'weight' => -8,
580
    'name' => t('URL'),
581
    'description' => t('Determine the language from the URL (Path prefix or domain).'),
582
    'config' => 'admin/config/regional/language/configure/url',
583
  );
584

    
585
  $providers[LOCALE_LANGUAGE_NEGOTIATION_SESSION] = array(
586
    'callbacks' => array(
587
      'language' => 'locale_language_from_session',
588
      'switcher' => 'locale_language_switcher_session',
589
      'url_rewrite' => 'locale_language_url_rewrite_session',
590
    ),
591
    'file' => $file,
592
    'weight' => -6,
593
    'name' => t('Session'),
594
    'description' => t('Determine the language from a request/session parameter.'),
595
    'config' => 'admin/config/regional/language/configure/session',
596
  );
597

    
598
  $providers[LOCALE_LANGUAGE_NEGOTIATION_USER] = array(
599
    'callbacks' => array('language' => 'locale_language_from_user'),
600
    'file' => $file,
601
    'weight' => -4,
602
    'name' => t('User'),
603
    'description' => t("Follow the user's language preference."),
604
  );
605

    
606
  $providers[LOCALE_LANGUAGE_NEGOTIATION_BROWSER] = array(
607
    'callbacks' => array('language' => 'locale_language_from_browser'),
608
    'file' => $file,
609
    'weight' => -2,
610
    'cache' => 0,
611
    'name' => t('Browser'),
612
    'description' => t("Determine the language from the browser's language settings."),
613
  );
614

    
615
  $providers[LOCALE_LANGUAGE_NEGOTIATION_INTERFACE] = array(
616
    'types' => array(LANGUAGE_TYPE_CONTENT),
617
    'callbacks' => array('language' => 'locale_language_from_interface'),
618
    'file' => $file,
619
    'weight' => 8,
620
    'name' => t('Interface'),
621
    'description' => t('Use the detected interface language.'),
622
  );
623

    
624
  $providers[LOCALE_LANGUAGE_NEGOTIATION_URL_FALLBACK] = array(
625
    'types' => array(LANGUAGE_TYPE_URL),
626
    'callbacks' => array('language' => 'locale_language_url_fallback'),
627
    'file' => $file,
628
    'weight' => 8,
629
    'name' => t('URL fallback'),
630
    'description' => t('Use an already detected language for URLs if none is found.'),
631
  );
632

    
633
  return $providers;
634
}
635

    
636
/**
637
 * Implements hook_modules_enabled().
638
 */
639
function locale_modules_enabled($modules) {
640
  include_once DRUPAL_ROOT . '/includes/language.inc';
641
  language_types_set();
642
  language_negotiation_purge();
643
}
644

    
645
/**
646
 * Implements hook_modules_disabled().
647
 */
648
function locale_modules_disabled($modules) {
649
  locale_modules_enabled($modules);
650
}
651

    
652
// ---------------------------------------------------------------------------------
653
// Locale core functionality
654

    
655
/**
656
 * Provides interface translation services.
657
 *
658
 * This function is called from t() to translate a string if needed.
659
 *
660
 * @param $string
661
 *   A string to look up translation for. If omitted, all the
662
 *   cached strings will be returned in all languages already
663
 *   used on the page.
664
 * @param $context
665
 *   The context of this string.
666
 * @param $langcode
667
 *   Language code to use for the lookup.
668
 */
669
function locale($string = NULL, $context = NULL, $langcode = NULL) {
670
  global $language;
671

    
672
  // Use the advanced drupal_static() pattern, since this is called very often.
673
  static $drupal_static_fast;
674
  if (!isset($drupal_static_fast)) {
675
    $drupal_static_fast['locale'] = &drupal_static(__FUNCTION__);
676
  }
677
  $locale_t = &$drupal_static_fast['locale'];
678

    
679

    
680
  if (!isset($string)) {
681
    // Return all cached strings if no string was specified
682
    return $locale_t;
683
  }
684

    
685
  $langcode = isset($langcode) ? $langcode : $language->language;
686

    
687
  // Store database cached translations in a static variable. Only build the
688
  // cache after $language has been set to avoid an unnecessary cache rebuild.
689
  if (!isset($locale_t[$langcode]) && isset($language)) {
690
    $locale_t[$langcode] = array();
691
    // Disabling the usage of string caching allows a module to watch for
692
    // the exact list of strings used on a page. From a performance
693
    // perspective that is a really bad idea, so we have no user
694
    // interface for this. Be careful when turning this option off!
695
    if (variable_get('locale_cache_strings', 1) == 1) {
696
      if ($cache = cache_get('locale:' . $langcode, 'cache')) {
697
        $locale_t[$langcode] = $cache->data;
698
      }
699
      elseif (lock_acquire('locale_cache_' . $langcode)) {
700
        // Refresh database stored cache of translations for given language.
701
        // We only store short strings used in current version, to improve
702
        // performance and consume less memory.
703
        $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)));
704
        foreach ($result as $data) {
705
          $locale_t[$langcode][$data->context][$data->source] = (empty($data->translation) ? TRUE : $data->translation);
706
        }
707
        cache_set('locale:' . $langcode, $locale_t[$langcode]);
708
        lock_release('locale_cache_' . $langcode);
709
      }
710
    }
711
  }
712

    
713
  // If we have the translation cached, skip checking the database
714
  if (!isset($locale_t[$langcode][$context][$string])) {
715

    
716
    // We do not have this translation cached, so get it from the DB.
717
    $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(
718
      ':language' => $langcode,
719
      ':source' => $string,
720
      ':context' => (string) $context,
721
    ))->fetchObject();
722
    if ($translation) {
723
      // We have the source string at least.
724
      // Cache translation string or TRUE if no translation exists.
725
      $locale_t[$langcode][$context][$string] = (empty($translation->translation) ? TRUE : $translation->translation);
726

    
727
      if ($translation->version != VERSION) {
728
        // This is the first use of this string under current Drupal version. Save version
729
        // and clear cache, to include the string into caching next time. Saved version is
730
        // also a string-history information for later pruning of the tables.
731
        db_update('locales_source')
732
          ->fields(array('version' => VERSION))
733
          ->condition('lid', $translation->lid)
734
          ->execute();
735
        cache_clear_all('locale:', 'cache', TRUE);
736
      }
737
    }
738
    else {
739
      // We don't have the source string, cache this as untranslated.
740
      db_merge('locales_source')
741
        ->insertFields(array(
742
          'location' => request_uri(),
743
          'version' => VERSION,
744
        ))
745
        ->key(array(
746
          'source' => $string,
747
          'context' => (string) $context,
748
          'textgroup' => 'default',
749
        ))
750
        ->execute();
751
      $locale_t[$langcode][$context][$string] = TRUE;
752
      // Clear locale cache so this string can be added in a later request.
753
      cache_clear_all('locale:', 'cache', TRUE);
754
    }
755
  }
756

    
757
  return ($locale_t[$langcode][$context][$string] === TRUE ? $string : $locale_t[$langcode][$context][$string]);
758
}
759

    
760
/**
761
 * Reset static variables used by locale().
762
 */
763
function locale_reset() {
764
  drupal_static_reset('locale');
765
}
766

    
767
/**
768
 * Returns plural form index for a specific number.
769
 *
770
 * The index is computed from the formula of this language.
771
 *
772
 * @param $count
773
 *   Number to return plural for.
774
 * @param $langcode
775
 *   Optional language code to translate to a language other than
776
 *   what is used to display the page.
777
 *
778
 * @return
779
 *   The numeric index of the plural variant to use for this $langcode and
780
 *   $count combination or -1 if the language was not found or does not have a
781
 *   plural formula.
782
 */
783
function locale_get_plural($count, $langcode = NULL) {
784
  global $language;
785

    
786
  // Used to locally cache the plural formulas for all languages.
787
  $plural_formulas = &drupal_static(__FUNCTION__, array());
788

    
789
  // Used to store precomputed plural indexes corresponding to numbers
790
  // individually for each language.
791
  $plural_indexes = &drupal_static(__FUNCTION__ . ':plurals', array());
792

    
793
  $langcode = $langcode ? $langcode : $language->language;
794

    
795
  if (!isset($plural_indexes[$langcode][$count])) {
796
    // Retrieve and statically cache the plural formulas for all languages.
797
    if (empty($plural_formulas)) {
798
      foreach (language_list() as $installed_language) {
799
        $plural_formulas[$installed_language->language] = $installed_language->formula;
800
      }
801
    }
802
    // If there is a plural formula for the language, evaluate it for the given
803
    // $count and statically cache the result for the combination of language
804
    // and count, since the result will always be identical.
805
    if (!empty($plural_formulas[$langcode])) {
806
      // $n is used inside the expression in the eval().
807
      $n = $count;
808
      $plural_indexes[$langcode][$count] = @eval('return intval(' . $plural_formulas[$langcode] . ');');
809
    }
810
    // In case there is no plural formula for English (no imported translation
811
    // for English), use a default formula.
812
    elseif ($langcode == 'en') {
813
      $plural_indexes[$langcode][$count] = (int) ($count != 1);
814
    }
815
    // Otherwise, return -1 (unknown).
816
    else {
817
      $plural_indexes[$langcode][$count] = -1;
818
    }
819
  }
820
  return $plural_indexes[$langcode][$count];
821
}
822

    
823

    
824
/**
825
 * Returns a language name
826
 */
827
function locale_language_name($lang) {
828
  $list = &drupal_static(__FUNCTION__);
829
  if (!isset($list)) {
830
    $list = locale_language_list();
831
  }
832
  return ($lang && isset($list[$lang])) ? $list[$lang] : t('All');
833
}
834

    
835
/**
836
 * Returns array of language names
837
 *
838
 * @param $field
839
 *   'name' => names in current language, localized
840
 *   'native' => native names
841
 * @param $all
842
 *   Boolean to return all languages or only enabled ones
843
 */
844
function locale_language_list($field = 'name', $all = FALSE) {
845
  if ($all) {
846
    $languages = language_list();
847
  }
848
  else {
849
    $languages = language_list('enabled');
850
    $languages = $languages[1];
851
  }
852
  $list = array();
853
  foreach ($languages as $language) {
854
    $list[$language->language] = ($field == 'name') ? t($language->name) : $language->$field;
855
  }
856
  return $list;
857
}
858

    
859
/**
860
 * Implements hook_modules_installed().
861
 */
862
function locale_modules_installed($modules) {
863
  locale_system_update($modules);
864
}
865

    
866
/**
867
 * Implements hook_themes_enabled().
868
 *
869
 * @todo This is technically wrong. We must not import upon enabling, but upon
870
 *   initial installation. The theme system is missing an installation hook.
871
 */
872
function locale_themes_enabled($themes) {
873
  locale_system_update($themes);
874
}
875

    
876
/**
877
 * Imports translations when new modules or themes are installed.
878
 *
879
 * This function will either import translation for the component change
880
 * right away, or start a batch if more files need to be imported.
881
 *
882
 * @param $components
883
 *   An array of component (theme and/or module) names to import
884
 *   translations for.
885
 */
886
function locale_system_update($components) {
887
  include_once DRUPAL_ROOT . '/includes/locale.inc';
888
  if ($batch = locale_batch_by_component($components)) {
889
    batch_set($batch);
890
  }
891
}
892

    
893
/**
894
 * Implements hook_js_alter().
895
 *
896
 * This function checks all JavaScript files currently added via drupal_add_js()
897
 * and invokes parsing if they have not yet been parsed for Drupal.t()
898
 * and Drupal.formatPlural() calls. Also refreshes the JavaScript translation
899
 * file if necessary, and adds it to the page.
900
 */
901
function locale_js_alter(&$javascript) {
902
  global $language;
903

    
904
  $dir = 'public://' . variable_get('locale_js_directory', 'languages');
905
  $parsed = variable_get('javascript_parsed', array());
906
  $files = $new_files = FALSE;
907

    
908
  // Require because locale_js_alter() could be called without locale_init().
909
  require_once DRUPAL_ROOT . '/includes/locale.inc';
910

    
911
  foreach ($javascript as $item) {
912
    if ($item['type'] == 'file') {
913
      $files = TRUE;
914
      $filepath = $item['data'];
915
      if (!in_array($filepath, $parsed)) {
916
        // Don't parse our own translations files.
917
        if (substr($filepath, 0, strlen($dir)) != $dir) {
918
          _locale_parse_js_file($filepath);
919
          $parsed[] = $filepath;
920
          $new_files = TRUE;
921
        }
922
      }
923
    }
924
  }
925

    
926
  // If there are any new source files we parsed, invalidate existing
927
  // JavaScript translation files for all languages, adding the refresh
928
  // flags into the existing array.
929
  if ($new_files) {
930
    $parsed += _locale_invalidate_js();
931
  }
932

    
933
  // If necessary, rebuild the translation file for the current language.
934
  if (!empty($parsed['refresh:' . $language->language])) {
935
    // Don't clear the refresh flag on failure, so that another try will
936
    // be performed later.
937
    if (_locale_rebuild_js()) {
938
      unset($parsed['refresh:' . $language->language]);
939
    }
940
    // Store any changes after refresh was attempted.
941
    variable_set('javascript_parsed', $parsed);
942
  }
943
  // If no refresh was attempted, but we have new source files, we need
944
  // to store them too. This occurs if current page is in English.
945
  elseif ($new_files) {
946
    variable_set('javascript_parsed', $parsed);
947
  }
948

    
949
  // Add the translation JavaScript file to the page.
950
  if ($files && !empty($language->javascript)) {
951
    // Add the translation JavaScript file to the page.
952
    $file = $dir . '/' . $language->language . '_' . $language->javascript . '.js';
953
    $javascript[$file] = drupal_js_defaults($file);
954
  }
955
}
956

    
957
/**
958
 * Implements hook_css_alter().
959
 *
960
 * This function checks all CSS files currently added via drupal_add_css() and
961
 * and checks to see if a related right to left CSS file should be included.
962
 */
963
function locale_css_alter(&$css) {
964
  global $language;
965

    
966
  // If the current language is RTL, add the CSS file with the RTL overrides.
967
  if ($language->direction == LANGUAGE_RTL) {
968
    foreach ($css as $data => $item) {
969
      // Only provide RTL overrides for files.
970
      if ($item['type'] == 'file') {
971
        $rtl_path = str_replace('.css', '-rtl.css', $item['data']);
972
        if (file_exists($rtl_path) && !isset($css[$rtl_path])) {
973
          // Replicate the same item, but with the RTL path and a little larger
974
          // weight so that it appears directly after the original CSS file.
975
          $item['data'] = $rtl_path;
976
          $item['weight'] += 0.0001;
977
          $css[$rtl_path] = $item;
978
        }
979
      }
980
    }
981
  }
982
}
983

    
984
 /**
985
 * Implement hook_library_alter().
986
 *
987
 * Provides the language support for the jQuery UI Date Picker.
988
 */
989
function locale_library_alter(&$libraries, $module) {
990
  if ($module == 'system' && isset($libraries['ui.datepicker'])) {
991
    global $language;
992
    // locale.datepicker.js should be added in the JS_LIBRARY group, so that
993
    // this attach behavior will execute early. JS_LIBRARY is the default for
994
    // hook_library_info_alter(), thus does not have to be specified explicitly.
995
    $datepicker = drupal_get_path('module', 'locale') . '/locale.datepicker.js';
996
    $libraries['ui.datepicker']['js'][$datepicker] = array();
997
    $libraries['ui.datepicker']['js'][] = array(
998
      'data' => array(
999
        'jquery' => array(
1000
          'ui' => array(
1001
            'datepicker' => array(
1002
              'isRTL' => $language->direction == LANGUAGE_RTL,
1003
              'firstDay' => variable_get('date_first_day', 0),
1004
            ),
1005
          ),
1006
        ),
1007
      ),
1008
      'type' => 'setting',
1009
    );
1010
  }
1011
}
1012

    
1013
// ---------------------------------------------------------------------------------
1014
// Language switcher block
1015

    
1016
/**
1017
 * Implements hook_block_info().
1018
 */
1019
function locale_block_info() {
1020
  include_once DRUPAL_ROOT . '/includes/language.inc';
1021
  $block = array();
1022
  $info = language_types_info();
1023
  foreach (language_types_configurable(FALSE) as $type) {
1024
    $block[$type] = array(
1025
      'info' => t('Language switcher (@type)', array('@type' => $info[$type]['name'])),
1026
      // Not worth caching.
1027
      'cache' => DRUPAL_NO_CACHE,
1028
    );
1029
  }
1030
  return $block;
1031
}
1032

    
1033
/**
1034
 * Implements hook_block_view().
1035
 *
1036
 * Displays a language switcher. Only show if we have at least two languages.
1037
 */
1038
function locale_block_view($type) {
1039
  if (drupal_multilingual()) {
1040
    $path = drupal_is_front_page() ? '<front>' : $_GET['q'];
1041
    $links = language_negotiation_get_switch_links($type, $path);
1042

    
1043
    if (isset($links->links)) {
1044
      drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
1045
      $class = "language-switcher-{$links->provider}";
1046
      $variables = array('links' => $links->links, 'attributes' => array('class' => array($class)));
1047
      $block['content'] = theme('links__locale_block', $variables);
1048
      $block['subject'] = t('Languages');
1049
      return $block;
1050
    }
1051
  }
1052
}
1053

    
1054
/**
1055
 * Implements hook_url_outbound_alter().
1056
 *
1057
 * Rewrite outbound URLs with language based prefixes.
1058
 */
1059
function locale_url_outbound_alter(&$path, &$options, $original_path) {
1060
  // Only modify internal URLs.
1061
  if (!$options['external'] && drupal_multilingual()) {
1062
    static $drupal_static_fast;
1063
    if (!isset($drupal_static_fast)) {
1064
      $drupal_static_fast['callbacks'] = &drupal_static(__FUNCTION__);
1065
    }
1066
    $callbacks = &$drupal_static_fast['callbacks'];
1067

    
1068
    if (!isset($callbacks)) {
1069
      $callbacks = array();
1070
      include_once DRUPAL_ROOT . '/includes/language.inc';
1071

    
1072
      foreach (language_types_configurable() as $type) {
1073
        // Get URL rewriter callbacks only from enabled language providers.
1074
        $negotiation = variable_get("language_negotiation_$type", array());
1075

    
1076
        foreach ($negotiation as $id => $provider) {
1077
          if (isset($provider['callbacks']['url_rewrite'])) {
1078
            if (isset($provider['file'])) {
1079
              require_once DRUPAL_ROOT . '/' . $provider['file'];
1080
            }
1081
            // Avoid duplicate callback entries.
1082
            $callbacks[$provider['callbacks']['url_rewrite']] = TRUE;
1083
          }
1084
        }
1085
      }
1086

    
1087
      $callbacks = array_keys($callbacks);
1088
    }
1089

    
1090
    foreach ($callbacks as $callback) {
1091
      $callback($path, $options);
1092
    }
1093

    
1094
    // No language dependent path allowed in this mode.
1095
    if (empty($callbacks)) {
1096
      unset($options['language']);
1097
    }
1098
  }
1099
}