Projet

Général

Profil

Paste
Télécharger (19 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / i18n / i18n_field / i18n_field.module @ e013fa40

1
<?php
2

    
3
/**
4
 * @file
5
 * Internationalization (i18n) module - Field handling
6
 *
7
 * For string keys we use:
8
 * - field:[field_name]:[bundle]:property, when it is an instance property (linked to bundle)
9
 * - field:[field_name]:#property..., when it is a field property (that may have multiple values)
10
 */
11

    
12
/**
13
 * Implements hook_menu().
14
 */
15
function i18n_field_menu() {
16
  $items = array();
17

    
18
  // Ensure the following is not executed until field_bundles is working and
19
  // tables are updated. Needed to avoid errors on initial installation.
20
  if (!module_exists('field_ui') || defined('MAINTENANCE_MODE')) {
21
    return $items;
22
  }
23

    
24
  // Create tabs for all possible bundles. From field_ui_menu().
25
  foreach (entity_get_info() as $entity_type => $entity_info) {
26
    if ($entity_info['fieldable']) {
27
      foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) {
28
        if (isset($bundle_info['admin'])) {
29
          // Extract path information from the bundle.
30
          $path = $bundle_info['admin']['path'];
31
          // Different bundles can appear on the same path (e.g. %node_type and
32
          // %comment_node_type). To allow field_ui_menu_load() to extract the
33
          // actual bundle object from the translated menu router path
34
          // arguments, we need to identify the argument position of the bundle
35
          // name string ('bundle argument') and pass that position to the menu
36
          // loader. The position needs to be casted into a string; otherwise it
37
          // would be replaced with the bundle name string.
38
          if (isset($bundle_info['admin']['bundle argument'])) {
39
            $bundle_arg = $bundle_info['admin']['bundle argument'];
40
            $bundle_pos = (string) $bundle_arg;
41
          }
42
          else {
43
            $bundle_arg = $bundle_name;
44
            $bundle_pos = '0';
45
          }
46
          // This is the position of the %field_ui_menu placeholder in the
47
          // items below.
48
          $field_position = count(explode('/', $path)) + 1;
49

    
50
          // Extract access information, providing defaults.
51
          $access = array_intersect_key($bundle_info['admin'], drupal_map_assoc(array('access callback', 'access arguments')));
52
          $access += array(
53
            'access callback' => 'user_access',
54
            'access arguments' => array('administer site configuration'),
55
          );
56
          $items["$path/fields/%field_ui_menu/translate"] = array(
57
            'load arguments' => array($entity_type, $bundle_arg, $bundle_pos, '%map'),
58
            'title' => 'Translate',
59
            'page callback' => 'i18n_field_page_translate',
60
            'page arguments' => array($field_position),
61
            'file' => 'i18n_field.pages.inc',
62
            'type' => MENU_LOCAL_TASK,
63
          ) + $access;
64

    
65
          $items["$path/fields/%field_ui_menu/translate/%i18n_language"] = array(
66
            'load arguments' => array($entity_type, $bundle_arg, $bundle_pos, '%map'),
67
            'title' => 'Instance',
68
            'page callback' => 'i18n_field_page_translate',
69
            'page arguments' => array($field_position, $field_position + 2),
70
            'file' => 'i18n_field.pages.inc',
71
            'type' => MENU_CALLBACK,
72
          ) + $access;
73
        }
74
      }
75
    }
76
  }
77
  return $items;
78
}
79

    
80
/**
81
 * Implements hook_hook_info().
82
 */
83
function i18n_field_hook_info() {
84
  $hooks['i18n_field_info'] = array(
85
    'group' => 'i18n',
86
  );
87
  return $hooks;
88
}
89

    
90
/**
91
 * Implements hook_field_attach_form().
92
 *
93
 * After the form fields are built. Translate title and description for fields with multiple values.
94
 */
95
function i18n_field_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
96
  // Determine the list of instances to iterate on.
97
  list(, , $bundle) = entity_extract_ids($entity_type, $entity);
98
  $instances = field_info_instances($entity_type, $bundle);
99
  foreach ($instances as $field_name => $instance) {
100
    if (isset($form[$field_name])) {
101
      $langcode = $form[$field_name]['#language'];
102
      $field = &$form[$field_name];
103
      // Note: cardinality for unlimited fields is -1
104
      if (isset($field[$langcode]['#cardinality']) && $field[$langcode]['#cardinality'] != 1) {
105
        $translated = i18n_string_object_translate('field_instance', $instance);
106
        if (!empty($field[$langcode]['#title'])) {
107
          $field[$langcode]['#title'] = $translated['label'];
108
        }
109
        if (!empty($field[$langcode]['#description'])) {
110
          $field[$langcode]['#description'] = $translated['description'];
111
        }
112
      }
113
    }
114
  }
115
}
116

    
117
/**
118
 * Implements hook_field_formatter_info().
119
 */
120
function i18n_field_field_formatter_info() {
121
  $types = array();
122
  foreach (i18n_field_type_info() as $type => $info) {
123
    if (!empty($info['translate_options'])) {
124
      $types[] = $type;
125
    }
126
  }
127
  return array(
128
    'i18n_list_default' => array(
129
      'label' => t('Default translated'),
130
      'field types' => $types,
131
    ),
132
  );
133
}
134

    
135
/**
136
 * Implements hook_field_formatter_view().
137
 */
138
function i18n_field_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
139
  $element = array();
140

    
141
  switch ($display['type']) {
142
    case 'i18n_list_default':
143
      if (($translate = i18n_field_type_info($field['type'], 'translate_options'))) {
144
        $allowed_values = $translate($field);
145
      }
146
      else {
147
        // Defaults to list_default behavior
148
        $allowed_values = list_allowed_values($field);
149
      }
150
      foreach ($items as $delta => $item) {
151
        if (isset($allowed_values[$item['value']])) {
152
          $output = field_filter_xss($allowed_values[$item['value']]);
153
        }
154
        else {
155
          // If no match was found in allowed values, fall back to the key.
156
          $output = field_filter_xss($item['value']);
157
        }
158
        $element[$delta] = array('#markup' => $output);
159
      }
160
      break;
161
  }
162

    
163
  return $element;
164
}
165

    
166
/**
167
 * Implements hook_field_widget_form_alter().
168
 *
169
 * Translate:
170
 * - Title (label)
171
 * - Description (help)
172
 * - Default value
173
 * - List options
174
 */
175
function i18n_field_field_widget_form_alter(&$element, &$form_state, $context) {
176
  global $language;
177

    
178
  // Don't translate if the widget is being shown on the field edit form.
179
  if ($form_state['build_info']['form_id'] == 'field_ui_field_edit_form') {
180
    return;
181
  }
182

    
183
  // Skip if we are missing any of the parameters
184
  if (empty($context['field']) || empty($context['instance']) || empty($context['langcode'])) {
185
    return;
186
  }
187
  $field = $context['field'];
188
  $instance = $context['instance'];
189
  $langcode = $context['langcode'];
190

    
191
  // Get the element to alter. Account for inconsistencies in how the element
192
  // is built for different field types.
193
  if (isset($element[0]) && count($element) == 1) {
194
    // Single-value file fields and image fields.
195
    $alter_element = &$element[0];
196
  }
197
  elseif (isset($element['value'])) {
198
    // Number fields. Single-value text fields.
199
    $alter_element = &$element['value'];
200
  }
201
  elseif ($field['type'] == 'entityreference' && isset($element['target_id'])) {
202
    // Entityreference fields using the entityreference_autocomplete widget.
203
    $alter_element = &$element['target_id'];
204
  }
205
  elseif ($field['type'] == 'node_reference' && isset($element['nid'])) {
206
    // The node_reference fields using the entityreference_autocomplete widget.
207
    $alter_element = &$element['nid'];
208
  }
209
  else {
210
    // All other fields.
211
    $alter_element = &$element;
212
  }
213

    
214
  // If a subelement has the same title as the parent, translate it instead.
215
  // Allows fields such as email and commerce_price to be translated.
216
  foreach (element_get_visible_children($element) as $key) {
217
    $single_value = ($field['cardinality'] == 1);
218
    $has_title = (isset($element['#title']) && isset($element[$key]['#title']));
219
    if ($single_value && $has_title && $element[$key]['#title'] == $element['#title']) {
220
      $alter_element = &$element[$key];
221
      break;
222
    }
223
  }
224

    
225
  // The field language may affect some variables (default) but not others (description will be in current page language)
226
  $i18n_langcode = empty($alter_element['#language']) || $alter_element['#language'] == LANGUAGE_NONE ? $language->language : $alter_element['#language'];
227

    
228
  // Translate instance to current page language and set to form_state
229
  // so it will be used for validation messages later.
230
  $instance_current = i18n_string_object_translate('field_instance', $instance);
231
  if (isset($form_state['field'][$instance['field_name']][$langcode]['instance'])) {
232
    $form_state['field'][$instance['field_name']][$langcode]['instance'] = $instance_current;
233
  }
234

    
235
  // Translate field title if set and it is the default one.
236
  if (!empty($instance_current['label']) && $instance_current['label'] != $instance['label']) {
237
    if (!empty($alter_element['#title']) && $alter_element['#title'] == check_plain($instance['label'])) {
238
      $alter_element['#title'] = check_plain($instance_current['label']);
239
    }
240
  }
241

    
242
  // Translate field description if set and it is the default one.
243
  if (!empty($instance_current['description']) && $instance_current['description'] != $instance['description']) {
244
    if (!empty($alter_element['#description'])) {
245
      // Allow single-value file fields and image fields to have their
246
      // descriptions translated. file_field_widget_form() passes the
247
      // description through theme('file_upload_help'), so i18n_field
248
      // must do the same.
249
      $filefield = in_array($field['type'], array('file', 'image'));
250
      $single_value = ($field['cardinality'] == 1);
251
      $no_default = empty($alter_element['#default_value']['fid']);
252
      if ($filefield && $single_value && $no_default) {
253
        $help_variables = array(
254
          'description' => field_filter_xss($instance['description']),
255
          'upload_validators' => isset($alter_element['#upload_validators']) ? $alter_element['#upload_validators'] : array(),
256
        );
257
        $original_description = theme('file_upload_help', $help_variables);
258
        if ($alter_element['#description'] == $original_description) {
259
          $help_variables = array(
260
            'description' => field_filter_xss($instance_current['description']),
261
            'upload_validators' => isset($alter_element['#upload_validators']) ? $alter_element['#upload_validators'] : array(),
262
          );
263
          $alter_element['#description'] = theme('file_upload_help', $help_variables);
264
        }
265
      }
266
      elseif ($alter_element['#description'] == field_filter_xss($instance['description'])) {
267
        $alter_element['#description'] = field_filter_xss($instance_current['description']);
268
      }
269
    }
270
  }
271

    
272
  // Translate list options.
273
  $has_options = (!empty($alter_element['#options']) || $field['type'] == 'list_boolean');
274
  $has_allowed_values = !empty($field['settings']['allowed_values']);
275
  $translate = i18n_field_type_info($field['type'], 'translate_options');
276
  if ($has_options && $has_allowed_values && $translate) {
277
    $alter_element['#options'] = $translate($field, $i18n_langcode);
278
    if (isset($alter_element['#properties']) && !empty($alter_element['#properties']['empty_option'])) {
279
      $label = theme('options_none', array('instance' => $instance, 'option' => $alter_element['#properties']['empty_option']));
280
      $alter_element['#options'] = array('_none' => $label) + $alter_element['#options'];
281
    }
282
    // Translate list_boolean fields using the checkboxes widget.
283
    if (!empty($alter_element['#title']) && $field['type'] == 'list_boolean' && !empty($alter_element['#on_value'])) {
284
      $on_value = $alter_element['#on_value'];
285
      $alter_element['#options'];
286
      $alter_element['#title'] = $alter_element['#options'][$on_value];
287
      // For using label instead of "On value".
288
      if ($instance['widget']['settings']['display_label']) {
289
        $alter_element['#title'] = $instance_current['label'];
290
      }
291
    }
292
  }
293

    
294
  // Check for more parameters, skip this part if missing.
295
  if (!isset($context['delta']) || !isset($context['items'])) {
296
    return;
297
  }
298
  $delta = $context['delta'];
299
  $items = $context['items'];
300

    
301
  // Translate default value.
302
  $has_default_value = (isset($alter_element['#default_value']) && !empty($instance['default_value'][$delta]['value']));
303
  $storage_has_value = !empty($items[$delta]['value']);
304
  $translate = i18n_field_type_info($field['type'], 'translate_default');
305
  if ($has_default_value && $storage_has_value && $translate) {
306
    // Compare the default value with the value currently in storage.
307
    if ($instance['default_value'][$delta]['value'] === $items[$delta]['value']) {
308
      $alter_element['#default_value'] = $translate($instance, $items[$delta]['value'], $i18n_langcode);
309
    }
310
  }
311
}
312

    
313
/**
314
 * Implements hook_field_attach_view_alter().
315
 */
316
function i18n_field_field_attach_view_alter(&$output, $context) {
317
  foreach (element_children($output) as $field_name) {
318
    $element = &$output[$field_name];
319
    if (!empty($element['#entity_type']) && !empty($element['#field_name']) && !empty($element['#bundle'])) {
320
      $instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);
321

    
322
      // Translate field title if set
323
      if (!empty($instance['label'])) {
324
        $element['#title'] = i18n_field_translate_property($instance, 'label');
325
      }
326

    
327
      // Translate field description if set
328
      if (!empty($instance['description'])) {
329
        $element['#description'] = i18n_field_translate_property($instance, 'description');
330
      }
331
    }
332
  }
333
}
334

    
335
/**
336
 * Implements hook_field_create_field().
337
 */
338
function i18n_field_field_create_field($field) {
339
  i18n_field_field_update_strings($field);
340
}
341

    
342
/**
343
 * Implements hook_field_create_instance().
344
 */
345
function i18n_field_field_create_instance($instance) {
346
  i18n_field_instance_update_strings($instance);
347
}
348

    
349
/**
350
 * Implements hook_field_delete_instance().
351
 */
352
function i18n_field_field_delete_instance($instance) {
353
  i18n_string_object_remove('field_instance', $instance);
354
}
355

    
356
/**
357
 * Implements hook_field_update_instance().
358
 */
359
function i18n_field_field_update_instance($instance, $prior_instance) {
360
  i18n_field_instance_update_strings($instance);
361
}
362

    
363
/**
364
 * Implements hook_field_update_field().
365
 */
366
function i18n_field_field_update_field($field) {
367
  i18n_field_field_update_strings($field);
368
}
369

    
370
/**
371
 * Update field strings
372
 */
373
function i18n_field_field_update_strings($field) {
374
  i18n_string_object_update('field', $field);
375
}
376

    
377
/**
378
 * Update field instance strings
379
 */
380
function i18n_field_instance_update_strings($instance) {
381
  i18n_string_object_update('field_instance', $instance);
382
}
383

    
384
/**
385
 * Returns the array of translated allowed values for a list field.
386
 *
387
 * The strings are not safe for output. Keys and values of the array should be
388
 * sanitized through field_filter_xss() before being displayed.
389
 *
390
 * @param $field
391
 *   The field definition.
392
 *
393
 * @return
394
 *   The array of allowed values. Keys of the array are the raw stored values
395
 *   (number or text), values of the array are the display labels.
396
 */
397
function i18n_field_translate_allowed_values($field, $langcode = NULL) {
398
  if (!empty($field['settings']['allowed_values'])) {
399
    return i18n_string_translate(array('field', $field['field_name'], '#allowed_values'), $field['settings']['allowed_values'], array('langcode' => $langcode, 'sanitize' => FALSE));
400
  }
401
  else {
402
    return array();
403
  }
404
}
405

    
406
/**
407
 * Translate field default.
408
 */
409
function i18n_field_translate_default($instance, $value, $langcode = NULL) {
410
  // The default value does not need sanitizing in a text_textfield widget.
411
  $sanitize = !($instance['widget']['type'] == 'text_textfield' && $instance['widget']['module'] == 'text');
412
  return i18n_string_translate(array('field', $instance['field_name'], $instance['bundle'], 'default_value'), $value, array('langcode' => $langcode, 'sanitize' => $sanitize));
413
}
414

    
415
/**
416
 * Translate field property
417
 */
418
function i18n_field_translate_property($instance, $property, $langcode = NULL) {
419
  // For performance reasons, we translate the whole instance once, which is cached.
420
  $instance = i18n_string_object_translate('field_instance', $instance, array('langcode' => $langcode));
421
  return $instance[$property];
422
}
423

    
424
/**
425
 * Get i18n information for translating fields.
426
 *
427
 * @param $type
428
 *   Optional field type.
429
 * @param $property
430
 *   Optional property to get from field type.
431
 *
432
 * @return
433
 *   - The property for the field if $type and $property set.
434
 *   - Array of properties for the field type if only $type is set.
435
 *   - Array of translation information for all field types.
436
 */
437
function i18n_field_type_info($type = NULL, $property = NULL) {
438
  $info = &drupal_static(__FUNCTION__);
439
  if (!isset($info)) {
440
    $info = module_invoke_all('i18n_field_info');
441
    drupal_alter('i18n_field_info', $info);
442
  }
443
  if ($property) {
444
    return isset($info[$type]) && isset($info[$type][$property]) ? $info[$type][$property] : NULL;
445
  }
446
  elseif ($type) {
447
    return isset($info[$type]) ? $info[$type] : array();
448
  }
449
  else {
450
    return $info;
451
  }
452
}
453

    
454
/**
455
 * Implements hook_field_info_alter().
456
 */
457
function i18n_field_field_info_alter(&$field_info) {
458
  foreach(array_keys($field_info) as $type) {
459
    $field_info[$type]['property_callbacks'][] = 'i18n_field_entity_property_callback';
460
  }
461
}
462

    
463
/**
464
 * Callback to translate entity property info for a fields.
465
 *
466
 * @see entity_metadata_field_entity_property_info()
467
 * @see entity_metadata_field_default_property_callback()
468
 * @see i18n_field_i18n_object_info_alter()
469
 * @see hook_module_implements_alter()
470
 */
471
function i18n_field_entity_property_callback(&$info, $entity_type, $field, $instance, $field_type) {
472
  global $language;
473

    
474
  // This could create a endless recursion if it's called during rebuilding the
475
  // cache for i18n_object_info(). So if the cache of i18n_object_info isn't
476
  // available yet we assume the worst case, leave the info alone but trigger a
477
  // rebuild of the property when hook_i18n_object_info_alter is invoked. At
478
  // that point the info is available and we can rely on it.
479
  if (!$info = &drupal_static('i18n_object_info')) {
480
    $i18n_field_entity_property_callback_fallback = &drupal_static(__FUNCTION__);
481
    $i18n_field_entity_property_callback_fallback = TRUE;
482
    return;
483
  }
484

    
485
  $name = $field['field_name'];
486
  $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$name];
487
  $property['label'] = i18n_field_translate_property($instance, 'label', $language->language);
488
}
489

    
490
/**
491
 * Implements hook_i18n_object_info_alter().
492
 */
493
function i18n_field_i18n_object_info_alter(&$info) {
494
  if (drupal_static('i18n_field_entity_property_callback')) {
495
    if ($info = drupal_static('i18n_object_info')) {
496
      // Clean static and permanent cache of the data and then re-run the property
497
      // building.
498
      drupal_static_reset('entity_get_property_info');
499
      cache_clear_all('entity_property_info:' . $GLOBALS['language']->language, 'cache');
500
      entity_get_property_info();
501
    }
502
    else {
503
      watchdog('i18n_field', 'Unable to run fall-back handling for entity property translation due missing "i18n_object_info" cache', array(), WATCHDOG_WARNING);
504
    }
505
  }
506
}
507

    
508
/**
509
 * Implements hook_module_implements_alter().
510
 */
511
function i18n_field_module_implements_alter(&$implementations, $hook) {
512
  if ($hook == 'i18n_object_info_alter') {
513
    // Move our hook implementation to the bottom.
514
    $group = $implementations['i18n_field'];
515
    unset($implementations['i18n_field']);
516
    $implementations['i18n_field'] = $group;
517
  }
518
}