TranslateEditForm.php 10 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php

/**
 * @file
 * Contains \Drupal\locale\Form\TranslateEditForm.
 */

namespace Drupal\locale\Form;

use Drupal\Component\Utility\String;
11
use Drupal\Core\Form\FormStateInterface;
12
use Drupal\Core\Render\Element;
13 14 15 16 17 18 19 20 21 22
use Drupal\locale\SourceString;

/**
 * Defines a translation edit form.
 */
class TranslateEditForm extends TranslateFormBase {

  /**
   * {@inheritdoc}
   */
23
  public function getFormId() {
24 25 26 27 28 29
    return 'locale_translate_edit_form';
  }

  /**
   * {@inheritdoc}
   */
30
  public function buildForm(array $form, FormStateInterface $form_state) {
31 32 33
    $filter_values = $this->translateFilterValues();
    $langcode = $filter_values['langcode'];

34
    $this->languageManager->reset();
35 36
    $languages = language_list();

37
    $langname = isset($langcode) ? $languages[$langcode]->getName() : "- None -";
38

39
    $form['#attached']['library'][] = 'locale/drupal.locale.admin';
40 41 42 43 44 45 46

    $form['langcode'] = array(
      '#type' => 'value',
      '#value' => $filter_values['langcode'],
    );

    $form['strings'] = array(
47
      '#type' => 'table',
48 49
      '#tree' => TRUE,
      '#language' => $langname,
50 51 52 53 54 55
      '#header' => [
        $this->t('Source string'),
        $this->t('Translation for @language', ['@language' => $langname]),
      ],
      '#empty' => $this->t('No strings available.'),
      '#attributes' => ['class' => ['locale-translate-edit-table']],
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    );

    if (isset($langcode)) {
      $strings = $this->translateFilterLoadStrings();

      $plural_formulas = $this->state->get('locale.translation.plurals') ?: array();

      foreach ($strings as $string) {
        // Cast into source string, will do for our purposes.
        $source = new SourceString($string);
        // Split source to work with plural values.
        $source_array = $source->getPlurals();
        $translation_array = $string->getPlurals();
        if (count($source_array) == 1) {
          // Add original string value and mark as non-plural.
71
          $plural = FALSE;
72 73 74 75 76 77 78 79 80
          $form['strings'][$string->lid]['original'] = array(
            '#type' => 'item',
            '#title' => $this->t('Source string (@language)', array('@language' => $this->t('Built-in English'))),
            '#title_display' => 'invisible',
            '#markup' => '<span lang="en">' . String::checkPlain($source_array[0]) . '</span>',
          );
        }
        else {
          // Add original string value and mark as plural.
81 82
          $plural = TRUE;
          $original_singular = [
83 84 85
            '#type' => 'item',
            '#title' => $this->t('Singular form'),
            '#markup' => '<span lang="en">' . String::checkPlain($source_array[0]) . '</span>',
86
            '#prefix' => '<span class="visually-hidden">' . $this->t('Source string (@language)', array('@language' => $this->t('Built-in English'))) . '</span>',
87 88
          ];
          $original_plural = [
89 90 91
            '#type' => 'item',
            '#title' => $this->t('Plural form'),
            '#markup' => '<span lang="en">' . String::checkPlain($source_array[1]) . '</span>',
92 93 94 95 96 97
          ];
          $form['strings'][$string->lid]['original'] = [
            $original_singular,
            ['#markup' => '<br>'],
            $original_plural,
          ];
98 99
        }
        if (!empty($string->context)) {
100 101 102 103 104 105 106 107
          $form['strings'][$string->lid]['original'][] = [
            '#type' => 'inline_template',
            '#template' => '<br><small>{{ context_title }}: <span lang="en">{{ context }}</span></small>',
            '#context' => [
              'context_title' => $this->t('In Context'),
              'context' => $string->context,
            ],
          ];
108 109 110
        }
        // Approximate the number of rows to use in the default textarea.
        $rows = min(ceil(str_word_count($source_array[0]) / 12), 10);
111
        if (!$plural) {
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
          $form['strings'][$string->lid]['translations'][0] = array(
            '#type' => 'textarea',
            '#title' => $this->t('Translated string (@language)', array('@language' => $langname)),
            '#title_display' => 'invisible',
            '#rows' => $rows,
            '#default_value' => $translation_array[0],
            '#attributes' => array('lang' => $langcode),
          );
        }
        else {
          // Dealing with plural strings.
          if (isset($plural_formulas[$langcode]['plurals']) && $plural_formulas[$langcode]['plurals'] > 2) {
            // Add a textarea for each plural variant.
            for ($i = 0; $i < $plural_formulas[$langcode]['plurals']; $i++) {
              $form['strings'][$string->lid]['translations'][$i] = array(
                '#type' => 'textarea',
128
                '#title' => ($i == 0 ? $this->t('Singular form') : $this->formatPlural($i, 'First plural form', '@count. plural form')),
129 130 131
                '#rows' => $rows,
                '#default_value' => isset($translation_array[$i]) ? $translation_array[$i] : '',
                '#attributes' => array('lang' => $langcode),
132
                '#prefix' => $i == 0 ? ('<span class="visually-hidden">' . $this->t('Translated string (@language)', array('@language' => $langname)) . '</span>') : '',
133 134 135 136 137 138 139 140 141 142 143
              );
            }
          }
          else {
            // Fallback for unknown number of plurals.
            $form['strings'][$string->lid]['translations'][0] = array(
              '#type' => 'textarea',
              '#title' => $this->t('Singular form'),
              '#rows' => $rows,
              '#default_value' => $translation_array[0],
              '#attributes' => array('lang' => $langcode),
144
              '#prefix' => '<span class="visually-hidden">' . $this->t('Translated string (@language)', array('@language' => $langname)) . '</span>',
145 146 147 148 149 150 151 152 153 154 155
            );
            $form['strings'][$string->lid]['translations'][1] = array(
              '#type' => 'textarea',
              '#title' => $this->t('Plural form'),
              '#rows' => $rows,
              '#default_value' => isset($translation_array[1]) ? $translation_array[1] : '',
              '#attributes' => array('lang' => $langcode),
            );
          }
        }
      }
156
      if (count(Element::children($form['strings']))) {
157 158 159 160 161 162 163
        $form['actions'] = array('#type' => 'actions');
        $form['actions']['submit'] = array(
          '#type' => 'submit',
          '#value' => $this->t('Save translations'),
        );
      }
    }
164
    $form['pager']['#theme'] = 'pager';
165 166 167 168 169 170
    return $form;
  }

  /**
   * {@inheritdoc}
   */
171
  public function validateForm(array &$form, FormStateInterface $form_state) {
172 173
    $langcode = $form_state->getValue('langcode');
    foreach ($form_state->getValue('strings') as $lid => $translations) {
174 175
      foreach ($translations['translations'] as $key => $value) {
        if (!locale_string_is_safe($value)) {
176 177
          $form_state->setErrorByName("strings][$lid][translations][$key", $this->t('The submitted string contains disallowed HTML: %string', array('%string' => $value)));
          $form_state->setErrorByName("translations][$langcode][$key", $this->t('The submitted string contains disallowed HTML: %string', array('%string' => $value)));
178
          $this->logger('locale')->warning('Attempted submission of a translation string with disallowed HTML: %string', array('%string' => $value));
179 180 181 182 183 184 185 186
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
187
  public function submitForm(array &$form, FormStateInterface $form_state) {
188
    $langcode = $form_state->getValue('langcode');
189 190 191
    $updated = array();

    // Preload all translations for strings in the form.
192
    $lids = array_keys($form_state->getValue('strings'));
193 194 195 196 197
    $existing_translation_objects = array();
    foreach ($this->localeStorage->getTranslations(array('lid' => $lids, 'language' => $langcode, 'translated' => TRUE)) as $existing_translation_object) {
      $existing_translation_objects[$existing_translation_object->lid] = $existing_translation_object;
    }

198
    foreach ($form_state->getValue('strings') as $lid => $new_translation) {
199 200 201
      $existing_translation = isset($existing_translation_objects[$lid]);

      // Plural translations are saved in a delimited string. To be able to
202 203
      // compare the new strings with the existing strings a string in the same
      // format is created.
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
      $new_translation_string_delimited = implode(LOCALE_PLURAL_DELIMITER, $new_translation['translations']);

      // Generate an imploded string without delimiter, to be able to run
      // empty() on it.
      $new_translation_string = implode('', $new_translation['translations']);

      $is_changed = FALSE;

      if ($existing_translation && $existing_translation_objects[$lid]->translation != $new_translation_string_delimited) {
        // If there is an existing translation in the DB and the new translation
        // is not the same as the existing one.
        $is_changed = TRUE;
      }
      elseif (!$existing_translation && !empty($new_translation_string)) {
        // Newly entered translation.
        $is_changed = TRUE;
      }

      if ($is_changed) {
        // Only update or insert if we have a value to use.
        $target = isset($existing_translation_objects[$lid]) ? $existing_translation_objects[$lid] : $this->localeStorage->createTranslation(array('lid' => $lid, 'language' => $langcode));
        $target->setPlurals($new_translation['translations'])
          ->setCustomized()
          ->save();
        $updated[] = $target->getId();
      }
      if (empty($new_translation_string) && isset($existing_translation_objects[$lid])) {
        // Empty new translation entered: remove existing entry from database.
        $existing_translation_objects[$lid]->delete();
        $updated[] = $lid;
      }
    }

    drupal_set_message($this->t('The strings have been saved.'));

    // Keep the user on the current pager page.
    $page = $this->getRequest()->query->get('page');
    if (isset($page)) {
242 243 244 245
      $form_state->setRedirect(
        'locale.translate_page',
        array(),
        array('page' => $page)
246
      );
247 248 249 250 251 252 253 254 255 256
    }

    if ($updated) {
      // Clear cache and force refresh of JavaScript translations.
      _locale_refresh_translations(array($langcode), $updated);
      _locale_refresh_configuration(array($langcode), $updated);
    }
  }

}