wordsonline_connector-1.0.x-dev/wordsonline_connector.module

wordsonline_connector.module
<?php

/**
 * @file
 * This is the module to use WordsOnline Connector.
 */

use Drupal\wordsonline_connector\WordsOnlineConst;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\wordsonline_connector\Entity\WordsOnlineResponse;
use Drupal\wordsonline_connector\WordsOnlineMessage;
use Drupal\tmgmt\Entity\Job;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Request api.
 *
 * @param string $path
 *   Url.
 * @param string $method
 *   Method request.
 * @param array $params
 *   List Parameter.
 * @param string $token
 *   Token.
 *
 * @return string
 *   Response.
 */
function wordsonline_connector_request($path, $method = 'GET', array $params = [], $token = NULL) {
  $options = [];
  $url = WordsOnlineConst::API_URL . $path;
  $client = \Drupal::httpClient();
  try {
    if ($method == 'GET') {
      $options['query'] = $params;
    }
    else {
      $options['json'] = $params;
    }
    if ($token != NULL) {
      $options['headers'] = [
        'Authorization' => 'Bearer ' . $token,
        'Content-Type' => 'application/json',
        'Referer' => 'ClientAPI',
      ];
    }
    else {
      $options['headers'] = [
        'Content-Type' => 'application/json',
      ];
    }
    $response = $client->request($method, $url, $options);
  }
  catch (RequestException $e) {
    if (!$e->hasResponse()) {
      if ($e->getCode()) {
        return $e->getCode();
      }
      throw new TMGMTException(WordsOnlineMessage::UNABLE_TO_CONNECT_SERVICES, ['@error' => $e->getMessage()], $e->getCode());
    }
    $response = $e->getResponse();
    throw new TMGMTException(WordsOnlineMessage::UNABLE_TO_CONNECT_SERVICES, ['@error' => $response->getReasonPhrase()], $response->getStatusCode());
  }
  $received_data = $response->getBody()->getContents();
  if ($response->getStatusCode() != 200) {
    throw new TMGMTException(
      WordsOnlineMessage::UNABLE_TO_CONNECT_SERVICES_WITH_URL,
      [
        '@error' => $response->getStatusCode(),
        '@url' => $url,
      ]
    );
  }
  return $received_data;
}

/**
 * Get status code.
 *
 * @param string $method
 *   Method request.
 * @param array $params
 *   List Parameter.
 *
 * @return int
 *   Status.
 */
function wordsonline_connector_get_status_code($method, array $params = []) {
  $options = [];
  $url = WordsOnlineConst::API_URL . 'token';
  $client = \Drupal::httpClient();
  try {
    $options['form_params'] = $params;
    $options['headers'] = [
      'Content-Type' => 'application/x-www-form-urlencoded',
    ];
    $response = $client->request($method, $url, $options);
  }
  catch (RequestException $e) {
    if (!$e->hasResponse()) {
      if ($e->getCode()) {
        return $e->getCode();
      }
    }
    $response = $e->getResponse();
    throw new TMGMTException(
      WordsOnlineMessage::UNABLE_TO_CONNECT_SERVICES,
      [
        '@error' => $response->getReasonPhrase(),
      ],
      $response->getStatusCode()
    );
  }
  return $response->getStatusCode();
}

/**
 * Get token.
 *
 * @param string $method
 *   Method request.
 * @param array $params
 *   List Parameter.
 *
 * @return string
 *   Receive data.
 */
function wordsonline_connector_get_token($method, array $params = []) {
  $options = [];
  $url = WordsOnlineConst::API_URL . 'token';
  $client = \Drupal::httpClient();
  try {
    $options['form_params'] = $params;
    $options['headers'] = [
      'Content-Type' => 'application/x-www-form-urlencoded',
    ];
    $response = $client->request($method, $url, $options);
  }
  catch (RequestException $e) {
    if (!$e->hasResponse()) {
      if ($e->getCode()) {
        return $e->getCode();
      }
    }
    $response = $e->getResponse();
    throw new TMGMTException(
      WordsOnlineMessage::UNABLE_TO_CONNECT_SERVICES,
      [
        '@error' => $response->getReasonPhrase(),
      ],
      $response->getStatusCode()
    );
  }

  $received_data = $response->getBody()->getContents();
  return $received_data;
}

/**
 * Get quote.
 *
 * @param string $request_guid
 *   Method request.
 * @param string $token
 *   Token.
 *
 * @return string
 *   Receive data.
 */
function wordsonline_connector_get_quote($request_guid, $token) {
  $url = WordsOnlineConst::API_URL . 'Requests/'.$request_guid.'/Quote';
  $result = \Drupal::httpClient()->get(
    $url,
    [
      'headers' => [
        'Authorization' => 'Bearer ' . $token,
        'Accept' => 'application/json',
        'Referer' => 'ClientAPI',
      ],
      'timeout' => 3600,
    ]
  );
  if ($result->getStatusCode() == 200) {
    $data = json_decode($result->getBody()->getContents());
    return $data;
  }
  else {
    return new WordsOnlineResponse(NULL, -1, "B0001", "error");
  }
}

/**
 * Approve quote.
 *
 * @param string $request_guid
 *   Method request.
 * @param string $action
 *   Action.
 * @param string $due_date
 *   Due Date.
 * @param string $token
 *   Token.
 *
 * @return int
 *   Status.
 */
function wordsonline_connector_approve_quote($request_guid, $action, $due_date, $token) {
  $url = WordsOnlineConst::API_URL . 'Requests/'.$request_guid.'/Quote';
  $result = \Drupal::httpClient()->put(
    $url,
    [
      'headers' => [
        'Authorization' => 'Bearer ' . $token,
        'Accept' => 'application/json',
        'Referer' => 'ClientAPI',
      ],
      'json' => [
        'requestGuid' => $request_guid,
        'dueDate' => $due_date,
        'action' => $action,
      ],
      'timeout' => 3600,
    ]
  );
  if ($result->getStatusCode() == 200) {
    $data = json_decode($result->getBody()->getContents());
    if ($data->status != 1) {
      \Drupal::messenger()->addError($data->message);
    }
    return $data->status;
  }
  else {
    $received_data = json_decode($result->getBody()->getContents());
    $orderResponse = json_decode($received_data, TRUE);
    $err_msg = "Fail to confirm order";
    if ($orderResponse != NULL && $orderResponse['message'] != NULL) {
      $err_msg = $err_msg . "\r\n" . $orderResponse['message'];
    }
    \Drupal::messenger()->addError($err_msg);
    return -1;
  }
}

/**
 * Get list request files.
 *
 * @param string $request_guid
 *   Method request.
 * @param string $token
 *   Token.
 *
 * @return \Drupal\wordsonline_connector\Entity\WordsOnlineResponse
 *   Response.
 */
function wordsonline_connector_get_request_files_list($request_guid, $token) {
  $url = WordsOnlineConst::API_URL . 'requests/'.$request_guid.'/Files?requestGuid=' . $request_guid . '&filetype=3';
  $result = \Drupal::httpClient()->get(
    $url,
    [
      'headers' => [
        'Authorization' => 'Bearer ' . $token,
        'Accept' => 'application/json',
        'Referer' => 'ClientAPI',
      ],
    ]
  );
  if ($result->getStatusCode() == 200) {
    $data = json_decode($result->getBody()->getContents());
    return $data;
  }
  else {
    return new WordsOnlineResponse(NULL, -1, "B0001", "error");
  }
}

/**
 * Download file.
 *
 * @param string $request_guid
 *   Method request.
 * @param string $file_guid
 *   File guid.
 * @param string $token
 *   Token.
 *
 * @return string
 *   Content of file.
 */
function wordsonline_connector_download_file($request_guid, $file_guid, $token) {
  $url = WordsOnlineConst::API_URL . 'requests/'.$request_guid.'/Files/'.$file_guid.'/download';
  $result = \Drupal::httpClient()->get(
    $url,
    [
      'headers' => [
        'Authorization' => 'Bearer ' . $token,
        'Referer' => 'ClientAPI',
      ],
    ]
  );
  if ($result->getStatusCode() == 200) {
    $data = $result->getBody();
    return $data;
  }
  else {
    return NULL;
  }
}

/**
 * Update status for request.
 *
 * @param string $request_guid
 *   Method request.
 * @param string $action
 *   Action.
 * @param string $description
 *   Description.
 * @param string $token
 *   Token.
 *
 * @return int
 *   Status.
 */
function wordsonline_connector_request_action($request_guid, $action, $description, $token) {
  $url = WordsOnlineConst::API_URL . 'requests/'.$request_guid.'/Actions';
  $result = \Drupal::httpClient()->post(
    $url,
    [
      'headers' => [
        'Authorization' => 'Bearer ' . $token,
        'Accept' => 'application/json',
        'Referer' => 'ClientAPI',
      ],
      'json' => [
        'requestGuid' => $request_guid,
        'description' => $description,
        'action' => $action,
      ],
      'timeout' => 3600,
    ]
  );
  if ($result->getStatusCode() == 200) {
    $data = json_decode($result->getBody()->getContents());
    if ($data->status != 1) {
      \Drupal::messenger()->addError($data->message);
    }
    return $data->status;
  }
  else {
    $received_data = json_decode($result->getBody()->getContents());
    $orderResponse = json_decode($received_data, TRUE);
    $err_msg = "Can't update request action";
    if ($orderResponse != NULL && $orderResponse['message'] != NULL) {
      $err_msg = $err_msg . "\r\n" . $orderResponse['message'];
    }
    \Drupal::messenger()->addError($err_msg);
    return -1;
  }
}


/**
 * Get error message.
 *
 * @param string $xmlData
 *   Xml content.
 *
 * @return string
 *   Error message.
 */
function wordsonline_connector_get_error_message($xmlData) {
  libxml_clear_errors();
  libxml_use_internal_errors(TRUE);
  $importedXML = simplexml_load_string($xmlData);
  $errors = libxml_get_errors();
  if ($importedXML === FALSE) {
    $messages = 'The imported file is not a valid XML.';
    if($errors){
      $messages .= "\r\n" . json_encode($errors);
    }
    return $messages;
  }
  $xml = $importedXML->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:1.2');
  $phase = $importedXML->xpath("//xliff:phase[@phase-name='extraction']");
  if ($phase) {
    $phase = reset($phase);
  }
  else {
    $messages = 'The imported file is missing required XLIFF phase information.';
    if($errors){
      $messages .= "\r\n" . json_encode($errors);
    }
    return $messages;
  }
  // Check if the job has a valid job reference.
  if (!isset($phase['job-id'])) {
    $messages = 'The imported file does not contain a job reference.';
    if($errors){
      $messages .= "\r\n" . json_encode($errors);
    }
    return $messages;
  }
  // Attempt to load the job if none passed.
  $job = (Job::load((int) $phase['job-id']));
  if (empty($job)) {
    $messages = "The imported file job id " . $phase['job-id'] . " is not available.";
    if($errors){
      $messages .= "\r\n" . json_encode($errors);
    }
    return $messages;
  }
  // Compare source language.
  if (!isset($xml->file['source-language']) || $job->getRemoteSourceLanguage() != $xml->file['source-language']) {
    $file_language = empty($xml->file['source-language']) ? t('none') : $xml->file['source-language'];
    $messages = 'The imported file source language ' . $file_language . ' does not match the job source language ' . $job->getRemoteSourceLanguage() . '.';
    if($errors){
      $messages .= "\r\n" . json_encode($errors);
    }
    return $messages;
  }
  // Compare target language.
  if (!isset($xml->file['target-language']) || $job->getRemoteTargetLanguage() != $xml->file['target-language']) {
    $file_language = empty($xml->file['target-language']) ? t('none') : $xml->file['target-language'];
    $messages = 'The imported file target language ' . $file_language . ' does not match the job target language ' . $job->getRemoteTargetLanguage() . '.';
    if($errors){
      $messages .= "\r\n" . json_encode($errors);
    }
    return $messages;
  }
  return json_encode($errors);
}

/**
 * Get request name.
 *
 * @return string
 *   Request name.
 */
function wordsonline_connector_get_request_name() {
  $date = new DrupalDateTime();
  $text = $date->format('YmdHis');
  return 'drupal' . $text;
}

/**
 * Implements hook_page_attachments().
 */
function wordsonline_connector_page_attachments(array &$attachments) {
  if (\Drupal::service('router.admin_context')->isAdminRoute()) {
    $attachments['#attached']['library'][] = 'wordsonline_connector/wordsonline_global';
  }
}

/**
 * Implements hook_help().
 */
function wordsonline_connector_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.wordsonline_connector':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The WordsOnline Drupal Connector module provides a tool set for translating content from different sources. The translation can be done by people or translation services of all kinds. It builds on and uses existing language tools and data structures in Drupal and can be used in automated workflow scenarios. For more information, see the online handbook entry for the WordsOnline Drupal Connector module.') . '</p>';
      return $output;
  }

}

/**
 * Implements hook_cron().
 */
function wordsonline_connector_cron() {
  $translator_manager = \Drupal::service('plugin.manager.tmgmt.wordsonline');
  $translator_manager->translate();

}

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

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