ezcontent-8.x-dev/modules/ezcontent_node/modules/ezcontent_smart_article/ezcontent_smart_article.module

modules/ezcontent_node/modules/ezcontent_smart_article/ezcontent_smart_article.module
<?php

/**
 * @file
 * Module file for ezcontent_smart_article.
 */

use Drupal\Component\Serialization\Json;
use Drupal\Component\Utility\Html;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\InvokeCommand;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * Implements hook_views_data_alter().
 */
function ezcontent_smart_article_views_data_alter(array &$data) {
  $data['media__field_smart_image_tags']['media_type_filter'] = [
    'title' => t('Filter by smart image tags'),
    'filter' => [
      'title' => t('Filter by smart image tags'),
      'help' => t('Provides a custom filter for smart image media by tags.'),
      'field' => 'field_smart_image_tags_target_id',
      'id' => 'taxonomy_index_tid',
    ],
  ];
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function ezcontent_smart_article_form_node_form_alter(&$form, FormStateInterface $form_state) {
  if (in_array($form['#form_id'], [
    'node_smart_article_edit_form',
    'node_smart_article_form',
  ])) {
    $summary_config = \Drupal::config('ezcontent_smart_article.settings');
    if (empty($summary_config->get('summary_generator_api_url')) ||
      empty($summary_config->get('summary_generator_data_file')) ||
      empty($summary_config->get('image_captioning_api_url')) ||
      empty($summary_config->get('abstractive_summary_api_url')) ||
      empty($summary_config->get('extractive_summary_api_url')) ||
      empty($summary_config->get('smart_tags_api_url'))) {
      $form['overlay_link'] = [
        '#type' => 'link',
        '#url' => Url::fromRoute('ezcontent_smart_article.invalid_subscription'),
        '#attributes' => [
          'class' => ['use-ajax'],
          'data-dialog-type' => 'modal',
          'data-dialog-options' => Json::encode([
            'title' => t('Smart Article Settings'),
            'width' => 700,
            'closeOnEscape' => FALSE,
            'modal' => TRUE,
          ]),
        ],
      ];
    }
    // Make Company name Autocomplete.
    $form['field_company_name']['widget'][0]['value']['#autocomplete_route_name'] = 'ezcontent_smart_article.autocomplete.companies';
    // Add a generate summary button and hide body field.
    $form['field_company_name']['generate_summary'] = [
      '#type' => 'submit',
      '#name' => 'generate_summary',
      '#value' => t('Generate Article Content'),
      '#weight' => 11,
      '#attributes' => empty($summary_config->get('summary_generator_api_url')) ? [
        'disabled' => 'disabled',
      ] : [],
      '#ajax' => [
        'callback' => 'ezcontent_smart_article_generate_callback',
        'wrapper' => 'form-summary-generate-wrapper',
        'effect' => 'fade',
        'event' => 'click',
        'progress' => [
          'type' => 'throbber',
          'message' => 'Please wait...',
        ],
      ],
    ];
    $form['#attached']['library'][] = 'ezcontent_smart_article/ezcontent_smart_article_libs';

    if (isset($form['body'])) {
      if ($form['body']['widget'][0]['#default_value'] == '') {
        $form['body']['#attributes']['class'][] = 'hide-body--field';
        $form['body']['#attributes']['style'] = 'display:none;';
      }
    }
    // Check if smart summary exist.
    if (isset($form['field_smart_text_summary']['widget'][0]['summary'])) {
      $form['field_smart_text_summary']['widget'][0]['summary_container']['number_of_sentences']['#states'] = [
        'visible' => [
          ':input[name="field_smart_text_summary[0][summary_container][summary_type]"]' => ['value' => 'extractive'],
        ],
      ];
      $form['field_smart_text_summary']['widget'][0]['summary_container']['generate_smart_summary']['#ajax'] = [
        'callback' => 'ezcontent_smart_summary_generate_callback',
        'wrapper' => 'form-smart-summary-generate-wrapper',
        'effect' => 'fade',
        'event' => 'click',
        'progress' => [
          'type' => 'throbber',
          'message' => 'Please wait...',
        ],
      ];
      // Disable summary generate button if subscription keys not available.
      $form['field_smart_text_summary']['widget'][0]['summary_container']['generate_smart_summary']['#attributes']
        = (empty($summary_config->get('abstractive_summary_api_url')) || empty($summary_config->get('extractive_summary_api_url')))
        ? ['disabled' => 'disabled'] : [];
      // Add submit handler to update summary.
      $form['actions']['submit']['#submit'][] = 'update_summary_field_submit_handler';
    }

    // Code for Podcast.
    $bundle = $entity_type = '';
    $form_object = $form_state->getFormObject();
    if ($form_object instanceof ContentEntityForm) {
      $entity = $form_object->getEntity();
      $bundle = $entity->bundle();
      $entity_type = $entity->getEntityTypeId();
      if (!empty($entity_type) && !empty($bundle)) {
        // Custom submit handler for Podcast.
        foreach ($entity->getFieldDefinitions() as $field_definition) {
          if ($field_definition->getType() === 'ezcontent_smart_podcast') {
            // Submit handler for podcast.
            $form['actions']['submit']['#submit'][] = 'ezcontent_smart_podcast_submit_handler';
            break;
          }
        }
      }
    }
  }
}

/**
 * Custom submit handler for podcast.
 *
 * @param array $form
 *   The form object.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   The form state object.
 *
 * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
 * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
 */
function ezcontent_smart_podcast_submit_handler(array &$form, FormStateInterface $form_state) {
  $text = '';
  $entity = $form_state->getFormObject()->getEntity();
  foreach ($entity->getFieldDefinitions() as $field_definition) {
    if ($field_definition->getType() === 'ezcontent_smart_podcast') {
      $field_name = $field_definition->getName();
      $text_to_speech_fields = $field_definition->getSettings()['text_to_speech_fields'];
    }
  }
  if (isset($field_name) && isset($text_to_speech_fields)) {
    if ($entity->$field_name->convert_text_to_speech && empty($entity->$field_name->target_id)) {
      $entity_type_id = $entity->getEntityTypeId();
      $entity_id = $entity->id();
      $default_display_fields = \Drupal::entityTypeManager()
        ->getStorage('entity_view_display')
        ->load($entity_type_id . '.' . $entity->bundle() . '.default')
        ->getComponents();
      uasort($default_display_fields, function ($a, $b) {
        if ($a['weight'] === $b['weight']) {
          return 0;
        }
        return $a['weight'] < $b['weight'] ? -1 : 1;
      });
      $default_display_fields = array_keys($default_display_fields);
      $text_to_speech_content_fields = array_filter($text_to_speech_fields['content']);
      $text_to_speech_reference_fields = $text_to_speech_fields['paragraphs'];
      foreach ($default_display_fields as $default_display_field) {
        if (isset($text_to_speech_content_fields[$default_display_field])) {
          if (isset($text_to_speech_reference_fields[$default_display_field])) {
            if ($entity->$default_display_field->entity) {
              foreach ($entity->$default_display_field->referencedEntities() as $ref_entity) {
                if (in_array($ref_entity->getType(), array_keys($text_to_speech_reference_fields[$default_display_field]))) {
                  $text = $text . ' ' . ezcontent_smart_podcast_get_ref_text_to_speech_fields($ref_entity);
                }
              }
            }
          }
          else {
            if ($entity->$default_display_field->value) {
              $stripped_value = strip_tags(trim($entity->$default_display_field->value));
              if (!preg_match("/[.]$/", $stripped_value)) {
                $stripped_value = $stripped_value . '.';
              }
              $text = $text . ' ' . $stripped_value;
            }
          }
        }
      }
      $data['entity_type_id'] = $entity_type_id;
      $data['entity_id'] = $entity_id;
      $data['field_name'] = $field_name;
      $data['text'] = $text;
      // Use key value to record an entry for the node being queued for podcast
      // creation.
      $key_value = \Drupal::keyValue('text_to_speech_node');
      // If key_value has an entry for the node, it means the node is already
      // added into the queue for conversion, then fetch the corresponding
      // queue item id and update the data in the queue.
      if ($key_value->has($entity_id)) {
        $item_id = $key_value->get($entity_id)['item_id'];
        \Drupal::database()->update('queue')
          ->fields(['data' => serialize($data)])
          ->condition('name', 'text_to_speech_queue')
          ->condition('item_id', $item_id)
          ->execute();
      }
      // The current node is being queued for the first time, so post queue
      // creation set the node id and the queue item id in the key_value.
      else {
        $queue = \Drupal::queue('text_to_speech_queue');
        $item_id = $queue->createItem($data);
        $key_value->set($entity_id, ['item_id' => $item_id]);
      }
    }
  }
}

/**
 * Helper function to fetch textual fields from given paragraph entity.
 *
 * @param object $entity
 *   Paragraph entity.
 *
 * @return string
 *   Text string from textual fields of the given entity.
 *
 * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
 * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
 *
 * @todo Move to a service.
 */
function ezcontent_smart_podcast_get_ref_text_to_speech_fields($entity) {
  $text = '';
  $types = [
    'string',
    'string_long',
    'text',
    'text_default',
    'text_long',
    'text_with_summary',
    'smart_text_with_summary',
  ];
  $default_display_fields = \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load($entity->getEntityTypeId() . '.' . $entity->getType() . '.default')
    ->getComponents();
  uasort($default_display_fields, function ($a, $b) {
    if ($a['weight'] === $b['weight']) {
      return 0;
    }
    return $a['weight'] < $b['weight'] ? -1 : 1;
  });
  foreach ($default_display_fields as $field => $value) {
    $field_definition = $entity->getFieldDefinition($field);
    $field_type = $field_definition->getType();
    $field_name = $field_definition->getName();
    if (in_array($field_type, $types)) {
      if ($entity->$field_name->value) {
        $stripped_value = strip_tags(trim($entity->$field_name->value));
        if (!preg_match("/[.]$/", $stripped_value)) {
          $stripped_value = $stripped_value . '.';
        }
        $text = $text . ' ' . $stripped_value;
      }
    }
    if ($field_type === 'entity_reference_revisions') {
      $ref_entity = $entity->$field_name->entity;
      $text = $text . ' ' . ezcontent_smart_podcast_get_ref_text_to_speech_fields($ref_entity);
    }
  }
  return $text;
}

/**
 * Summary generator callback.
 *
 * @todo Move to a service.
 */
function ezcontent_smart_article_generate_callback(&$form, FormStateInterface $form_state) {
  $results = \Drupal::service('ezcontent_smart_article.companies_list');
  $company_name = $form_state->getValue('field_company_name')[0]['value'];
  $text = $results->getData($company_name, 'article');

  $response = new AjaxResponse();
  $arguments = [$text, 'edit-body-0-value'];
  $response->addCommand(new InvokeCommand(NULL, "update_text_editor", $arguments));
  $response->addCommand(new InvokeCommand('.hide-body--field', 'show'));
  return $response;
}

/**
 * Summary generator callback.
 *
 * @todo Move to a service.
 */
function ezcontent_smart_summary_generate_callback(&$form, FormStateInterface $form_state) {
  $generate_summary = \Drupal::service('ezcontent_smart_article.generate_summary');
  $summary_type = $form_state->getValue('field_smart_text_summary')[0]['summary_container']['summary_type'];
  $number_of_sentences = $form_state->getValue('field_smart_text_summary')[0]['summary_container']['number_of_sentences'];
  $article = Html::decodeEntities(strip_tags($form_state->getValue('field_smart_text_summary')[0]['value']));
  $text = Json::decode($generate_summary->generateSummary($article, $summary_type, $number_of_sentences));
  $summary = $text['data']['data']['summary'];

  $response = new AjaxResponse();
  $arguments = [
    $summary,
    'edit-field-smart-text-summary-0-summary-container-summary-area',
  ];
  $response->addCommand(new InvokeCommand(NULL, "update_summary_text", $arguments));
  return $response;
}

/**
 * Summary generator callback.
 *
 * @todo Move to a service.
 */
function update_summary_field_submit_handler(&$form, FormStateInterface $form_state) {
  $entity = $form_state->getFormObject()->getEntity();
  $summary = $form_state->getValue('field_smart_text_summary')[0]['summary_container']['summary_area'];
  $entity->get('field_smart_text_summary')->summary = $summary;
  $entity->save();
}

/**
 * Implements hook_theme().
 */
function ezcontent_smart_article_theme($existing, $type, $theme, $path) {
  return [
    'smarttag_template' => [
      'variables' => ['tags' => []],
    ],
    'smart_article_get_subscription_landing_page' => [
      'variables' => [],
    ],
    'smart_article_invalid_subscription_popup' => [
      'variables' => [],
    ],
    'autocomplete_deluxe_smart_tags' => [
      'variables' => ['tags' => []],
    ],
  ];
}

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

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