ww_publish-8.x-1.x-dev/ww_publish.module

ww_publish.module
<?php

/**
 * @file
 * The module enables that the WoodWing Studio publishes nodes.
 */

use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\Core\Utility\Error;
use Drupal\media\MediaTypeInterface;
use Drupal\node\Entity\Node;
use Drupal\node\NodeTypeInterface;
use Drupal\ww_publish\Entity\SnsMessageEntity;
use Drupal\ww_publish\Entity\SnsMessageEntityInterface;
use Drupal\ww_publish\Job;

/**
 * Implements hook_help().
 *
 * @inheritdoc
 */
function ww_publish_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.ww_publish':
      $text = file_get_contents(__DIR__ . '/README.md');
      if (!Drupal::moduleHandler()->moduleExists('markdown')) {
        return '<pre>' . Html::escape($text) . '</pre>';
      }
      else {
        // Use the Markdown filter to render the README.
        $filter_manager = Drupal::service('plugin.manager.filter');
        $settings = Drupal::configFactory()
          ->get('markdown.settings')
          ->getRawData();
        $config = ['settings' => $settings];
        $filter = $filter_manager->createInstance('markdown', $config);
        return $filter->process($text, 'en');
      }
  }
  return NULL;
}

/**
 * Implements hook_form_FORM_ID_alter() for the field config edit form.
 */
function ww_publish_form_field_config_edit_form_alter(&$form, FormStateInterface $form_state) {
  /** @var \Drupal\field\FieldConfigInterface $fieldEntity */
  $fieldEntity = $form_state->getFormObject()->getEntity();

  $description = t('Identifier for the related field in WoodWing Studio.');
  if ($fieldEntity->getTargetEntityTypeId() == 'paragraph') {
    $description = t('Identifier for the related field in WoodWing Studio. Multiple components can be separated with a comma: body,crosshead|text');
  }
  elseif ($fieldEntity->getType() == 'entity_reference') {
    $description = t('Identifier for the related field in WoodWing Studio. Prefix with metadata: to map a metadata field, e.g. metadata:ExtraMetaData|FIELD_NAME');
  }

  $form['third_party_settings']['ww_publish']['content_station_identifier'] = [
    '#type' => 'textfield',
    '#title' => t('WoodWing Studio identifier'),
    '#size' => 512,
    '#maxlength' => 512,
    '#description' => $description,
    '#default_value' => $fieldEntity->getThirdPartySetting('ww_publish', 'content_station_identifier'),
  ];

}

/**
 * Implements hook_form_FORM_ID_alter() for the content type edit form.
 */
function ww_publish_form_node_type_edit_form_alter(&$form, FormStateInterface $form_state) {
  $nodeTypeEntity = $form_state->getFormObject()->getEntity();
  $moduleHandler = \Drupal::service('module_handler');


  $form['ww_publish'] = [
    '#type' => 'details',
    '#title' => t('WoodWing Studio settings'),
    '#group' => 'additional_settings',
  ];
  $form['ww_publish']['content_station_identifier_title'] = [
    '#type' => 'textfield',
    '#title' => t('WoodWing Studio identifier for the title field'),
    '#description' => t('Identifier of the related component in WoodWing Studio.'),
    '#default_value' => $nodeTypeEntity->getThirdPartySetting('ww_publish', 'content_station_identifier_title'),
  ];

  // Test if the module Paragraph is enabled.
  if ($moduleHandler->moduleExists('scheduler')) {
    $defaultValuePublish = $nodeTypeEntity->getThirdPartySetting('ww_publish', 'content_station_identifier_publish_on');
    $defaultValueUnpublish = $nodeTypeEntity->getThirdPartySetting('ww_publish', 'content_station_identifier_unpublish_on');
    $attributes = [];
    $description = t('Identifier of the related component in WoodWing Studio.');
  } else {
    $defaultValuePublish = NULL;
    $defaultValueUnpublish = NULL;
    $attributes = ['disabled' => 'disabled'];
    $description = t('The module Scheduler is not enabled.');
  }
  $form['ww_publish']['content_station_identifier_publish_on'] = [
    '#type' => 'textfield',
    '#title' => t('WoodWing Studio identifier for the scheduler field publish_on'),
    '#description' => $description,
    '#default_value' => $defaultValuePublish,
    '#attributes' => $attributes,
  ];
  $form['ww_publish']['content_station_identifier_unpublish_on'] = [
    '#type' => 'textfield',
    '#title' => t('WoodWing Studio identifier for the scheduler field unpublish_on'),
    '#description' => $description,
    '#default_value' => $defaultValueUnpublish,
    '#attributes' => $attributes,
  ];

  $form['ww_publish']['article_storyid_field'] = [
    '#type' => 'textfield',
    '#title' => t('Article StoryID field'),
    '#description' => t('Machine name of the WoodWing article ID field. E.g.: field_ww_id. Preferred over ID if the used WoodWing Studio version supports it. This is a UUID, so it must be a string field.'),
    '#default_value' => $nodeTypeEntity->getThirdPartySetting('ww_publish', 'article_storyid_field'),
  ];

  $form['ww_publish']['article_id_field'] = [
    '#type' => 'textfield',
    '#title' => t('Article ID field'),
    '#description' => t('Machine name of the WoodWing article ID field. E.g.: field_ww_id. Can be the same field as the Story ID when used as a fallback for existing content.'),
    '#default_value' => $nodeTypeEntity->getThirdPartySetting('ww_publish', 'article_id_field'),
  ];

  // Test if the module Paragraph is enabled.
  if ($moduleHandler->moduleExists('paragraphs')) {
    $defaultValue = $nodeTypeEntity->getThirdPartySetting('ww_publish', 'paragraph_field');
    $attributes = [];
    $description = t('Machine name of the field, which is used to save WoodWing Studio components as paragraphs. E.g.: field_paragraph');
  } else {
    $defaultValue = NULL;
    $attributes = ['disabled' => 'disabled'];
    $description = t('The module Paragraphs is not enabled.');
  }
  $form['ww_publish']['paragraph_field'] = [
    '#type' => 'textfield',
    '#title' => t('Paragraph field'),
    '#description' => $description,
    '#default_value' => $defaultValue,
    '#attributes' => $attributes,
  ];

  $form['#entity_builders'][] = 'ww_publish_form_node_type_edit_form_builder';
}

/**
 * Entity builder for the node type form with ww_publish options.
 *
 * @see ww_publish_form_node_type_edit_form_alter()
 */
function ww_publish_form_node_type_edit_form_builder($entity_type, NodeTypeInterface $type, &$form, FormStateInterface $form_state) {
  $type->setThirdPartySetting('ww_publish', 'content_station_identifier_title', trim($form_state->getValue('content_station_identifier_title')));
  $type->setThirdPartySetting('ww_publish', 'content_station_identifier_publish_on', trim($form_state->getValue('content_station_identifier_publish_on')));
  $type->setThirdPartySetting('ww_publish', 'content_station_identifier_unpublish_on', trim($form_state->getValue('content_station_identifier_unpublish_on')));
  $type->setThirdPartySetting('ww_publish', 'article_storyid_field', trim($form_state->getValue('article_storyid_field')));
  $type->setThirdPartySetting('ww_publish', 'article_id_field', trim($form_state->getValue('article_id_field')));
  $type->setThirdPartySetting('ww_publish', 'paragraph_field', trim($form_state->getValue('paragraph_field')));
}

/**
 * Implements hook_form_FORM_ID_alter() for the media type edit form.
 */
function ww_publish_form_media_type_edit_form_alter(&$form, FormStateInterface $form_state) {
  $media_type = $form_state->getFormObject()->getEntity();

  $form['ww_publish'] = [
    '#type' => 'details',
    '#title' => t('WoodWing Studio settings'),
    '#group' => 'additional_settings',
  ];

  $form['ww_publish']['id_field'] = [
    '#type' => 'textfield',
    '#title' => t('Image ID field'),
    '#description' => t('Machine name of the WoodWing image ID field. E.g.: field_ww_id.'),
    '#default_value' => $media_type->getThirdPartySetting('ww_publish', 'id_field'),
  ];

  $form['#entity_builders'][] = 'ww_publish_form_media_type_edit_form_builder';
}

/**
 * Entity builder for the media type form with ww_publish options.
 *
 * @see ww_publish_form_media_type_edit_form_alter()
 */
function ww_publish_form_media_type_edit_form_builder($entity_type, MediaTypeInterface $type, &$form, FormStateInterface $form_state) {
  $type->setThirdPartySetting('ww_publish', 'id_field', trim($form_state->getValue('id_field')));
}

/**
 * Implements hook_form_FORM_ID_alter() for node edit form.
 *
 * Display the error messages from the error messages field.
 */
function ww_publish_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $config = \Drupal::config('ww_publish.settings');
  if (
    $config->get('error_messages_field') &&
    $form_state->getFormObject() instanceof EntityForm
  ) {
    $entity = $form_state->getFormObject()->getEntity();
    if (
      $entity instanceof Node &&
      !$entity->isNew() &&
      isset($entity->{$config->get('error_messages_field')}) &&
      $entity->{$config->get('error_messages_field')}
    ) {
      foreach ($entity->{$config->get('error_messages_field')}->getValue() as $errorMessage) {
        if (
          !empty($errorMessage) &&
          array_key_exists('value', $errorMessage)
        )
        \Drupal::messenger()->addError($errorMessage['value']);
      }
    }
  }
}

/**
 * Implements hook_cron().
 */
function ww_publish_cron() {
  $config = \Drupal::config('ww_publish.settings');

  // Load all the old SNS messages and delete them.
  $storage = \Drupal::entityTypeManager()->getStorage('ww_publish_sns_message');
  $snsMessageEntitiesIds = $storage->getQuery()
    ->condition('created', \Drupal::time()->getRequestTime() - ($config->get('sns_delete') * 24 * 60 * 60), '<')
    ->accessCheck(FALSE)
    ->execute();
  $snsMessageEntities = $storage->loadMultiple($snsMessageEntitiesIds);
  $storage->delete($snsMessageEntities);

  // Publish the article/nodes.
  $query = \Drupal::entityQuery('ww_publish_sns_message')
    ->accessCheck(FALSE)
    ->condition('status', SnsMessageEntityInterface::NEW)
    ->range(0, 50);
  $snsMessageIds = $query->execute();

  /** @var \Drupal\ww_publish\Job $job */
  $job = \Drupal::service('ww_publish.job');
  /** @var \Drupal\ww_publish\Entity\SnsMessageEntityInterface $snsMessageEntity */
  foreach ($snsMessageIds as $snsMessageId) {
    try {
      $job->publishArticle($snsMessageId);
    }
    catch (\Throwable $e) {
      $variables = Error::decodeException($e);
      $message = '%type: @message in %function (line %line of %file).';
      \Drupal::logger('ww_publish')->error($message, $variables);
    }
  }
}

/**
 * Implements hook_requirements().
 */
function ww_publish_requirements($phase) {
  $requirements = [];
  if ($phase == 'runtime') {
    if (!\Drupal::config('ww_publish.settings')->get('topic_arn')) {
      $requirements['ww_publish'] = [
        'title' => t('ArnTopic configuration missing'),
        'severity' => REQUIREMENT_WARNING,
        'description' => t('It is recommended to configure a ArnTopic to ensure that only notifications from a trusted source are processed. <a href=":link">You can set it here</a>.', [
          ':link' => Url::fromRoute('ww_publish.settings')->toString(),
        ]),
      ];
    }
  }

  return $requirements;
}

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

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