Project

General

Profile

Paste
Download (19.2 KB) Statistics
| Branch: | Revision:

root / drupal7 / sites / all / modules / i18n / i18n_field / i18n_field.module @ 01f36513

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 ($field['type'] == 'url' && $field['module'] == 'url' && $field['cardinality'] == 1) {
198
    $alter_element = &$element;
199
  }
200
  elseif (isset($element['value'])) {
201
    // Number fields. Single-value text fields.
202
    $alter_element = &$element['value'];
203
  }
204
  elseif ($field['type'] == 'entityreference' && isset($element['target_id'])) {
205
    // Entityreference fields using the entityreference_autocomplete widget.
206
    $alter_element = &$element['target_id'];
207
  }
208
  elseif ($field['type'] == 'node_reference' && isset($element['nid'])) {
209
    // The node_reference fields using the entityreference_autocomplete widget.
210
    $alter_element = &$element['nid'];
211
  }
212
  else {
213
    // All other fields.
214
    $alter_element = &$element;
215
  }
216

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

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

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

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

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

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

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

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

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

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

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

    
338
/**
339
 * Implements hook_field_create_field().
340
 */
341
function i18n_field_field_create_field($field) {
342
  i18n_field_field_update_strings($field);
343
}
344

    
345
/**
346
 * Implements hook_field_create_instance().
347
 */
348
function i18n_field_field_create_instance($instance) {
349
  i18n_field_instance_update_strings($instance);
350
}
351

    
352
/**
353
 * Implements hook_field_delete_instance().
354
 */
355
function i18n_field_field_delete_instance($instance) {
356
  i18n_string_object_remove('field_instance', $instance);
357
}
358

    
359
/**
360
 * Implements hook_field_update_instance().
361
 */
362
function i18n_field_field_update_instance($instance, $prior_instance) {
363
  i18n_field_instance_update_strings($instance);
364
}
365

    
366
/**
367
 * Implements hook_field_update_field().
368
 */
369
function i18n_field_field_update_field($field) {
370
  i18n_field_field_update_strings($field);
371
}
372

    
373
/**
374
 * Update field strings
375
 */
376
function i18n_field_field_update_strings($field) {
377
  i18n_string_object_update('field', $field);
378
}
379

    
380
/**
381
 * Update field instance strings
382
 */
383
function i18n_field_instance_update_strings($instance) {
384
  i18n_string_object_update('field_instance', $instance);
385
}
386

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

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

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

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

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

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

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

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

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

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