You are here

tmgmt_smartling.module in TMGMT Translator Smartling 8.2

Contains

File

tmgmt_smartling.module
View source
<?php

/**
 * @file
 * Contains
 */
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\tmgmt\JobInterface;
use Drupal\tmgmt\JobItemInterface;
use Drupal\views\ViewExecutable;
use Smartling\File\Params\DownloadFileParameters;
function tmgmt_smartling_download_file_submit(array &$form, FormStateInterface $form_state) {

  /* @var \Drupal\tmgmt\Entity\Job $job */
  $job = $form_state
    ->getFormObject()
    ->getEntity();

  /* @var \Drupal\tmgmt_smartling\Smartling\SmartlingApi $smartlingApi */
  tmgmt_smartling_download_file($job);
}
function tmgmt_smartling_download_file(JobInterface $job) {
  try {
    $smartlingApi = $job
      ->getTranslatorPlugin()
      ->getApi($job
      ->getTranslator());
    $retrieval_type = $job
      ->getTranslator()
      ->getSetting('retrieval_type');
    $filename = $job
      ->getTranslatorPlugin()
      ->getFileName($job);
    $downloadParameters = new DownloadFileParameters();
    $downloadParameters
      ->set('retrievalType', $retrieval_type);
    $extension = pathinfo($filename, PATHINFO_EXTENSION);
    $xml = $smartlingApi
      ->downloadFile($filename, $job
      ->getRemoteTargetLanguage(), $downloadParameters);
  } catch (\Exception $e) {
    Drupal::logger('tmgmt_smartling')
      ->error($e
      ->getMessage());
    return FALSE;
  }
  $path = $job
    ->getSetting('scheme') . '://tmgmt_smartling_translations/' . $job
    ->getTranslatorPlugin()
    ->getFileName($job);
  $dirname = dirname($path);
  if (file_prepare_directory($dirname, FILE_CREATE_DIRECTORY) && ($file = file_save_data($xml, $path, FILE_EXISTS_REPLACE))) {
    $plugin = \Drupal::service('plugin.manager.tmgmt_file.format')
      ->createInstance($extension);
    if ($plugin) {

      // Validate the file on job.
      if (!$plugin
        ->validateImport($file
        ->getFileUri(), $job)) {
        $job
          ->addMessage('Failed to validate file @file. Import for job @job_id aborted.', [
          '@file' => $file
            ->getFileUri(),
          '@job_id' => $job
            ->id(),
        ], 'error');
        \Drupal::logger('tmgmt_smartling')
          ->error('Failed to validate file @file. Import for job @job_id aborted.', [
          '@file' => $file
            ->getFileUri(),
          '@job_id' => $job
            ->id(),
        ]);
        return FALSE;
      }
      else {
        try {

          // Compare old and new hashes in order to decide should we apply
          // translation or not. In other words we do not want to apply
          // downloaded translation if it's the same as it was.
          $old_hash = $job
            ->get('job_file_content_hash')
            ->getValue();
          $old_hash = !empty($old_hash[0]['value']) ? $old_hash[0]['value'] : '';
          $hash = md5($xml);
          if ($old_hash !== $hash) {
            $job
              ->set('job_file_content_hash', $hash);

            // Set active state for all job items of a job in order to be able
            // force translation. It allows to override existing translations
            // that might be in an "Accepted" state.
            // @see JobItem::addTranslatedData() method.
            foreach ($job
              ->getItems() as $item) {
              $item
                ->setState(JobItemInterface::STATE_ACTIVE);
            }

            // Validation successful, start import.
            $job
              ->addTranslatedData($plugin
              ->import($file
              ->getFileUri(), $job));
            $job
              ->addMessage('Successfully imported file.');
            \Drupal::logger('tmgmt_smartling')
              ->info('Translation for "@filename" was successfully downloaded and imported.', [
              '@filename' => $filename,
            ]);
          }
          else {
            $job
              ->addMessage('Import of downloaded file was skipped: downloaded and existing translations are equal.');
            \Drupal::logger('tmgmt_smartling')
              ->warning('Translation for "@filename" was successfully downloaded but import was skipped: downloaded and existing translations are equal.', [
              '@filename' => $filename,
            ]);
          }
        } catch (Exception $e) {
          $job
            ->addMessage('File import failed with the following message: @message', [
            '@message' => $e
              ->getMessage(),
          ], 'error');
          \Drupal::logger('tmgmt_smartling')
            ->error('File import failed with the following message: @message', [
            '@message' => $e
              ->getMessage(),
          ]);
          return FALSE;
        }
      }
    }
  }
  return TRUE;
}

/**
 * Implements hook_theme().
 */
function tmgmt_smartling_theme() {
  return [
    'smartling_dashboard_link' => [
      'variables' => [
        'proj_id' => '',
        'file_name' => '',
      ],
    ],
    'tmgmt_smartling_xml_template' => [
      'path' => drupal_get_path('module', 'tmgmt_smartling') . '/templates',
      'template' => 'tmgmt-smartling-xml-template',
      'variables' => [
        'items' => NULL,
      ],
    ],
  ];
}

/**
 * Implements hook_views_data_alter().
 */
function tmgmt_smartling_views_data_alter(array &$data) {
  $data['tmgmt_job']['smartling_dashboard'] = array(
    'title' => t('Link to Smartling Dashboard'),
    'field' => array(
      'title' => t('Link to Smartling Dashboard'),
      //'help' => t('Flags a specific node type.'),
      'id' => 'tmgmt_smartling_dashboard_link',
    ),
  );
}

/**
 * Implements hook_views_pre_view().
 */
function tmgmt_smartling_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view
    ->id() === 'tmgmt_translation_all_job_items') {
    $handlers = $view
      ->getHandlers('field');
    foreach ($handlers as $name => $value) {
      $view
        ->removeHandler($view->current_display, 'field', $name);
    }
    $view
      ->addHandler($view->current_display, 'field', 'tmgmt_job_item', 'tmgmt_job_item_bulk_form', array(
      'id' => 'tmgmt_job_item_bulk_form',
      'table' => 'tmgmt_job_item',
      'field' => 'tmgmt_job_item_bulk_form',
      'group_type' => 'group',
      'label' => 'Bulk update',
      'hide_alter_empty' => 1,
      'action_title' => 'With selection',
      'include_exclude' => 'exclude',
      'selected_actions' => [],
      'entity_type' => 'tmgmt_job_item',
      'plugin_id' => 'bulk_form',
      'weight' => -10,
    ));
    foreach ($handlers as $name => $value) {
      $view
        ->addHandler($view->current_display, 'field', 'tmgmt_job_item', $name, $value);
    }
  }
  if ($view
    ->id() === 'tmgmt_job_overview') {
    $handlers = $view
      ->getHandlers('field');
    $view
      ->removeHandler($view->current_display, 'field', 'operations');
    $view
      ->addHandler($view->current_display, 'field', 'tmgmt_job', 'smartling_dashboard', array(
      'id' => 'smartling_dashboard',
      'table' => 'tmgmt_job',
      'field' => 'smartling_dashboard',
      'group_type' => 'group',
      'label' => 'Smartling',
      'hide_alter_empty' => 1,
      'selected_actions' => [],
      'entity_type' => 'tmgmt_job',
      'plugin_id' => 'tmgmt_smartling_dashboard_link',
      'weight' => -10,
    ));
    $view
      ->addHandler($view->current_display, 'field', 'tmgmt_job_item', 'operations', $handlers['operations']);
  }
}

/**
 * Implements hook_requirements().
 */
function tmgmt_smartling_requirements($phase) {
  $requirements = [];
  if ($phase == 'runtime') {
    $user_id = \Drupal::config('tmgmt.translator.smartling')
      ->get('settings.user_id');
    $token_secret = \Drupal::config('tmgmt.translator.smartling')
      ->get('settings.token_secret');
    if (empty($user_id) || empty($token_secret)) {
      $missing_settings = [];
      if (empty($user_id)) {
        $missing_settings[] = 'User ID';
      }
      if (empty($token_secret)) {
        $missing_settings[] = 'Token Secret';
      }
      $requirements['tmgmt_smartling'] = [
        'title' => t('Smartling'),
        'description' => t('Please set up missing settings for Smartling plugin at @page_url: @settings', [
          '@page_url' => Link::fromTextAndUrl(t('Smartling provider settings page'), Url::fromUri('internal:/admin/tmgmt/translators/manage/smartling', [
            'attributes' => [
              'target' => '_blank',
            ],
          ]))
            ->toString(),
          '@settings' => implode(', ', $missing_settings),
        ]),
        'severity' => REQUIREMENT_ERROR,
      ];
    }
  }
  return $requirements;
}

/**
 * Implements hook_entity_base_field_info().
 */
function tmgmt_smartling_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type
    ->id() === 'tmgmt_job') {
    $fields['job_file_content_hash'] = BaseFieldDefinition::create('string')
      ->setLabel(t('File content hash (md5)'))
      ->setSetting('max_length', 32)
      ->setTranslatable(FALSE);
    return $fields;
  }
}