l10n_server-2.x-dev/l10n_community/src/Form/ImportForm.php

l10n_community/src/Form/ImportForm.php
<?php

declare(strict_types=1);

namespace Drupal\l10n_community\Form;

use Drupal\Component\Utility\Environment;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Translation export form.
 */
class ImportForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId(): string {
    return 'l10n_community_import';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, ?string $langcode = NULL): array {
    /** @var \Drupal\l10n_community\L10nAccess $access */
    $access = \Drupal::service('l10n_community.access');
    $user = \Drupal::currentUser()->getAccount();
    $config = \Drupal::config('l10n_community.settings');

    if (!$langcode) {
      $langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
    }

    $form['#attributes']['enctype'] = 'multipart/form-data';
    $form['langcode'] = [
      '#type' => 'value',
      '#value' => $langcode,
    ];

    $form['file'] = [
      '#type' => 'file',
      '#title' => t('Gettext .po file with translations'),
      '#size' => 50,
      '#description' => t('The maximum allowed size for uploads is %maxsize.', [
        '%maxsize' => format_size(Environment::getUploadMaxSize()),
      ]),
    ];

    $form['import_uid'] = [
      '#type' => 'value',
      '#value' => $user->id(),
    ];

    if (
      ($import_name = $config->get('import_user'))
      && ($import_account = user_load_by_name($import_name))
    ) {
      // If available, let the user import with attribution to a bulk import
      // user.
      $form['import_uid'] = [
        '#title' => t('Attribute import to'),
        '#type' => 'radios',
        '#default_value' => $user->id(),
        '#options' => [
          $user->id() => $this->t('Yourself (%name)', ['%name' => $user->getDisplayName()]),
          $import_account->id() => $import_account->getDisplayName(),
        ],
        '#description' => $this->t(
          'When importing the result of teamwork,
          If the imported translations were worked on by a team of people,
          it is common courtesy to not attribute them to your personal username
          to ensure you do not claim credit for work of the whole team.
        '),
      ];
    }

    if (!$access->check('moderate own suggestions')
        && (!$access->check('moderate suggestions from others') || empty($import_account))) {
      // Either has no permission to approve own or approve others, or we do not
      // have a mass import account and no permission to approve own, so no way
      // we can offer importing translations directly.
      $form['is_suggestion'] = [
        '#type' => 'value',
        '#value' => 1,
      ];
    }
    else {
      // If can submit translations, offer option to pick mode.
      $form['is_suggestion'] = [
        '#title' => $this->t('Status'),
        '#type' => 'radios',
        '#default_value' => 0,
        '#options' => [
          0 => $this->t('Store as approved translations'),
          1 => $this->t('Store as suggestions needing approval, possibly discussion'),
        ],
      ];
    }

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => t('Import'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    /** @var \Drupal\l10n_community\L10nAccess $access */
    $access = \Drupal::service('l10n_community.access');
    $user = \Drupal::currentUser()->getAccount();

    if (empty($form_state->getValue('is_suggestion'))) {
      if ($form_state->getValue('import_uid') == $user->id()) {
        // Trying to submit translation in its own name.
        if (!$access->check('moderate own suggestions')) {
          $form_state->setErrorByName('is_suggestion', $this->t('You do not have sufficient permissions to submit translations directly in your name. Please submit as suggestions.'));
        }
      }
      else {
        // Trying to submit translation in the import_account's name.
        if (!$access->check('moderate suggestions from others')) {
          $form_state->setErrorByName('is_suggestion', $this->t('You do not have sufficient permissions to submit translations directly in the name of other users. Please submit as suggestions.'));
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    /** @var \Drupal\l10n_server\L10nPo $po */
    $po = \Drupal::service('l10n_server.po');

    // Save file in the local file system.
    $validators = ['file_validate_extensions' => []];
    /** @var \Drupal\file\FileInterface $file */
    if ($file = file_save_upload('file', $validators, FALSE, 0)) {
      // Increase time limit for PO parsing if possible.
      if (!ini_get('safe_mode')) {
        set_time_limit(240);
      }

      // Do the actual parsing on the local file.
      $parsed = $po->parse($file, 'Drupal\l10n_server\L10nPo::importOneString', [
        $form_state->getValue('langcode'),
        $form_state->getValue('is_suggestion'),
        $form_state->getValue('import_uid'),
      ]);
      if ($parsed) {
        $po->updateMessage();
        // @todo Clear cache where stats are shown.
        // phpcs:ignore
        // cache_clear_all('l10n:stats:' . $form_state['values']['langcode'], 'cache');
      }
    }
    else {
      \Drupal::messenger()->addError(t('File to import not found. Did you choose a .po file to upload which was under %maxsize?', [
        '%maxsize' => format_size(Environment::getUploadMaxSize()),
      ]));
    }

  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc