content_translation.admin.inc 21.3 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * The content translation administration forms.
6 7 8
 */

use Drupal\Core\Entity\EntityInterface;
9
use Drupal\Core\Entity\Field\FieldDefinitionInterface;
10
use Drupal\Core\Language\Language;
11

12
/**
13
 * Returns a form element to configure field synchronization.
14
 *
15 16
 * @param \Drupal\Core\Entity\Field\FieldDefinitionInterface $field
 *   A field definition object.
17 18 19 20
 *
 * @return array
 *   A form element to configure field synchronization.
 */
21
function content_translation_field_sync_widget(FieldDefinitionInterface $field) {
22 23
  $element = array();

24 25
  $column_groups = $field->getFieldSetting('column_groups');
  if (!empty($column_groups) && count($column_groups) > 1) {
26 27 28
    $options = array();
    $default = array();

29
    foreach ($column_groups as $group => $info) {
30 31 32 33
      $options[$group] = $info['label'];
      $default[$group] = !empty($info['translatable']) ? $group : FALSE;
    }

34 35
    $settings = array('dependent_selectors' => array('instance[settings][translation_sync]' => array('file')));

36
    $translation_sync = $field->getFieldSetting('translation_sync');
37 38 39 40
    $element = array(
      '#type' => 'checkboxes',
      '#title' => t('Translatable elements'),
      '#options' => $options,
41
      '#default_value' => !empty($translation_sync) ? $translation_sync : $default,
42
      '#attached' => array(
43
        'library' => array(
44
          array('content_translation', 'drupal.content_translation.admin'),
45
        ),
46
        'js' => array(
47
          array('data' => array('contentTranslationDependentOptions' => $settings), 'type' => 'setting'),
48 49
        ),
      ),
50 51 52 53 54 55 56 57
    );
  }

  return $element;
}

/**
 * (proxied) Implements hook_form_FORM_ID_alter().
58
 */
59
function _content_translation_form_language_content_settings_form_alter(array &$form, array &$form_state) {
60 61
  // Inject into the content language settings the translation settings if the
  // user has the required permission.
62
  if (!user_access('administer content translation')) {
63 64 65 66 67
    return;
  }

  $default = $form['entity_types']['#default_value'];
  foreach ($default as $entity_type => $enabled) {
68
    $default[$entity_type] = $enabled || content_translation_enabled($entity_type) ? $entity_type : FALSE;
69 70 71
  }
  $form['entity_types']['#default_value'] = $default;

72 73
  $form['#attached']['library'][] = array('content_translation', 'drupal.content_translation.admin');
  $form['#attached']['js'][] = array('data' => drupal_get_path('module', 'content_translation') . '/content_translation.admin.js', 'type' => 'file');
74

75
  $dependent_options_settings = array();
76
  foreach ($form['#labels'] as $entity_type => $label) {
77
    $entity_info = entity_get_info($entity_type);
78
    foreach (entity_get_bundles($entity_type) as $bundle => $bundle_info) {
79 80 81
      // Here we do not want the widget to be altered and hold also the "Enable
      // translation" checkbox, which would be redundant. Hence we add this key
      // to be able to skip alterations.
82
      $form['settings'][$entity_type][$bundle]['settings']['language']['#content_translation_skip_alter'] = TRUE;
83

84 85 86
      // Only show the checkbox to enable translation if the bundles in the
      // entity might have fields and if there are fields to translate.
      if (!empty($entity_info['fieldable'])) {
87 88
        $instances = field_info_instances($entity_type, $bundle);
        if ($instances) {
89 90
          $form['settings'][$entity_type][$bundle]['translatable'] = array(
            '#type' => 'checkbox',
91
            '#title' => $bundle,
92
            '#default_value' => content_translation_enabled($entity_type, $bundle),
93 94 95 96
          );

          // @todo Exploit field definitions once all core entities and field
          // types are migrated to the Entity Field API.
97
          foreach ($instances as $field_name => $instance) {
98
            $form['settings'][$entity_type][$bundle]['fields'][$field_name] = array(
99
              '#label' => $instance->getFieldLabel(),
100
              '#type' => 'checkbox',
101 102
              '#title' => $instance->getFieldLabel(),
              '#default_value' => $instance->isFieldTranslatable(),
103
            );
104
            $column_element = content_translation_field_sync_widget($instance);
105 106
            if ($column_element) {
              $form['settings'][$entity_type][$bundle]['columns'][$field_name] = $column_element;
107

108 109 110 111
              if (isset($column_element['#options']['file'])) {
                $dependent_options_settings["settings[{$entity_type}][{$bundle}][columns][{$field_name}]"] = array('file');
              }
            }
112
          }
113
        }
114 115 116
      }
    }
  }
117
  $settings = array('dependent_selectors' => $dependent_options_settings);
118 119 120
  $form['#attached']['js'][] = array('data' => array('contentTranslationDependentOptions' => $settings), 'type' => 'setting');
  $form['#validate'][] = 'content_translation_form_language_content_settings_validate';
  $form['#submit'][] = 'content_translation_form_language_content_settings_submit';
121 122
}

123 124 125
/**
 * (proxied) Implements hook_preprocess_HOOK();
 */
126
function _content_translation_preprocess_language_content_settings_table(&$variables) {
127 128
  // Alter the 'build' variable injecting the translation settings if the user
  // has the required permission.
129
  if (!user_access('administer content translation')) {
130 131 132 133 134 135 136 137 138 139 140
    return;
  }

  $element = $variables['element'];
  $build = &$variables['build'];

  array_unshift($build['#header'], array('data' => t('Translatable'), 'class' => array('translatable')));
  $rows = array();

  foreach (element_children($element) as $bundle) {
    $field_names = !empty($element[$bundle]['fields']) ? element_children($element[$bundle]['fields']) : array();
141 142 143
    if (!empty($element[$bundle]['translatable'])) {
      $checkbox_id = $element[$bundle]['translatable']['#id'];
    }
144 145
    $rows[$bundle] = $build['#rows'][$bundle];

146 147 148 149 150 151
    if (!empty($element[$bundle]['translatable'])) {
      $translatable = array(
        'data' => $element[$bundle]['translatable'],
        'class' => array('translatable'),
      );
      array_unshift($rows[$bundle]['data'], $translatable);
152

153 154 155 156 157 158 159 160
      $rows[$bundle]['data'][1]['data']['#prefix'] = '<label for="' . $checkbox_id . '">';
    }
    else {
      $translatable = array(
        'class' => array('untranslatable'),
      );
      array_unshift($rows[$bundle]['data'], $translatable);
    }
161 162 163 164 165 166 167 168 169 170 171 172 173 174

    foreach ($field_names as $field_name) {
      $field_element = &$element[$bundle]['fields'][$field_name];
      $rows[] = array(
        'data' => array(
          array(
            'data' => drupal_render($field_element),
            'class' => array('translatable'),
          ),
          array(
            'data' => array(
              '#prefix' => '<label for="' . $field_element['#id'] . '">',
              '#suffix' => '</label>',
              'bundle' => array(
175
                '#prefix' => '<span class="visually-hidden">',
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
                '#suffix' => '</span> ',
                '#markup' => check_plain($element[$bundle]['settings']['#label']),
              ),
              'field' => array(
                '#markup' => check_plain($field_element['#label']),
              ),
            ),
            'class' => array('field'),
          ),
          array(
            'data' => '',
            'class' => array('operations'),
          ),
        ),
        'class' => array('field-settings'),
      );

      if (!empty($element[$bundle]['columns'][$field_name])) {
        $column_element = &$element[$bundle]['columns'][$field_name];
        foreach (element_children($column_element) as $key) {
          $column_label = $column_element[$key]['#title'];
          unset($column_element[$key]['#title']);
          $rows[] = array(
            'data' => array(
              array(
                'data' => drupal_render($column_element[$key]),
                'class' => array('translatable'),
              ),
              array(
                'data' => array(
                  '#prefix' => '<label for="' . $column_element[$key]['#id'] . '">',
                  '#suffix' => '</label>',
                  'bundle' => array(
209
                    '#prefix' => '<span class="visually-hidden">',
210 211 212 213
                    '#suffix' => '</span> ',
                    '#markup' => check_plain($element[$bundle]['settings']['#label']),
                  ),
                  'field' => array(
214
                    '#prefix' => '<span class="visually-hidden">',
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
                    '#suffix' => '</span> ',
                    '#markup' => check_plain($field_element['#label']),
                  ),
                  'columns' => array(
                    '#markup' => check_plain($column_label),
                  ),
                ),
                'class' => array('column'),
              ),
              array(
                'data' => '',
                'class' => array('operations'),
              ),
            ),
            'class' => array('column-settings'),
          );
        }
      }
    }
  }

  $build['#rows'] = $rows;
}

239
/**
240
 * Form validation handler for content_translation_admin_settings_form().
241
 *
242
 * @see content_translation_admin_settings_form_submit()
243
 */
244
function content_translation_form_language_content_settings_validate(array $form, array &$form_state) {
245 246 247 248 249 250 251 252 253 254 255 256 257
  $settings = &$form_state['values']['settings'];
  foreach ($settings as $entity_type => $entity_settings) {
    foreach ($entity_settings as $bundle => $bundle_settings) {
      if (!empty($bundle_settings['translatable'])) {
        $name = "settings][$entity_type][$bundle][translatable";

        $translatable_fields = isset($settings[$entity_type][$bundle]['fields']) ? array_filter($settings[$entity_type][$bundle]['fields']) : FALSE;
        if (empty($translatable_fields)) {
          $t_args = array('%bundle' => $form['settings'][$entity_type][$bundle]['settings']['#label']);
          form_set_error($name, t('At least one field needs to be translatable to enable %bundle for translation.', $t_args));
        }

        $values = $bundle_settings['settings']['language'];
258
        if (language_is_locked($values['langcode']) && empty($values['language_show'])) {
259
          foreach (language_list(Language::STATE_LOCKED) as $language) {
260 261 262 263 264 265 266 267 268 269
            $locked_languages[] = $language->name;
          }
          form_set_error($name, t('Translation is not supported if language is always one of: @locked_languages', array('@locked_languages' => implode(', ', $locked_languages))));
        }
      }
    }
  }
}

/**
270
 * Form submission handler for content_translation_admin_settings_form().
271
 *
272
 * @see content_translation_admin_settings_form_validate()
273
 */
274
function content_translation_form_language_content_settings_submit(array $form, array &$form_state) {
275 276 277 278 279 280 281 282
  $entity_types = $form_state['values']['entity_types'];
  $settings = &$form_state['values']['settings'];

  // If an entity type is not translatable all its bundles and fields must be
  // marked as non-translatable. Similarly, if a bundle is made non-translatable
  // all of its fields will be not translatable.
  foreach ($settings as $entity_type => &$entity_settings) {
    foreach ($entity_settings as $bundle => &$bundle_settings) {
283 284 285
      if (!empty($bundle_settings['translatable'])) {
        $bundle_settings['translatable'] = $bundle_settings['translatable'] && $entity_types[$entity_type];
      }
286 287 288
      if (!empty($bundle_settings['fields'])) {
        foreach ($bundle_settings['fields'] as $field_name => $translatable) {
          $bundle_settings['fields'][$field_name] = $translatable && $bundle_settings['translatable'];
289 290 291 292 293
          // If we have column settings and no column is translatable, no point
          // in making the field translatable.
          if (isset($bundle_settings['columns'][$field_name]) && !array_filter($bundle_settings['columns'][$field_name])) {
            $bundle_settings['fields'][$field_name] = FALSE;
          }
294 295 296 297 298
        }
      }
    }
  }

299
  _content_translation_update_field_translatability($settings);
300 301 302 303
  drupal_set_message(t('Settings successfully updated.'));
}

/**
304
 * Stores content translation settings.
305 306 307 308 309 310 311 312 313 314 315 316 317
 *
 * @param array $settings
 *   An associative array of settings keyed by entity type and bundle. At bundle
 *   level the following keys are available:
 *   - translatable: The bundle translatability status, which is a bool.
 *   - settings: An array of language configuration settings as defined by
 *     language_save_default_configuration().
 *   - fields: An associative array with field names as keys and a boolean as
 *     value, indicating field translatability.
 *
 * @todo Remove this migration entirely once the Field API is converted to the
 *   Entity Field API.
 */
318
function _content_translation_update_field_translatability($settings) {
319 320 321 322 323 324 325 326 327 328
  $fields = array();
  foreach ($settings as $entity_type => $entity_settings) {
    foreach ($entity_settings as $bundle => $bundle_settings) {
      // Collapse field settings since here we have per instance settings, but
      // translatability has per-field scope. We assume that all the field
      // instances have the same value.
      if (!empty($bundle_settings['fields'])) {
        foreach ($bundle_settings['fields'] as $field_name => $translatable) {
          // If a field is enabled for translation for at least one instance we
          // need to mark it as translatable.
329
          $fields[$entity_type][$field_name] = $translatable || !empty($fields[$entity_type][$field_name]);
330 331 332 333 334 335 336 337
        }
      }
      // @todo Store non-configurable field settings to be able to alter their
      //   definition afterwards.
    }
  }

  $operations = array();
338 339 340
  foreach ($fields as $entity_type => $entity_type_fields) {
    foreach ($entity_type_fields as $field_name => $translatable) {
      $field = field_info_field($entity_type, $field_name);
341
      if ($field->isFieldTranslatable() != $translatable) {
342 343 344 345 346 347 348 349 350 351 352 353 354
        // If a field is untranslatable, it can have no data except under
        // Language::LANGCODE_NOT_SPECIFIED. Thus we need a field to be translatable before
        // we convert data to the entity language. Conversely we need to switch
        // data back to Language::LANGCODE_NOT_SPECIFIED before making a field
        // untranslatable lest we lose information.
        $field_operations = array(
          array('content_translation_translatable_switch', array($translatable, $entity_type, $field_name)),
        );
        if ($field->hasData()) {
          $field_operations[] = array('content_translation_translatable_batch', array($translatable, $field_name));
          $field_operations = $translatable ? $field_operations : array_reverse($field_operations);
        }
        $operations = array_merge($operations, $field_operations);
355 356 357 358 359
      }
    }
  }

  // As last operation store the submitted settings.
360
  $operations[] = array('content_translation_save_settings', array($settings));
361 362 363 364

  $batch = array(
    'title' => t('Updating translatability for the selected fields'),
    'operations' => $operations,
365 366
    'finished' => 'content_translation_translatable_batch_done',
    'file' => drupal_get_path('module', 'content_translation') . '/content_translation.admin.inc',
367 368 369 370
  );
  batch_set($batch);
}

371 372 373 374 375 376 377 378
/**
 * Toggles translatability of the given field.
 *
 * This is called from a batch operation, but should only run once per field.
 *
 * @param bool $translatable
 *   Indicator of whether the field should be made translatable (TRUE) or
 *   untranslatble (FALSE).
379 380
 * @param string $entity_type
 *   Field entity type.
381 382 383
 * @param string $field_name
 *   Field machine name.
 */
384 385
function content_translation_translatable_switch($translatable, $entity_type, $field_name) {
  $field = field_info_field($entity_type, $field_name);
386 387
  if ($field->isFieldTranslatable() !== $translatable) {
    $field->translatable = $translatable;
388
    $field->save();
389 390 391 392
  }
}

/**
393
 * Batch callback: Converts field data to or from Language::LANGCODE_NOT_SPECIFIED.
394 395 396 397 398 399 400
 *
 * @param bool $translatable
 *   Indicator of whether the field should be made translatable (TRUE) or
 *   untranslatble (FALSE).
 * @param string $field_name
 *   Field machine name.
 */
401
function content_translation_translatable_batch($translatable, $field_name, &$context) {
402
  // Determine the entity types to act on.
403
  $entity_types = array();
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
  foreach (field_info_instances() as $entity_type => $info) {
    foreach ($info as $bundle => $instances) {
      foreach ($instances as $instance_field_name => $instance) {
        if ($instance_field_name == $field_name) {
          $entity_types[] = $entity_type;
          break 2;
        }
      }
    }
  }

  if (empty($context['sandbox'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max'] = 0;

    foreach ($entity_types as $entity_type) {
420
      $field = field_info_field($entity_type, $field_name);
421 422
      $columns = $field->getColumns();
      $column = isset($columns['value']) ? 'value' : key($columns);
423 424
      $query_field = "$field_name.$column";

425
      // How many entities will need processing?
426
      $query = \Drupal::entityQuery($entity_type);
427
      $count = $query
428
        ->exists($query_field)
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
        ->count()
        ->execute();

      $context['sandbox']['max'] += $count;
      $context['sandbox']['progress_entity_type'][$entity_type] = 0;
      $context['sandbox']['max_entity_type'][$entity_type] = $count;
    }

    if ($context['sandbox']['max'] === 0) {
      // Nothing to do.
      $context['finished'] = 1;
      return;
    }
  }

  foreach ($entity_types as $entity_type) {
    if ($context['sandbox']['max_entity_type'][$entity_type] === 0) {
      continue;
    }

    $info = entity_get_info($entity_type);
    $offset = $context['sandbox']['progress_entity_type'][$entity_type];
451
    $query = \Drupal::entityQuery($entity_type);
452
    $field = field_info_field($entity_type, $field_name);
453 454
    $columns = $field->getColumns();
    $column = isset($columns['value']) ? 'value' : key($columns);
455
    $query_field = "$field_name.$column";
456
    $result = $query
457
      ->exists($query_field)
458 459 460 461 462 463 464 465
      ->sort($info['entity_keys']['id'])
      ->range($offset, 10)
      ->execute();

    foreach (entity_load_multiple($entity_type, $result) as $id => $entity) {
      $context['sandbox']['max_entity_type'][$entity_type] -= count($result);
      $context['sandbox']['progress_entity_type'][$entity_type]++;
      $context['sandbox']['progress']++;
466
      $langcode = $entity->language()->id;
467 468

      // Skip process for language neutral entities.
469
      if ($langcode == Language::LANGCODE_NOT_SPECIFIED) {
470 471 472 473 474
        continue;
      }

      // We need a two-step approach while updating field translations: given
      // that field-specific update functions might rely on the stored values to
475 476 477 478
      // perform their processing first we need to store the new translations
      // and only after we can remove the old ones. Otherwise we might have data
      // loss, since the removal of the old translations might occur before the
      // new ones are stored.
479
      if ($translatable && isset($entity->{$field_name}[Language::LANGCODE_NOT_SPECIFIED])) {
480
        // If the field is being switched to translatable and has data for
481
        // Language::LANGCODE_NOT_SPECIFIED then we need to move the data to the right
482
        // language.
483
        $entity->{$field_name}[$langcode] = $entity->{$field_name}[Language::LANGCODE_NOT_SPECIFIED];
484
        // Store the original value.
485
        _content_translation_update_field($entity_type, $entity, $field_name);
486
        $entity->{$field_name}[Language::LANGCODE_NOT_SPECIFIED] = array();
487
        // Remove the language neutral value.
488
        _content_translation_update_field($entity_type, $entity, $field_name);
489 490 491
      }
      elseif (!$translatable && isset($entity->{$field_name}[$langcode])) {
        // The field has been marked untranslatable and has data in the entity
492
        // language: we need to move it to Language::LANGCODE_NOT_SPECIFIED and drop the
493
        // other translations.
494
        $entity->{$field_name}[Language::LANGCODE_NOT_SPECIFIED] = $entity->{$field_name}[$langcode];
495
        // Store the original value.
496
        _content_translation_update_field($entity_type, $entity, $field_name);
497 498
        // Remove translations.
        foreach ($entity->{$field_name} as $langcode => $items) {
499
          if ($langcode != Language::LANGCODE_NOT_SPECIFIED) {
500 501 502
            $entity->{$field_name}[$langcode] = array();
          }
        }
503
        _content_translation_update_field($entity_type, $entity, $field_name);
504 505 506 507 508 509 510 511 512 513 514 515 516 517
      }
      else {
        // No need to save unchanged entities.
        continue;
      }
    }
  }

  $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
}

/**
 * Stores the given field translations.
 */
518
function _content_translation_update_field($entity_type, EntityInterface $entity, $field_name) {
519
  $empty = 0;
520
  $translations = $entity->getTranslationLanguages();
521 522

  // Ensure that we are trying to store only valid data.
523 524 525 526
  foreach (array_keys($translations) as $langcode) {
    $items = $entity->getTranslation($langcode)->get($field_name);
    $items->filterEmptyValues();
    $empty += $items->isEmpty();
527 528 529 530 531
  }

  // Save the field value only if there is at least one item available,
  // otherwise any stored empty field value would be deleted. If this happens
  // the range queries would be messed up.
532 533
  if ($empty < count($translations)) {
    $entity->save();
534 535 536 537 538 539
  }
}

/**
 * Batch finished callback: Checks the exit status of the batch operation.
 */
540
function content_translation_translatable_batch_done($success, $results, $operations) {
541 542 543 544 545 546 547 548 549
  if ($success) {
    drupal_set_message(t("Successfully changed field translation setting."));
  }
  else {
    // @todo: Do something about this case.
    drupal_set_message(t("Something went wrong while processing data. Some nodes may appear to have lost fields."), 'error');
  }
}