lionbridge_translation_provider-8.x-2.4/tmgmt_contentapi/src/ContentApiTranslatorUI.php
tmgmt_contentapi/src/ContentApiTranslatorUI.php
<?php
namespace Drupal\tmgmt_contentapi;
use Drupal\Component\Utility\Html;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
use Drupal\tmgmt\Entity\Job;
use Drupal\tmgmt\JobInterface;
use Drupal\tmgmt\JobItemInterface;
use Drupal\tmgmt\TranslatorPluginUiBase;
use Drupal\tmgmt_contentapi\Swagger\Client\Api\JobApi;
use Drupal\tmgmt_contentapi\Swagger\Client\Api\ProviderApi;
use Drupal\tmgmt_contentapi\Swagger\Client\Api\RequestApi;
use Drupal\tmgmt_contentapi\Swagger\Client\Api\TokenApi;
use Drupal\tmgmt_contentapi\Swagger\Client\ApiException;
use Drupal\tmgmt_contentapi\Swagger\Client\Configuration;
use Drupal\tmgmt_contentapi\Swagger\Client\Model\ArrayOfRequestIds;
use Drupal\tmgmt_contentapi\Swagger\Client\Model\ArrayOfRequestIdsNote;
use Drupal\tmgmt_contentapi\Swagger\Client\Model\Request;
use GuzzleHttp\Exception\RequestException;
// Use the new FormHelper namespace for the analysis code helper.
use Drupal\tmgmt_contentapi\FormHelper\ContentApiAnalysisCodeFormHelper;
/**
* Freeway File translator UI.
*/
class ContentApiTranslatorUI extends TranslatorPluginUiBase {
/**
* {@inheritdoc}
*/
#[\ReturnTypeWillChange]
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
/** @var \Drupal\tmgmt\TranslatorInterface $translator */
$prevHost = '';
$translator = $form_state->getFormObject()->getEntity();
$capisettings = $translator->getSetting('capi-settings');
$cronsettings = $translator->getSetting('cron-settings');
$exportsettings = $translator->getSetting('export_format');
$transfersettings = $translator->getSetting('transfer-settings');
$empty_code_analysis_settings = [
'freeway_auth_url' => '',
'freeway_service_url' => '',
'analysis_code_username' => '',
'analysis_code_password' => ''
];
$codeanalysissettings = $translator->getSetting('code-analysis-settings') ?? $empty_code_analysis_settings;
$tmpSettings = \Drupal::service('config.factory')->getEditable('tmgmt.translator.contentapi');
if (array_key_exists("settings", $form_state->getUserInput()) && array_key_exists("capi-settings", $form_state->getUserInput()["settings"])) {
$capisettings["capi_username_ctt"] = $form_state->getUserInput()["settings"]["capi-settings"]["capi_username_ctt"];
$capisettings["capi_password_ctt"] = $form_state->getUserInput()["settings"]["capi-settings"]["capi_password_ctt"];
if ($form_state->getUserInput()["settings"]["capi-settings"]["capi_host"] != NULL && $form_state->getUserInput()["settings"]["capi-settings"]["capi_host"] != '') {
$capisettings["capi_host"] = $form_state->getUserInput()["settings"]["capi-settings"]["capi_host"];
if (
$tmpSettings->get('settings.capi-settings') == NULL
|| !array_key_exists('capi_host', $tmpSettings->get('settings.capi-settings'))
||
(
$capisettings["capi_host"] != ""
&&
$tmpSettings->get('settings.capi-settings.capi_host') != $capisettings["capi_host"]
)
) {
$prevHost = ($tmpSettings->get('settings.capi-settings.capi_host') != NULL ? $tmpSettings->get('settings.capi-settings.capi_host') : '');
$tmpSettings->set('settings.capi-settings.capi_host', $capisettings["capi_host"]);
$tmpSettings->save();
}
}
}
$token = '';
$capi = new TokenApi();
if (!empty($capisettings['capi_username_ctt'])) {
try {
$token = $capi->generateNewToken($capisettings["capi_username_ctt"], $capisettings["capi_password_ctt"]);
}
catch (\Exception $ew) {
}
}
$form['export_format'] = [
'#type' => 'radios',
'#title' => t('Export to'),
'#options' => \Drupal::service('plugin.manager.tmgmt_contentapi.format')->getLabels(),
'#default_value' => $exportsettings ?? "contentapi_xlf",
'#description' => t('Select the format for exporting data.'),
];
$form['xliff_cdata'] = [
'#type' => 'checkbox',
'#title' => t('XLIFF CDATA'),
'#description' => t('Select to use CDATA for import/export.'),
'#default_value' => $translator->getSetting('xliff_cdata'),
];
$form['xliff_processing'] = [
'#type' => 'checkbox',
'#title' => t('Extended XLIFF processing'),
'#description' => t('Select to further process content semantics and mask HTML tags instead of just escaping them.'),
'#default_value' => $translator->getSetting('xliff_processing'),
];
$form['xliff_message'] = [
'#type' => 'container',
'#markup' => t('By selecting CDATA option, XLIFF processing will be ignored.'),
'#attributes' => [
'class' => ['messages messages--warning'],
],
];
$form['allow_override'] = [
'#type' => 'checkbox',
'#title' => t('Allow export-format overrides'),
'#default_value' => $translator->getSetting('allow_override'),
];
$form['one_export_file'] = [
'#type' => 'checkbox',
'#title' => t('Use one export file for all items in job'),
'#description' => t('Select to export all items to one file. Clear to export items to multiple files.'),
'#default_value' => $translator->getSetting('one_export_file'),
];
// Any visible, writeable wrapper can potentially be used for the files.
// directory, including a remote file system that integrates with a CDN.
foreach (\Drupal::service('stream_wrapper_manager')->getDescriptions(StreamWrapperInterface::WRITE_VISIBLE) as $scheme => $description) {
$options[$scheme] = Html::escape($description);
}
if (!empty($options)) {
$form['scheme'] = [
'#type' => 'radios',
'#title' => t('Download method'),
'#default_value' => $translator->getSetting('scheme'),
'#options' => $options,
'#description' => t('Choose where to store exported files. Recommendation: Use a secure location to prevent unauthorized access.'),
];
}
$process_method_options = ["Quick Scan", "Failsafe scan"];
$form['process_method'] = [
'#type' => 'radios',
'#title' => t('Import Process'),
'#default_value' => ($translator->getSetting('process_method')) ? $translator->getSetting('process_method') : 0,
'#options' => $process_method_options,
'#description' => t('Choose the method to import the job item <br/> Quick scan over the reported changes from our systems, where the failsafe scans for all the info in the translation jobs.'),
];
$form['capi-settings'] = [
'#type' => 'details',
'#title' => t('Lionbridge Content API Settings'),
'#open' => TRUE,
];
$form['capi-settings']['po_reference'] = [
'#type' => 'textfield',
'#title' => t('PO Number'),
'#required' => FALSE,
'#description' => t('Enter your Lionbridge purchase order number.'),
'#default_value' => $capisettings['po_reference'] ?? '',
];
$form['capi-settings']['capi_username_ctt'] = [
'#type' => 'textfield',
'#title' => t('Client ID'),
'#required' => TRUE,
'#description' => t('Enter your Lionbridge client id.'),
'#default_value' => $capisettings['capi_username_ctt'] ?? '',
];
$form['capi-settings']['capi_password_ctt'] = [
'#type' => 'textfield',
'#title' => t('Client Secret ID'),
'#required' => TRUE,
'#description' => t('Enter your Lionbridge client secret id.'),
'#default_value' => $capisettings['capi_password_ctt'] ?? '',
];
$form['capi-settings']['capi_host'] = [
'#type' => 'textfield',
'#title' => t('Host'),
'#required' => TRUE,
'#description' => t('Default value: https://contentapi.lionbridge.com/v2 <br> Staging value: https://content-api.staging.lionbridge.com/v2'),
'#default_value' => $capisettings['capi_host'] ?? 'https://contentapi.lionbridge.com/v2',
];
$form['capi-settings'] += parent::addConnectButton();
$providers = NULL;
if (isset($token) && $token != '') {
try {
$providerapi = new ProviderApi();
$providers = $providerapi->providersGet($token);
if ($prevHost != '') {
$tmpSettings->set('settings.capi-settings.capi_host', $prevHost);
$tmpSettings->save();
}
}
catch (\Exception $e) {
// Add logger.
\DRUPAL::logger('TMGMT_CONTENTAPI')->error("Failed to fetch providers : " . $e->getMessage());
}
}
$providersarray = [];
if (!empty($providers)) {
foreach ($providers as $provider) {
$prid = $provider->getProviderId();
$prname = $provider->getProviderName();
$providersarray[$prid] = $prname;
}
}
asort($providersarray, SORT_REGULAR);
$defaultprovidervalue = $capisettings['provider'] ?? '';
// Do not allow to set same provider for multiple translators, during creation and editing.
$providersarray = \DRUPAL::service('tmgmt_contentapi.capi_details')->popOutAlredyConfiguredProvider($providersarray, $defaultprovidervalue);
$form['capi-settings']['provider'] = [
'#type' => 'select',
'#title' => t('Provider configuration'),
'#required' => FALSE,
'#options' => $providersarray,
'#default_value' => $defaultprovidervalue,
'#description' => t('Please select a Provider for your project.'),
];
$form['capi-settings']['allow_provider_override'] = [
'#type' => 'checkbox',
'#title' => t('Allow provider overrides'),
'#default_value' => $translator->getSetting('capi-settings')['allow_provider_override'] ?? '',
];
$form['transfer-settings'] = [
'#type' => 'checkbox',
'#title' => t('Transfer all files as zip'),
'#description' => t('Select to transfer all exported files for a job as a .zip file.'),
'#default_value' => $transfersettings,
];
$form['cron-settings'] = [
'#type' => 'details',
'#title' => t('Scheduled Tasks'),
'#description' => t('Specify settings for scheduled tasks.'),
'#open' => TRUE,
];
$form['cron-settings']['status'] = [
'#type' => 'checkbox',
'#title' => t('Auto Import Job'),
'#description' => t('Select to auto import job, by scheduled task. Clear to download translated jobs manually.'),
'#default_value' => $cronsettings['status'] ?? '',
];
// Replace the inlined code-analysis-settings section and use the helper instead.
$form = ContentApiAnalysisCodeFormHelper::buildFormSection($form, $form_state, $codeanalysissettings);
return $form;
}
/**
* {@inheritdoc}
*/
#[\ReturnTypeWillChange]
public function checkoutSettingsForm(array $form, FormStateInterface $form_state, JobInterface $job) {
$valid_provider = $this->getValidProvider($form, $form_state, $job);
$translator = $job->getTranslator();
$capisettings = $translator->getSetting('capi-settings');
$jobcapisettings = $job->getSetting("capi-settings");
$exportsettingstranslator = $job->getTranslator()->getSetting('export_format');
$exportsettings = NULL;
if ($job->getSetting('exports-settings') != NULL && array_key_exists('cpexport_format', $job->getSetting('exports-settings'))) {
$exportsettings = $job->getSetting('exports-settings')['cpexport_format'];
}
$allowprovideroverride = $capisettings['allow_provider_override'];
$dt = DrupalDateTime::createFromTimestamp(time());
$date = $dt->modify('+ 14 days');
$form['exports-settings'] = [
'#type' => 'details',
'#title' => t('Export Settings'),
'#open' => TRUE,
];
$form['exports-settings']['cpexport_format'] = [
'#type' => 'radios',
'#title' => t('Export to'),
'#options' => \Drupal::service('plugin.manager.tmgmt_contentapi.format')->getLabels(),
'#default_value' => $exportsettings ?? $exportsettingstranslator,
'#description' => t('Select the format for exporting data.'),
];
$form['capi-settings'] = [
'#type' => 'details',
'#title' => t('Content API Job Details'),
'#open' => TRUE,
];
$form['capi-settings']['po_reference'] = [
'#type' => 'textfield',
'#title' => t('PO Reference'),
'#required' => FALSE,
'#description' => t('Please enter your PO Reference'),
'#default_value' => $jobcapisettings["po_reference"] ?? $capisettings['po_reference'],
];
$form['capi-settings']['description'] = [
'#type' => 'textarea',
'#title' => t('Description'),
'#required' => FALSE,
'#description' => t('Please enter a description for the job.'),
'#default_value' => $jobcapisettings["description"] ?? '',
];
$form['capi-settings']['due_date'] = [
'#type' => 'datetime',
'#title' => t('Expected Due Date'),
'#required' => FALSE,
'#date_date_format' => 'Y-m-d',
'#date_time_format' => 'H:i',
'#description' => t('Please enter the expected due date.'),
'#default_value' => $jobcapisettings["due_date"] ?? $date,
];
$form['capi-settings']['task'] = [
'#type' => 'select',
'#title' => t('Task'),
'#options' => ["trans" => "Translation"],
'#default_value' => $jobcapisettings["task"] ?? 'trans',
'#description' => t('Please select a task for your project.'),
];
$token = \DRUPAL::service('tmgmt_contentapi.capi_details')->getCapiToken($translator);
$providers = NULL;
try {
$providerapi = new ProviderApi();
$providers = $providerapi->providersGet($token);
}
catch (\Exception $e) {
$form_state->setErrorByName('settings][capi-settings][capi_host', $msg);
}
$providersarray = [];
foreach ($providers as $provider) {
$prid = $provider->getProviderId();
$prname = $provider->getProviderName();
$providersarray[$prid] = $prname;
}
asort($providersarray, SORT_REGULAR);
$form['capi-settings']['provider'] = [
'#type' => 'select',
'#title' => t('Provider configuration'),
'#required' => TRUE,
'#options' => $providersarray,
'#default_value' => $valid_provider ?? '',
'#description' => t('Please select a Provider for your project.'),
'#ajax' => [
'callback' => 'tmgmt_contentapi_ajax_provider_changed',
'wrapper' => 'quote',
],
];
if (!$allowprovideroverride) {
$form['capi-settings']['provider']['#attributes']['disabled'] = 'disabled';
}
$analysis_code = \Drupal::service('tmgmt_contentapi.analysis_code_api')->verifyAndGenerateAnalysisCodeSelect($translator);
if (isset($analysis_code) && !empty($analysis_code)) {
$form['capi-settings']['analysis_code'] = [
'#type' => 'details',
'#title' => t('Analysis Code'),
'#description' => t('Please select an Analysis Code for the job.'),
'#prefix' => '<div id="analysis_code">',
'#suffix' => '</div>',
'#open' => TRUE,
];
foreach ($analysis_code as $level => $section) {
$level_number = explode('_', $level)[1];
foreach ($section as $key => $value) {
$form['capi-settings']['analysis_code'][$key . '_' . $level_number] = [
// Allow empty values, so that the user can select nothing.
'#empty_value' => '',
'#type' => 'select',
'#title' => $key,
'#options' => $value,
'#required' => TRUE,
];
}
}
}
$form['capi-settings']['quote'] = [
'#type' => 'container',
'#prefix' => '<div id="quote">',
'#suffix' => '</div>',
];
if (isset($valid_provider)) {
$form['capi-settings']['quote']['supported_languages'] = [
'#type' => 'details',
'#title' => t('Supported Languages'),
'#open' => FALSE,
'#description' => t('Supported language pairs by the selected provider.'),
];
$providerapi = new ProviderApi();
$rows = [];
$header = [t('source languages'), t('target languages')];
try {
$selected_provider = $providerapi->providersProviderIdGet($token, $valid_provider);
$capabilities = $selected_provider->getCapabilities();
$supported_lang_pairs = isset($capabilities) ? $capabilities->getSupportedLanguages() : [];
foreach ($supported_lang_pairs as $pair) {
$rows[] = [
implode(',', isset($pair) ? $pair->getSources() : []),
implode(',', isset($pair) ? $pair->getTargets() : NULL)
];
}
}
catch (ApiException $ex) {
$rows[] = [$ex->getMessage()];
}
$form['capi-settings']['quote']['supported_languages']['lang_table'] = [
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' => t('No language specific settings defined for the selected provider.')
];
$form['capi-settings']['quote']['is_quote'] = [
'#type' => 'checkbox',
'#title' => t('Quote'),
'#description' => t('Check to receive a quote before translation starts. Quote has to be approved in order to start the translation'),
'#default_value' => 0,
];
// Check if the selected provider supports quote.
$supportsQuote = isset($capabilities) ? $capabilities->getSupportQuote() : FALSE;
if (!$supportsQuote) {
$form_values = $form_state->getValues();
$form_user_input = $form_state->getUserInput();
$form_values['settings']['capi-settings']['quote']['is_quote'] = 0;
$form_user_input['settings']['capi-settings']['quote']['is_quote'] = FALSE;
$form_state->setValues($form_values);
$form_state->setUserInput($form_user_input);
$form['capi-settings']['quote']['is_quote']['#attributes'] = ['disabled' => TRUE];
}
else {
unset($form['capi-settings']['quote']['is_quote']['#attributes']['disabled']);
}
}
return parent::checkoutSettingsForm($form, $form_state, $job);
}
/**
* Function to get valid provider.
*
* @param array $form
* Form to process.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* Current form state.
* @param \Drupal\tmgmt\JobInterface $job
* Job object.
*/
#[\ReturnTypeWillChange]
public function getValidProvider(array $form, FormStateInterface &$form_state, JobInterface $job) {
// Can be triggered by translator, provider dropdown, language drop down, request translation, submit button in job overview.
$who_triggered = $form_state->getTriggeringElement();
$values = $form_state->getValues();
$form_user_input = $form_state->getUserInput();
$trigger_name = isset($who_triggered) ? $who_triggered['#name'] : NULL;
$translator = $job->getTranslator();
// We need this, otherwise when new jobs are submitted and no translator saved, ajax causes problems when switching translator
// TMGMT bug?
$job->save();
$capisettings = $translator->getSetting('capi-settings');
$jobcapisettings = $job->getSetting("capi-settings");
$translator_provider_id = isset($capisettings) ? $capisettings['provider'] : NULL;
$job_provider_id = isset($values) && isset($values['settings']['capi-settings']['provider']) ?
$values['settings']['capi-settings']['provider'] : $translator_provider_id;
switch ($trigger_name) {
case 'translator':
$values['settings']['capi-settings']['provider'] = $translator_provider_id;
$form_user_input['settings']['capi-settings']['provider'] = $translator_provider_id;
$form_state->setValues($values);
$form_state->setUserInput($form_user_input);
return $translator_provider_id;
default:
$values['settings']['capi-settings']['provider'] = $job_provider_id;
$form_user_input['settings']['capi-settings']['provider'] = $job_provider_id;
$form_state->setValues($values);
$form_state->setUserInput($form_user_input);
return $job_provider_id;
}
}
/**
* {@inheritdoc}
*/
#[\ReturnTypeWillChange]
public function checkoutInfo(JobInterface $job) {
$requestobjs = unserialize($job->getSetting("capi-remote"));
// Get the first key from the requestobjs array
$first_key = !empty($requestobjs) ? array_key_first($requestobjs) : null;
$date = $job->getSetting('capi-settings')['due_date'];
// $duedate = $date->format('Y-m-d h:i');
$due_date = date('Y-m-d\TH:i:s.000') . 'Z';
$translator = $job->getTranslator();
$token = \DRUPAL::service('tmgmt_contentapi.capi_details')->getCapiToken($translator);
$providers = NULL;
$providersarray = [];
// Check if we have any request and take from first jobid.
$task = $job->getSetting('capi-settings')['task'];
$capijobid = NULL;
if ($task == 'trans') {
$capijobid = isset($requestobjs[$first_key]) && count($requestobjs) > 0 ? reset($requestobjs[$first_key])->getJobId() : NULL;
}
else {
$job->setState(Job::STATE_FINISHED);
$capijobid = isset($requestobjs[$first_key]) && count($requestobjs) > 0 ? $requestobjs[$first_key]->getJobId() : NULL;
}
$form = [];
$projectInfo = NULL;
if ($job->getState() > Job::STATE_UNPROCESSED) {
$jobapi = new JobApi();
$find_job = $jobapi->FindJob($token, $capijobid);
try {
$jobapi = new JobApi();
$projectInfo = $jobapi->jobsJobIdGet($token, $capijobid, "fullWithStats");
// Get job status on detail page.
$job_local_details = \Drupal::service('tmgmt_contentapi.capi_data_processor')->getGlobalColumnInfoForJobOverview($job->id(), TRUE);
$jobstatus = $job_local_details['overall_job_status'];
if (isset($token) && $token != '') {
try {
$providerapi = new ProviderApi();
$providers = $providerapi->providersGet($token);
foreach ($providers as $provider) {
$prid = $provider->getProviderId();
$prname = $provider->getProviderName();
$providersarray[$prid] = $prname;
}
}
catch (\Exception $e) {
$msg = $e->getMessage();
if (strlen($msg) > 200) {
$msg = substr($msg, 0, 200);
}
\Drupal::messenger()->addMessage($msg);
}
}
}
catch (ApiException $ex) {
$respbody = $ex->getResponseBody();
if (strlen($respbody) > 200) {
$respbody = substr($respbody, 0, 200);
}
\Drupal::messenger()->addMessage('The API returned an error. ' . $respbody, 'warning');
$projectInfo = NULL;
}
catch (\Exception $ex) {
$respbody = $ex->getMessage();
if (strlen($respbody) > 200) {
$respbody = substr($respbody, 0, 200);
}
\Drupal::messenger()->addMessage('The API returned an error. ' . $respbody, 'warning');
$projectInfo = NULL;
}
}
$cpodername = 'n/a';
$cporderid = 'n/a';
$cpstatuscode = 'n/a';
$lateerror = 'n/a';
$providerid = 'n/a';
$poreference = 'n/a';
$duedate = NULL;
$archived = 'n/a';
$description = 'n/a';
$jobstats = NULL;
if ($projectInfo != NULL) {
$cpodername = $projectInfo->getJobName();
$cporderid = $projectInfo->getJobId();
$cpstatuscode = $jobstatus;
// $projectInfo->getLatestErrorMessage();
$lateerror = '';
$providerid = $providersarray[$projectInfo->getProviderId()] . '<br>( ' . $projectInfo->getProviderId() . ' )';
$poreference = $projectInfo->getPoReference();
$duedate = date('Y-m-d h:i', strtotime($date));
$archived = $projectInfo->getArchived() ? "TRUE" : "FALSE";
$description = $projectInfo->getDescription();
$jobstats = $projectInfo->getJobStats();
$requestApi = new RequestApi();
$allRequests = $requestApi->jobsJobIdRequestsGet($token, $capijobid);
foreach ($allRequests as $instRequest) {
if ($instRequest->getLatestErrorMessage() != NULL && $instRequest->getLatestErrorMessage() != '') {
$lateerror = $instRequest->getLatestErrorMessage();
}
}
}
$this->createCpOrderForm(
$form,
$cpodername,
$cporderid,
$cpstatuscode,
$description,
$poreference,
$duedate,
$providerid,
$lateerror,
$archived,
$jobstats
);
if ($task == 'trans') {
$form['fw-immport-palaceholder'] = [
'#prefix' => '<div id="fw-im-placholder">',
'#suffix' => '</div>',
];
if ($projectInfo != NULL && $projectInfo->getShouldQuote()) {
$form['fw-immport-palaceholder']['quote-info'] = [
'#prefix' => '<div role="contentinfo" aria-label="Warning message" class="messages messages--warning">'
. '<div role="alert"><h2 class="visually-hidden">Warning message</h2>',
'#markup' => t('This job was submitted for a quote. To submit your job for processing, you must log into your translation provider\'s system to approve this quote.
'),
'#suffix' => '</div></div>'
];
}
$form['fw-immport-palaceholder']['fieldset-import'] = [
'#type' => 'fieldset',
'#title' => t('IMPORT TRANSLATED FILE'),
'#collapsible' => TRUE,
];
$form['fw-immport-palaceholder']['fieldset-import']['automatic-import'] = [
'#type' => 'details',
'#title' => t('Import'),
'#open' => TRUE,
'#description' => t('Click the below "Sync and Import" button to sync the job and import if its ready to import.'),
];
$form['fw-immport-palaceholder']['fieldset-import']['automatic-import']['auto-submit'] = [
'#type' => 'submit',
'#value' => t('Sync and Import'),
'#submit' => ['tmgmt_contentapi_semi_import_form_submit'],
];
$form['fw-immport-palaceholder']['fieldset-import']['automatic-import']['tm-update'] = [
'#type' => 'submit',
'#value' => t('Update TM'),
'#submit' => ['tmgmt_contentapi_update_tm_form_submit'],
];
$form['fw-immport-palaceholder']['fieldset-import']['manual-import'] = [
'#type' => 'details',
'#title' => t('Manual Import'),
'#open' => TRUE,
];
$form['fw-immport-palaceholder']['fieldset-import']['manual-import']['file'] = [
'#type' => 'managed_file',
'#title' => t('File'),
'#upload_location' => 'temporary://',
'#description' => t('Supported formats: .xlf, .zip.'),
'#upload_validators' => [
'FileExtension' => ['extensions' => 'zip xlf'],
],
];
$queue_name = \Drupal::service('tmgmt_contentapi.import_job')::QUEUE_NAME_IMPORT_JOBS_MANUALLY;
$queue_item_details = \Drupal::service('tmgmt_contentapi.import_job')->calculateRemainingItems($job->id(), $queue_name);
if ($queue_item_details['allowed_upload']) {
$form['fw-immport-palaceholder']['fieldset-import']['manual-import']['submit'] = [
'#type' => 'submit',
'#value' => t('Manual Import'),
'#submit' => ['tmgmt_contentapi_import_form_submit'],
'#validate' => ['tmgmt_contentapi_check_empty_file']
];
}
else {
$form['fw-immport-palaceholder']['fieldset-import']['manual-import']['message'] = [
'#type' => 'markup',
'#markup' => '<p>Manual import is in progress ' . $queue_item_details['remaining_items'] . ' processed out of ' . $queue_item_details['total_items'] . '</p>',
];
}
}
return $form;
}
/**
* Function to create order form.
*/
#[\ReturnTypeWillChange]
public function createCpOrderForm(&$fieldset, $ordername, $orderid, $orderstatus, $description, $poreference, $duedate, $providerid, $errors, $archived, $jobstats) {
$fieldset['fw-table'] = [
'#prefix' => '<table class="views-table views-view-table cols-8"><thead>
<tr>
<th>Job Name</th>
<th>Job ID</th>
<th>Job Status</th>
<th>Description</th>
<th>PO Number</th>
<th>Due Date</th>
<th>Provider ID</th>
<th>Latest Error</th>
<th>Archived</th>
<th>Statistics</th>
</tr></thead>',
'#suffix' => '</table>',
];
$fieldset['fw-table']['first-row'] = [
'#prefix' => '<tr>',
'#suffix' => '</tr>'
];
$fieldset['fw-table']['first-row']['ordername'] = [
'#prefix' => '<td>',
'#markup' => $ordername,
'#suffix' => '</td>'
];
$fieldset['fw-table']['first-row']['id'] = [
'#prefix' => '<td>',
'#markup' => $orderid,
'#suffix' => '</td>'
];
$fieldset['fw-table']['first-row']['status'] = [
'#prefix' => '<td>',
'#markup' => $orderstatus,
'#suffix' => '</td>'
];
$fieldset['fw-table']['first-row']['description'] = [
'#prefix' => '<td>',
'#markup' => $description,
'#suffix' => '</td>'
];
$fieldset['fw-table']['first-row']['po-reference'] = [
'#prefix' => '<td>',
'#markup' => $poreference,
'#suffix' => '</td>'
];
$fieldset['fw-table']['first-row']['due-date'] = [
'#prefix' => '<td>',
'#markup' => isset($duedate) && $duedate !== NULL ? $duedate : "n/a",
'#suffix' => '</td>'
];
$fieldset['fw-table']['first-row']['provider-id'] = [
'#prefix' => '<td>',
'#markup' => $providerid,
'#suffix' => '</td>'
];
$fieldset['fw-table']['first-row']['error'] = [
'#prefix' => '<td>',
'#markup' => $errors,
'#suffix' => '</td>'
];
$fieldset['fw-table']['first-row']['archived'] = [
'#prefix' => '<td>',
'#markup' => $archived,
'#suffix' => '</td>'
];
$fieldset['fw-table']['first-row']['statistics'] = [
'#prefix' => '<td>',
'#markup' => $this->createMarkupForStats($jobstats),
'#suffix' => '</td>'
];
}
/**
* Function to create markup for stats.
*/
#[\ReturnTypeWillChange]
public function createMarkupForStats($stats) {
$markup = "";
if (isset($stats)) {
$totalcompleted = t("total completed: ") . $stats->getTotalCompleted();
$totalintrans = t("total in translation: ") . $stats->getTotalInTranslation();
$totalreceived = t("total received: ") . $stats->getTotalReceived();
$totalerrors = t("total errors: ") . $stats->getTotalError();
$markup += "<p>" . $totalcompleted . "</p>";
$markup += "<p>" . $totalreceived . "</p>";
$markup += "<p>" . $totalintrans . "</p>";
$markup += "<p>" . $totalerrors . "</p>";
}
return $markup;
}
/**
* {@inheritdoc}
*/
#[\ReturnTypeWillChange]
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
// Nothing to do here by default.
$whotriggered = $form_state->getTriggeringElement();
$typeofTrigger = $whotriggered['#type'];
$prevHost = "";
$providers = [];
$tmpSettings = \Drupal::service('config.factory')->getEditable('tmgmt.translator.contentapi');
if ($typeofTrigger != 'select') {
try {
$logonError = FALSE;
$endpointError = FALSE;
$translator = $form_state->getFormObject()->getEntity();
$capisettings = $translator->getSetting('capi-settings');
$settings = $form_state->getValue('settings');
$capisettings = $settings['capi-settings'];
$username = $capisettings['capi_username_ctt'];
$password = $capisettings['capi_password_ctt'];
$tokenobj = NULL;
$providerapi = new ProviderApi();
$host = $capisettings['capi_host'];
$config = new Configuration();
$config->setHost($host);
$capi = new TokenApi();
$capiSettingsData = $tmpSettings->get('settings.capi-settings') ?: [];
if (
!array_key_exists('capi_host', $capiSettingsData )
||
(
$capisettings["capi_host"] != ""
&&
$tmpSettings->get('settings.capi-settings.capi_host') != $capisettings["capi_host"]
)
) {
$prevHost = $tmpSettings->get('settings.capi-settings.capi_host');
$tmpSettings->set('settings.capi-settings.capi_host', $capisettings["capi_host"]);
$tmpSettings->save();
}
try {
$tokenobj = $capi->generateNewToken($username, $password);
}
catch (RequestException $ex) {
$logonError = TRUE;
throw $ex;
}
catch (ApiException $ex) {
$logonError = TRUE;
throw $ex;
}
try {
$providers = $providerapi->providersGet($tokenobj);
}
catch (RequestException $ex) {
$endpointError = TRUE;
throw $ex;
}
catch (ApiException $ex) {
$endpointError = TRUE;
throw $ex;
}
$form_state->setValue(['settings', 'capi-settings', 'token'], $tokenobj);
$capisettings['token'] = $tokenobj;
$translator->setSetting('capi-settings', $capisettings);
}
catch (\Exception $exception) {
if ($prevHost != "") {
$tmpSettings->set('settings.capi-settings.capi_host', $prevHost);
$tmpSettings->save();
}
$msgs = [];
if ($logonError == TRUE) {
array_push($msgs, "Please check your Content API Client ID and Secret ID");
$form_state->setErrorByName('settings][capi-settings][capi_username_ctt');
$form_state->setErrorByName('settings][capi-settings][capi_password_ctt', 'Please check your Client ID and Secret ID Settings: ' . $exception->getMessage());
}
if ($endpointError == TRUE) {
array_push($msgs, "Please verify that the Content API Host is correct");
$form_state->setErrorByName('settings][capi-settings][capi_host', 'Please verify that the Content API Host is correct');
}
\Drupal::logger('TMGMT_CONTENTAPI')->error('Failed to valideate form: %message ', [
'%message' => $exception->getMessage(),
]);
}
// Validate analysis code settings.
$codeanalysissettings = $settings['code-analysis-settings'];
// freeway_auth_url and freeway_service_url must be valid URLs.
if (!empty($codeanalysissettings['freeway_auth_url']) && !filter_var($codeanalysissettings['freeway_auth_url'], FILTER_VALIDATE_URL)) {
$form_state->setErrorByName('settings][code-analysis-settings][freeway_auth_url', 'Freeway Auth URL must be a valid URL.');
}
if (!empty($codeanalysissettings['freeway_service_url']) && !filter_var($codeanalysissettings['freeway_service_url'], FILTER_VALIDATE_URL)) {
$form_state->setErrorByName('settings][code-analysis-settings][freeway_service_url', 'Freeway Service URL must be a valid URL.');
}
// Check if any of the checkboxes are selected then all fields will be mandatory.
$any_level_selected = !empty($codeanalysissettings['code_group']['level_1']) || !empty($codeanalysissettings['code_group']['level_2']) || !empty($codeanalysissettings['code_group']['level_3']);
if ($any_level_selected) {
$required_fields = [
'Freeway Auth URL' => 'freeway_auth_url',
'Freeway Service URL' => 'freeway_service_url',
'Login Name' => 'analysis_code_username',
'Login Password' => 'analysis_code_password',
];
foreach ($required_fields as $label => $field_name) {
if (empty($codeanalysissettings[$field_name])) {
$form_state->setErrorByName(
$field_name,
t('@label is required when any Analysis Code visibility is selected.', [
'@label' => ucfirst(str_replace('_', ' ', $label)),
])
);
}
}
}
// Save the code analysis settings.
$tmpSettings->set('settings.code-analysis-settings.freeway_auth_url', $codeanalysissettings['freeway_auth_url']);
$tmpSettings->set('settings.code-analysis-settings.freeway_service_url', $codeanalysissettings['freeway_service_url']);
$tmpSettings->set('settings.code-analysis-settings.analysis_code_username', $codeanalysissettings['analysis_code_username']);
$tmpSettings->set('settings.code-analysis-settings.analysis_code_password', $codeanalysissettings['analysis_code_password']);
$tmpSettings->set('settings.code-analysis-settings.level_1', $codeanalysissettings['code_group']['level_1']);
$tmpSettings->set('settings.code-analysis-settings.level_2', $codeanalysissettings['code_group']['level_2']);
$tmpSettings->set('settings.code-analysis-settings.level_3', $codeanalysissettings['code_group']['level_3']);
$tmpSettings->save();
}
}
/**
* Function to review form.
*/
#[\ReturnTypeWillChange]
public function reviewForm(array $form, FormStateInterface $form_state, JobItemInterface $item) {
// TODO: Change the autogenerated stub.
return $form;
}
/**
* Function to review data itemen element.
*/
#[\ReturnTypeWillChange]
public function reviewDataItemElement(array $form, FormStateInterface $form_state, $data_item_key, $parent_key, array $data_item, JobItemInterface $item) {
// TODO: Change the autogenerated stub.
return parent::reviewDataItemElement($form, $form_state, $data_item_key, $parent_key, $data_item, $item);
}
/**
* Function to validate review form.
*/
#[\ReturnTypeWillChange]
public function reviewFormValidate(array $form, FormStateInterface $form_state, JobItemInterface $item) {
// TODO: Change the autogenerated stub.
parent::reviewFormValidate($form, $form_state, $item);
}
/**
* Function to submit review form.
*/
#[\ReturnTypeWillChange]
public function reviewFormSubmit(array $form, FormStateInterface $form_state, JobItemInterface $item) {
parent::reviewFormSubmit($form, $form_state, $item);
$triggertby = $form_state->getTriggeringElement();
$triggerid = $triggertby['#id'];
// If reject button has been pressed, reject request in content api.
if ($triggerid == 'edit-reject') {
$job = $item->getJob();
$submittedrequestsarray = unserialize($job->getSetting('capi-remote'));
$first_key = !empty($submittedrequestsarray) ? array_key_first($submittedrequestsarray) : null;
if (isset($submittedrequestsarray) && count($submittedrequestsarray) > 0) {
$arraywithrequest = $submittedrequestsarray[$first_key];
$itemid = $item->id();
foreach ($arraywithrequest as $request) {
$requestSourceNativeId = explode("_", $request->getSourceNativeId())[1];
// Check to cancel the request which belongs to the item or if all item sent in one request then all.
if ($requestSourceNativeId == $itemid || $requestSourceNativeId == 'all') {
try {
$translator = $job->getTranslator();
$token = \DRUPAL::service('tmgmt_contentapi.capi_details')->getCapiToken($translator);
$requestapi = new RequestApi();
$arrayrequestid = new ArrayOfRequestIdsNote();
$arrayrequestid->setRequestIds([$request->getRequestId()]);
$arrayrequestid->setNote('Translation has been rejected by Client using Drupal Connector. Please check the Translation.');
$returnarray = $requestapi->jobsJobIdRequestsRejectPut($token, $request->getJobId(), $arrayrequestid);
if (count($returnarray) == 1 && $returnarray[0] instanceof Request) {
$job->addMessage(t('Remote request rejected: @requestid', ['@requestid' => $request->getRequestId()]));
}
}
catch (\Exception $ex) {
$msg = t('Remote Job could not be rejected: @message', ['@message' => $ex->getMessage()]);
if (strlen($msg) > 200) {
$msg = substr($msg, 0, 200);
}
$job->addMessage($msg, [], 'warning');
}
}
}
}
}
// If Item have been saved as completed, approve request, but not all.
if ($triggerid == 'edit-accept') {
$job = $item->getJob();
$submittedrequestsarray = unserialize($job->getSetting('capi-remote'));
$first_key = !empty($submittedrequestsarray) ? array_key_first($submittedrequestsarray) : null;
if (isset($submittedrequestsarray) && count($submittedrequestsarray) > 0) {
$arraywithrequest = $submittedrequestsarray[$first_key];
$itemid = $item->id();
foreach ($arraywithrequest as $request) {
$requestSourceNativeId = explode("_", $request->getSourceNativeId())[1];
// Check to cancel the request which belongs to the item or if all item sent in one request then all.
if ($requestSourceNativeId == $itemid) {
try {
$translator = $job->getTranslator();
$token = \DRUPAL::service('tmgmt_contentapi.capi_details')->getCapiToken($translator);
$requestapi = new RequestApi();
$arrayrequestid = new ArrayOfRequestIds();
$arrayrequestid->setRequestIds([$request->getRequestId()]);
$jobapi = new JobApi();
$find_job = $jobapi->FindJob($token, $request->getJobId());
if ($find_job == 200) {
$returnarray = $requestapi->jobsJobIdRequestsApprovePut($token, $request->getJobId(), $arrayrequestid);
}
if (count($returnarray) == 1 && $returnarray[0] instanceof Request) {
$job->addMessage(t('Remote request approved: @requestid', ['@requestid' => $request->getRequestId()]));
}
}
catch (\Exception $ex) {
$msg = t('Remote Job could not be approved: @message', ['message' => $ex->getMessage()]);
if (strlen($msg) > 200) {
$msg = substr($msg, 0, 200);
}
$job->addMessage($msg, [], 'warning');
}
}
// TODO: Not sure if this is required, as when displaying Job details, check happens if job finished and approves all. comment out to check?
$allaccepteditems = $job->getItems(['state' => JobItemInterface::STATE_ACCEPTED]);
$allitems = $job->getItems();
// Check if all all job items excluding this one, as this one has not been saved as comleted yet, are accepted.
if (count($allitems) == (count($allaccepteditems) + 1)) {
// Generate array with requestIds to approve, all will be approved.
try {
$translator = $job->getTranslator();
$token = \DRUPAL::service('tmgmt_contentapi.capi_details')->getCapiToken($translator);
$requestapi = new RequestApi();
$arrayrequestid = new ArrayOfRequestIds();
$arrayrequestid->setRequestIds([$request->getRequestId()]);
$jobapi = new JobApi();
$find_job = $jobapi->FindJob($token, $request->getJobId());
if ($find_job == 200) {
$returnarray = $requestapi->jobsJobIdRequestsApprovePut($token, $request->getJobId(), $arrayrequestid);
}
if (count($returnarray) == 1 && $returnarray[0] instanceof Request) {
$job->addMessage(t('Remote request archived: @jobid', ['@jobid' => $request->getJobId()]));
}
}
catch (\Exception $ex) {
$msg = t('Remote Job could not be approved: @message', ['@message' => $ex->getMessage()]);
if (strlen($msg) > 200) {
$msg = substr($msg, 0, 200);
}
$job->addMessage($msg, [], 'warning');
}
}
}
}
}
}
}
