You are here

scheduler.module in Scheduler 8

Scheduler publishes and unpublishes nodes on dates specified by the user.

File

scheduler.module
View source
<?php

/**
 * @file
 * Scheduler publishes and unpublishes nodes on dates specified by the user.
 */
use Drupal\Component\Utility\Xss;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\node\Entity\NodeType;
use Drupal\scheduler\SchedulerEvent;
use Drupal\scheduler\SchedulerEvents;

/**
 * Implements hook_help().
 */
function scheduler_help($route_name, RouteMatchInterface $route_match) {
  $output = '';
  switch ($route_name) {
    case 'help.page.scheduler':
      $output = '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Scheduler module provides the functionality for automatic publishing and unpublishing of nodes at specified future dates.') . '</p>';
      $output .= '<p>' . t('You can read more in the <a href="@readme">readme</a> file or our <a href="@project">project page on Drupal.org</a>.', [
        '@readme' => $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'scheduler') . '/README.md',
        '@project' => 'https://drupal.org/project/scheduler',
      ]) . '</p>';
      break;
    case 'scheduler.admin_form':
      $output = '<p>' . t('Most of the Scheduler options are set for each different content type, and are accessed via the <a href="@link">admin content type</a> list.', [
        '@link' => Url::fromRoute('entity.node_type.collection')
          ->toString(),
      ]) . '</br>';
      $output .= t('The options and settings below are common to all content types.') . '</p>';
      break;
    case 'scheduler.cron_form':
      $base_url = $GLOBALS['base_url'];
      $access_key = \Drupal::config('scheduler.settings')
        ->get('lightweight_cron_access_key');
      $cron_url = $base_url . '/scheduler/cron/' . $access_key;
      $output = '<p>' . t("When you have set up Drupal's standard crontab job cron.php then Scheduler will be executed during each cron run. However, if you would like finer granularity to scheduler, but don't want to run Drupal's cron more often then you can use the lightweight cron handler provided by Scheduler. This is an independent cron job which only runs the scheduler process and does not execute any cron tasks defined by Drupal core or any other modules.") . '</p>';
      $output .= '<p>' . t("Scheduler's cron is at /scheduler/cron/{access-key} and a sample crontab entry to run scheduler every minute might look like:") . '</p>';
      $output .= '<code>* * * * * wget -q -O /dev/null "' . $cron_url . '"</code>';
      $output .= '<p>' . t('or') . '</p>';
      $output .= '<code>* * * * * curl -s -o /dev/null "' . $cron_url . '"</code><br/><br/>';
      break;
    default:
  }
  return $output;
}

/**
 * Implements hook_form_FORM_ID_alter() for node_type_form().
 */
function scheduler_form_node_type_form_alter(array &$form, FormStateInterface $form_state) {

  // Load the real code only when needed.
  module_load_include('inc', 'scheduler', 'scheduler.admin');
  _scheduler_form_node_type_form_alter($form, $form_state);
}

/**
 * Implements hook_form_FORM_ID_alter() for node_form().
 */
function scheduler_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $config = \Drupal::config('scheduler.settings');

  /** @var \Drupal\node\NodeTypeInterface $type */
  $type = $form_state
    ->getFormObject()
    ->getEntity()->type->entity;
  $publishing_enabled = $type
    ->getThirdPartySetting('scheduler', 'publish_enable', $config
    ->get('default_publish_enable'));
  $unpublishing_enabled = $type
    ->getThirdPartySetting('scheduler', 'unpublish_enable', $config
    ->get('default_unpublish_enable'));

  // Determine if the scheduler fields have been set to hidden (disabled).
  $display = $form_state
    ->getFormObject()
    ->getFormDisplay($form_state);
  $publishing_displayed = !empty($display
    ->getComponent('publish_on'));
  $unpublishing_displayed = !empty($display
    ->getComponent('unpublish_on'));

  /** @var \Drupal\node\NodeInterface $node */
  $node = $form_state
    ->getFormObject()
    ->getEntity();

  // Invoke all implementations of hook_scheduler_hide_publish_on_field() to
  // allow other modules to hide the field on the node edit form.
  if ($publishing_enabled && $publishing_displayed) {
    $hook = 'scheduler_hide_publish_on_field';
    foreach (\Drupal::moduleHandler()
      ->getImplementations($hook) as $module) {
      $function = $module . '_' . $hook;
      $publishing_displayed = $function($form, $form_state, $node) !== TRUE && $publishing_displayed;
    }
  }

  // Invoke all implementations of hook_scheduler_hide_unpublish_on_field() to
  // allow other modules to hide the field on the node edit form.
  if ($unpublishing_enabled && $unpublishing_displayed) {
    $hook = 'scheduler_hide_unpublish_on_field';
    foreach (\Drupal::moduleHandler()
      ->getImplementations($hook) as $module) {
      $function = $module . '_' . $hook;
      $unpublishing_displayed = $function($form, $form_state, $node) !== TRUE && $unpublishing_displayed;
    }
  }

  // If both publishing and unpublishing are either not enabled or are hidden
  // for this node type then the only thing to do is remove the fields from the
  // form, then exit.
  if ((!$publishing_enabled || !$publishing_displayed) && (!$unpublishing_enabled || !$unpublishing_displayed)) {
    unset($form['publish_on']);
    unset($form['unpublish_on']);
    return;
  }
  $allow_date_only = $config
    ->get('allow_date_only');

  // A publish_on date is required if the content type option is set and the
  // node is being created or it is currently not published but has a
  // scheduled publishing date.
  $publishing_required = $publishing_enabled && $type
    ->getThirdPartySetting('scheduler', 'publish_required', $config
    ->get('default_publish_required')) && ($node
    ->isNew() || !$node
    ->isPublished() && !empty($node->publish_on->value));

  // An unpublish_on date is required if the content type option is set and the
  // node is being created or the current status is published or the node is
  // scheduled to be published.
  $unpublishing_required = $unpublishing_enabled && $type
    ->getThirdPartySetting('scheduler', 'unpublish_required', $config
    ->get('default_unpublish_required')) && ($node
    ->isNew() || $node
    ->isPublished() || !empty($node->publish_on->value));

  // Create a 'details' field group to wrap the scheduling fields, and expand it
  // if publishing or unpublishing is required, if a date already exists or the
  // fieldset is configured to be always expanded.
  $has_data = isset($node->publish_on->value) || isset($node->unpublish_on->value);
  $always_expand = $type
    ->getThirdPartySetting('scheduler', 'expand_fieldset', $config
    ->get('default_expand_fieldset')) === 'always';
  $expand_details = $publishing_required || $unpublishing_required || $has_data || $always_expand;

  // Create the group for the fields.
  $form['scheduler_settings'] = [
    '#type' => 'details',
    '#title' => t('Scheduling options'),
    '#open' => $expand_details,
    '#weight' => 35,
    '#attributes' => [
      'class' => [
        'scheduler-form',
      ],
    ],
    '#optional' => FALSE,
  ];

  // Attach the fields to group.
  $form['unpublish_on']['#group'] = 'scheduler_settings';
  $form['publish_on']['#group'] = 'scheduler_settings';

  // Show the field group as a vertical tab if this option is enabled.
  $use_vertical_tabs = $type
    ->getThirdPartySetting('scheduler', 'fields_display_mode', $config
    ->get('default_fields_display_mode')) === 'vertical_tab';
  if ($use_vertical_tabs) {
    $form['scheduler_settings']['#group'] = 'advanced';

    // Attach the javascript for the vertical tabs.
    $form['scheduler_settings']['#attached']['library'][] = 'scheduler/vertical-tabs';
  }

  // Define the descriptions depending on whether the time can be skipped.
  $descriptions = [];
  if ($allow_date_only) {
    $descriptions['format'] = t('Enter a date. The time part is optional.');

    // Show the default time so users know what they will get if they do not
    // enter a time.
    $descriptions['default'] = t('The default time is @default_time.', [
      '@default_time' => $config
        ->get('default_time'),
    ]);

    // Use javascript to pre-fill the time parts if the dates are required.
    // See js/scheduler_default_time.js for more details.
    if ($publishing_required || $unpublishing_required) {
      $form['scheduler_settings']['#attached']['library'][] = 'scheduler/default-time';
      $form['scheduler_settings']['#attached']['drupalSettings']['schedulerDefaultTime'] = $config
        ->get('default_time');
    }
  }
  else {
    $descriptions['format'] = t('Enter a date and time.');
  }
  if (!$publishing_required) {
    $descriptions['blank'] = t('Leave the date blank for no scheduled publishing.');
  }
  $form['publish_on']['#access'] = $publishing_enabled && $publishing_displayed;
  $form['publish_on']['widget'][0]['value']['#required'] = $publishing_required;
  $form['publish_on']['widget'][0]['value']['#description'] = Xss::filter(implode(' ', $descriptions));
  if (!$unpublishing_required) {
    $descriptions['blank'] = t('Leave the date blank for no scheduled unpublishing.');
  }
  else {
    unset($descriptions['blank']);
  }
  $form['unpublish_on']['#access'] = $unpublishing_enabled && $unpublishing_displayed;
  $form['unpublish_on']['widget'][0]['value']['#required'] = $unpublishing_required;
  $form['unpublish_on']['widget'][0]['value']['#description'] = Xss::filter(implode(' ', $descriptions));

  // When hiding the seconds on time input, we need to remove the seconds from
  // the form value, as some browsers HTML5 rendering still show the seconds.
  // We can use the same jQuery drupal behaviors file as for default time.
  if ($config
    ->get('hide_seconds')) {

    // If there is a publish_on time, then use jQuery to remove the seconds.
    if (isset($node->publish_on->value)) {
      $form['scheduler_settings']['#attached']['library'][] = 'scheduler/default-time';
      $form['scheduler_settings']['#attached']['drupalSettings']['schedulerHideSecondsPublishOn'] = date('H:i', $node->publish_on->value);
    }

    // Likewise for the unpublish_on time.
    if (isset($node->unpublish_on->value)) {
      $form['scheduler_settings']['#attached']['library'][] = 'scheduler/default-time';
      $form['scheduler_settings']['#attached']['drupalSettings']['schedulerHideSecondsUnpublishOn'] = date('H:i', $node->unpublish_on->value);
    }
  }
  if (!\Drupal::currentUser()
    ->hasPermission('schedule publishing of nodes')) {

    // Do not show the scheduler fields for users who do not have permission.
    // Setting #access to FALSE for 'scheduler_settings' is enough to hide the
    // fields. Setting FALSE for the individual fields is necessary to keep any
    // existing scheduled dates preserved and remain unchanged on saving.
    $form['scheduler_settings']['#access'] = FALSE;
    $form['publish_on']['#access'] = FALSE;
    $form['unpublish_on']['#access'] = FALSE;

    // @todo Find a more elegant solution for bypassing the validation of
    // scheduler fields when the user does not have permission.
    // Note: This scenario is NOT yet covered by any tests, neither in
    // SchedulerPermissionsTest.php nor SchedulerRequiredTest.php
    // @see https://www.drupal.org/node/2651448
    $form['publish_on']['widget'][0]['value']['#required'] = FALSE;
    $form['unpublish_on']['widget'][0]['value']['#required'] = FALSE;
  }

  // Check which widget type is set for the scheduler fields, and give a warning
  // if the wrong one has been set and provide a hint and link to fix it.
  $pluginDefinitions = $display
    ->get('pluginManager')
    ->getDefinitions();
  $fields_to_check = [];
  if ($publishing_enabled && $publishing_displayed) {
    $fields_to_check[] = 'publish_on';
  }
  if ($unpublishing_enabled && $unpublishing_displayed) {
    $fields_to_check[] = 'unpublish_on';
  }
  $correct_widget_id = 'datetime_timestamp_no_default';
  foreach ($fields_to_check as $field) {
    $actual_widget_id = $display
      ->getComponent($field)['type'];
    if ($actual_widget_id != $correct_widget_id) {
      \Drupal::messenger()
        ->addMessage(t('The widget for field %field is incorrectly set to %wrong. This should be changed to %correct by an admin user via Field UI <a href="@link">content type form display</a> :not_available', [
        '%field' => (string) $form[$field]['widget']['#title'],
        '%correct' => (string) $pluginDefinitions[$correct_widget_id]['label'],
        '%wrong' => (string) $pluginDefinitions[$actual_widget_id]['label'],
        '@link' => \Drupal::moduleHandler()
          ->moduleExists('field_ui') ? Url::fromRoute('entity.entity_form_display.node.default', [
          'node_type' => $type
            ->get('type'),
        ])
          ->toString() : '#',
        ':not_available' => \Drupal::moduleHandler()
          ->moduleExists('field_ui') ? '' : '(' . t('not available') . ')',
      ]), 'warning', FALSE);
    }
  }
}

/**
 * Implements hook_form_FORM_ID_alter() for devel_generate_form_content.
 */
function scheduler_form_devel_generate_form_content_alter(array &$form, FormStateInterface $form_state) {

  // Add an extra column to the node_types table to show which type are enabled
  // for scheduled publishing and unpublishing.
  $publishing_enabled_types = array_keys(_scheduler_get_scheduler_enabled_node_types('publish'));
  $unpublishing_enabled_types = array_keys(_scheduler_get_scheduler_enabled_node_types('unpublish'));
  $form['node_types']['#header']['scheduler'] = t('Scheduler settings');
  foreach (array_keys($form['node_types']['#options']) as $type) {
    $items = [];
    if (in_array($type, $publishing_enabled_types)) {
      $items[] = t('Enabled for publishing');
    }
    if (in_array($type, $unpublishing_enabled_types)) {
      $items[] = t('Enabled for unpublishing');
    }
    if (empty($items)) {
      $scheduler_settings = t('None');
    }
    else {
      $scheduler_settings = [
        'data' => [
          '#theme' => 'item_list',
          '#items' => $items,
        ],
      ];
    }
    $form['node_types']['#options'][$type]['scheduler'] = $scheduler_settings;
  }

  // Add form items to specify what proportion of generated nodes should have a
  // publish-on and unpublish-on date assigned. See hook_node_presave() for the
  // code which sets the node values.
  $form['scheduler_publishing'] = [
    '#type' => 'number',
    '#title' => t('Publishing date for Scheduler'),
    '#description' => t('Enter the percentage of randomly selected Scheduler-enabled nodes to be given a publish-on date. Enter 0 for none, 100 for all. The date and time will be random within the range starting at node creation date, up to a time in the future matching the same span as selected above for node creation date.'),
    '#default_value' => 50,
    '#required' => TRUE,
    '#min' => 0,
    '#max' => 100,
  ];
  $form['scheduler_unpublishing'] = [
    '#type' => 'number',
    '#title' => t('Unpublishing date for Scheduler'),
    '#description' => t('Enter the percentage of randomly selected Scheduler-enabled nodes to be given an unpublish-on date. Enter 0 for none, 100 for all. The date and time will be random within the range starting at the later of node creation date and publish-on date, up to a time in the future matching the same span as selected above for node creation date.'),
    '#default_value' => 50,
    '#required' => TRUE,
    '#min' => 0,
    '#max' => 100,
  ];
}

/**
 * Implements hook_form_FORM_ID_alter() for language_content_settings_form.
 */
function scheduler_form_language_content_settings_form_alter(array &$form, FormStateInterface $form_state) {

  // Add our validation function for the translation field settings form at
  // admin/config/regional/content-language.
  $form['#validate'][] = '_scheduler_translation_validate';
}

/**
 * Validation handler for language_content_settings_form.
 *
 * If the content type is translatable and the field is enabled for Scheduler
 * but the translation setting for the publish_on / unpublish_on field does not
 * match the 'published status' field setting then throw a validation error.
 *
 * @see https://www.drupal.org/project/scheduler/issues/2871164
 */
function _scheduler_translation_validate($form, FormStateInterface $form_state) {
  $content_types = $form_state
    ->getValues()['settings']['node'];
  $publishing_enabled_types = array_keys(_scheduler_get_scheduler_enabled_node_types('publish'));
  $unpublishing_enabled_types = array_keys(_scheduler_get_scheduler_enabled_node_types('unpublish'));
  $enabled = [];
  foreach ($content_types as $name => $settings) {
    $enabled['publish_on'] = in_array($name, $publishing_enabled_types);
    $enabled['unpublish_on'] = in_array($name, $unpublishing_enabled_types);
    if ($settings['translatable'] && ($enabled['publish_on'] || $enabled['unpublish_on'])) {
      $params = [
        '@type' => $form['settings']['node'][$name]['settings']['#label'],
        '@status' => $form['settings']['node'][$name]['fields']['status']['#label'],
      ];
      foreach ([
        'publish_on',
        'unpublish_on',
      ] as $var) {
        $mismatch = $enabled[$var] && $settings['fields'][$var] != $settings['fields']['status'];
        if ($mismatch) {
          $params['@scheduler_field'] = $form['settings']['node'][$name]['fields'][$var]['#label'];
          $message = t("Content type '@type' - Translatable settings for status field '@status' and Scheduler field '@scheduler_field' should match, either both on or both off", $params);
          $form_state
            ->setErrorByName("settings][node][{$name}][fields][status", $message);
          $form_state
            ->setErrorByName("settings][node][{$name}][fields][{$var}", $message);
        }
      }
    }
  }
}

/**
 * Implements hook_entity_base_field_info().
 */
function scheduler_entity_base_field_info(EntityTypeInterface $entity_type) {
  $fields = [];
  if ($entity_type
    ->id() === 'node') {
    $fields['publish_on'] = BaseFieldDefinition::create('timestamp')
      ->setLabel(t('Publish on'))
      ->setDisplayOptions('form', [
      'type' => 'datetime_timestamp_no_default',
      'weight' => 30,
    ])
      ->setDisplayConfigurable('form', TRUE)
      ->setTranslatable(TRUE)
      ->setRevisionable(TRUE)
      ->addConstraint('SchedulerPublishOn');
    $fields['unpublish_on'] = BaseFieldDefinition::create('timestamp')
      ->setLabel(t('Unpublish on'))
      ->setDisplayOptions('form', [
      'type' => 'datetime_timestamp_no_default',
      'weight' => 30,
    ])
      ->setDisplayConfigurable('form', TRUE)
      ->setTranslatable(TRUE)
      ->setRevisionable(TRUE)
      ->addConstraint('SchedulerUnpublishOn');
    return $fields;
  }
}

/**
 * Implements hook_views_data_alter().
 */
function scheduler_views_data_alter(array &$data) {

  // By default the 'is null' and 'is not null' operators are only added to the
  // list of filter options if the view contains a relationship. We want them to
  // be always available for the scheduler date fields.
  $data['node_field_data']['publish_on']['filter']['allow empty'] = TRUE;
  $data['node_field_data']['unpublish_on']['filter']['allow empty'] = TRUE;
  $data['node_field_revision']['publish_on']['filter']['allow empty'] = TRUE;
  $data['node_field_revision']['unpublish_on']['filter']['allow empty'] = TRUE;
}

/**
 * Implements hook_ENTITY_TYPE_view() for node entities.
 */
function scheduler_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {

  // If the node is going to be unpublished, then add this information to the
  // header for search engines. Only do this when the current page is the
  // full-page view of the node.
  // @see https://googleblog.blogspot.be/2007/07/robots-exclusion-protocol-now-with-even.html
  if (!empty($node->unpublish_on->value) && node_is_page($node)) {
    $unavailable_after = date(DATE_RFC850, $node->unpublish_on->value);
    $build['#attached']['http_header'][] = [
      'X-Robots-Tag',
      'unavailable_after: ' . $unavailable_after,
    ];
  }
}

/**
 * Implements hook_ENTITY_TYPE_presave() for node entities.
 */
function scheduler_node_presave(EntityInterface $node) {
  $config = \Drupal::config('scheduler.settings');
  $scheduler_manager = \Drupal::service('scheduler.manager');
  $entity = $node->type->entity;
  $request_time = \Drupal::time()
    ->getRequestTime();
  $publish_message = FALSE;
  $unpublish_message = FALSE;

  // If there is no entity object or the class is incorrect then stop here. This
  // should not really happen but it has been observed, so better to be safe.
  // @see https://www.drupal.org/node/2902512
  if (is_null($entity) || !get_class($entity) == 'Drupal\\node\\Entity\\NodeType') {
    return;
  }

  // If this node is being created via Devel Generate then set values for the
  // publish_on and unpublish_on dates as specified in the devel_generate form.
  if (isset($node->devel_generate)) {
    static $publishing_enabled_types;
    static $unpublishing_enabled_types;
    static $publishing_percent;
    static $unpublishing_percent;
    static $time_range;
    if (!isset($publishing_enabled_types)) {
      $publishing_enabled_types = array_keys(_scheduler_get_scheduler_enabled_node_types('publish'));
      $unpublishing_enabled_types = array_keys(_scheduler_get_scheduler_enabled_node_types('unpublish'));

      // The values may not be set if calling via drush, so default to zero.
      $publishing_percent = @$node->devel_generate['scheduler_publishing'] ?: 0;
      $unpublishing_percent = @$node->devel_generate['scheduler_unpublishing'] ?: 0;

      // Reuse the selected 'node creation' time range for our future date span.
      $time_range = $node->devel_generate['time_range'];
    }
    if ($publishing_percent && in_array($node
      ->getType(), $publishing_enabled_types)) {
      if (rand(1, 100) <= $publishing_percent) {

        // Randomly assign a publish_on value in the range starting with the
        // created date and up to the selected time range in the future.
        $node
          ->set('publish_on', rand($node->created->value + 1, $request_time + $time_range));
      }
    }
    if ($unpublishing_percent && in_array($node
      ->getType(), $unpublishing_enabled_types)) {
      if (rand(1, 100) <= $unpublishing_percent) {

        // Randomly assign an unpublish_on value in the range from the later of
        // created date/publish_on date up to the time range in the future.
        $node
          ->set('unpublish_on', rand(max($node->created->value, $node->publish_on->value), $request_time + $time_range));
      }
    }
  }

  // If the node type is enabled for scheduled publishing and has a publish_on
  // date then check if publishing is allowed and if the content needs to be
  // published immediately.
  if ($entity
    ->getThirdPartySetting('scheduler', 'publish_enable', $config
    ->get('default_publish_enable')) && !empty($node->publish_on->value)) {

    // Check that other modules allow the action on this node.
    $publication_allowed = $scheduler_manager
      ->isAllowed($node, 'publish');

    // Publish the node immediately if the publication date is in the past.
    $publish_immediately = $entity
      ->getThirdPartySetting('scheduler', 'publish_past_date', $config
      ->get('default_publish_past_date')) == 'publish';
    if ($publication_allowed && $publish_immediately && $node->publish_on->value <= $request_time) {

      // Trigger the PRE_PUBLISH_INMEDIATELY event so that modules can react
      // before the node has been published.
      $event = new SchedulerEvent($node);
      $scheduler_manager
        ->dispatch($event, SchedulerEvents::PRE_PUBLISH_IMMEDIATELY);
      $node = $event
        ->getNode();

      // Set the 'changed' timestamp to match what would have been done had this
      // content been published via cron.
      $node
        ->setChangedTime($node->publish_on->value);

      // If required, set the created date to match published date.
      if ($entity
        ->getThirdPartySetting('scheduler', 'publish_touch', $config
        ->get('default_publish_touch')) || $node
        ->getCreatedTime() > $node->publish_on->value && $entity
        ->getThirdPartySetting('scheduler', 'publish_past_date_created', $config
        ->get('default_publish_past_date_created'))) {
        $node
          ->setCreatedTime($node->publish_on->value);
      }
      $node->publish_on->value = NULL;
      $node
        ->setPublished();

      // Trigger the PUBLISH_IMMEDIATELY event so that modules can react after
      // the node has been published.
      $event = new SchedulerEvent($node);
      $scheduler_manager
        ->dispatch($event, SchedulerEvents::PUBLISH_IMMEDIATELY);
      $node = $event
        ->getNode();
    }
    else {

      // Ensure the node is unpublished as it will be published by cron later.
      $node
        ->setUnpublished();

      // Only inform the user that the node is scheduled if publication has not
      // been prevented by other modules. Those modules have to display a
      // message themselves explaining why publication is denied.
      $publish_message = $publication_allowed && $entity
        ->getThirdPartySetting('scheduler', 'show_message_after_update', $config
        ->get('default_show_message_after_update'));
    }
  }
  if ($entity
    ->getThirdPartySetting('scheduler', 'unpublish_enable', $config
    ->get('default_unpublish_enable')) && !empty($node->unpublish_on->value)) {

    // Scheduler does not do the same 'immediate' processing for unpublishing.
    // However, the api hook should still be called during presave as there may
    // be messages to be displayed if the unpublishing will be disallowed later.
    $unpublication_allowed = $scheduler_manager
      ->isAllowed($node, 'unpublish');
    $unpublish_message = $unpublication_allowed && $entity
      ->getThirdPartySetting('scheduler', 'show_message_after_update', $config
      ->get('default_show_message_after_update'));
  }

  // Give one message, which will include the publish_on date, the unpublish_on
  // date or both dates. Cannot make the title into a link here when the node
  // is being created. But the node module gives the link in the next message.
  $date_formatter = \Drupal::service('date.formatter');
  if ($publish_message && $unpublish_message) {
    \Drupal::messenger()
      ->addMessage(t('%title is scheduled to be published @publish_time and unpublished @unpublish_time.', [
      '%title' => $node
        ->getTitle(),
      '@publish_time' => $date_formatter
        ->format($node->publish_on->value, 'long'),
      '@unpublish_time' => $date_formatter
        ->format($node->unpublish_on->value, 'long'),
    ]), 'status', FALSE);
  }
  elseif ($publish_message) {
    \Drupal::messenger()
      ->addMessage(t('%title is scheduled to be published @publish_time.', [
      '%title' => $node
        ->getTitle(),
      '@publish_time' => $date_formatter
        ->format($node->publish_on->value, 'long'),
    ]), 'status', FALSE);
  }
  elseif ($unpublish_message) {
    \Drupal::messenger()
      ->addMessage(t('%title is scheduled to be unpublished @unpublish_time.', [
      '%title' => $node
        ->getTitle(),
      '@unpublish_time' => $date_formatter
        ->format($node->unpublish_on->value, 'long'),
    ]), 'status', FALSE);
  }
}

/**
 * Implements hook_ENTITY_TYPE_insert() for node entities.
 */
function scheduler_node_insert(EntityInterface $node) {

  // Removed RULES code but keep the function. There may be code to add here.
  // @todo remove this comment when done. JSS Sep 2016.
}

/**
 * Implements hook_ENTITY_TYPE_update() for node entities.
 */
function scheduler_node_update(EntityInterface $node) {

  // Removed RULES code but keep the function. There may be code to add here.
  // This function is currently called by actions SetPublishingDate and
  // SetUnpublishingDate.
  // @todo remove this comment when done. JSS Sep 2016.
}

/**
 * Implements hook_cron().
 */
function scheduler_cron() {

  // Use drupal_static so that any function can find out if we are running
  // Scheduler cron. Set the default value to FALSE, then turn on the flag.
  // @see scheduler_cron_is_running()
  $scheduler_cron =& drupal_static(__FUNCTION__, FALSE);
  $scheduler_cron = TRUE;

  /** @var \Drupal\scheduler\SchedulerManager $scheduler_manager */
  $scheduler_manager = \Drupal::service('scheduler.manager');
  $scheduler_manager
    ->publish();
  $scheduler_manager
    ->unpublish();

  // Scheduler 7.x provided hook_scheduler_api() which has been replaced by
  // event dispatching in 8.x. Display a warning in the log if any of these
  // hooks still exist, so that admins and developers are informed.
  foreach (Drupal::moduleHandler()
    ->getImplementations('scheduler_api') as $module) {
    \Drupal::logger('scheduler')
      ->warning('Function %function has not been executed. In Drupal 8, implementations of hook_scheduler_api() should be replaced by Scheduler event listeners.', [
      '%function' => $module . '_scheduler_api',
    ]);
  }

  // Reset the static scheduler_cron flag.
  drupal_static_reset(__FUNCTION__);
}

/**
 * Return whether Scheduler cron is running.
 *
 * This function can be called from any Scheduler function, from any contrib
 * module or from custom PHP in a view or rule.
 *
 * @return bool
 *   TRUE if scheduler_cron is currently running. FALSE if not.
 */
function scheduler_cron_is_running() {
  return drupal_static('scheduler_cron');
}

/**
 * Implements hook_entity_extra_field_info().
 */
function scheduler_entity_extra_field_info() {
  $config = \Drupal::config('scheduler.settings');

  // Expose the Scheduler group on the 'Manage Form Display' tab when editing a
  // content type. This allows admins to adjust the weight of the group, and it
  // works for vertical tabs and separate fieldsets.
  $fields = [];
  foreach (NodeType::loadMultiple() as $type) {
    $publishing_enabled = $type
      ->getThirdPartySetting('scheduler', 'publish_enable', $config
      ->get('default_publish_enable'));
    $unpublishing_enabled = $type
      ->getThirdPartySetting('scheduler', 'unpublish_enable', $config
      ->get('default_unpublish_enable'));
    if ($publishing_enabled || $unpublishing_enabled) {

      // Weight 20 puts this below the core fields by default.
      $fields['node'][$type
        ->get('type')]['form']['scheduler_settings'] = [
        'label' => t('Scheduler Dates'),
        'description' => t('Fieldset containing Scheduler Publish-on and Unpublish-on date input fields'),
        'weight' => 20,
      ];
    }
  }
  return $fields;
}

/**
 * Prepares variables for node templates.
 *
 * Makes the publish_on and unpublish_on data available as theme variables.
 *
 * @see template_preprocess_node()
 */
function scheduler_preprocess_node(&$variables) {
  $date_formatter = \Drupal::service('date.formatter');

  /** @var \Drupal\node\NodeInterface $node */
  $node = $variables['node'];
  if (!empty($node->publish_on->value) && $node->publish_on->value && is_numeric($node->publish_on->value)) {
    $variables['publish_on'] = $date_formatter
      ->format($node->publish_on->value, 'long');
  }
  if (!empty($node->unpublish_on->value) && $node->unpublish_on->value && is_numeric($node->unpublish_on->value)) {
    $variables['unpublish_on'] = $date_formatter
      ->format($node->unpublish_on->value, 'long');
  }
}

/**
 * Implements hook_feeds_processor_targets_alter().
 *
 * This function exposes publish_on and unpublish_on as mappable targets to the
 * Feeds module.
 *
 * @todo Port to Drupal 8.
 *
 * @see https://www.drupal.org/node/2651354
 */
function scheduler_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name) {
  $config = \Drupal::config('scheduler.settings');

  // Scheduler module only works on nodes.
  if ($entity_type == 'node') {
    $publishing_enabled = $entity_type
      ->getThirdPartySetting('scheduler', 'publish_enable', $config
      ->get('default_publish_enable'));
    $unpublishing_enabled = $entity_type
      ->getThirdPartySetting('scheduler', 'unpublish_enable', $config
      ->get('default_unpublish_enable'));
    if ($publishing_enabled) {
      $targets['publish_on'] = [
        'name' => t('Scheduler: publish on'),
        'description' => t('The date when the Scheduler module will publish the node.'),
        'callback' => 'scheduler_feeds_set_target',
      ];
    }
    if ($unpublishing_enabled) {
      $targets['unpublish_on'] = [
        'name' => t('Scheduler: unpublish on'),
        'description' => t('The date when the Scheduler module will unpublish the node.'),
        'callback' => 'scheduler_feeds_set_target',
      ];
    }
  }
}

/**
 * Mapping callback for the Feeds module.
 *
 * @todo Port to Drupal 8.
 *
 * @see https://www.drupal.org/node/2651354
 */
function scheduler_feeds_set_target($source, $entity, $target, $value, $mapping) {

  // We expect a string or integer, but can accomodate an array, by taking the
  // first item. Use trim() so that a string of blanks is reduced to empty.
  $value = is_array($value) ? trim(reset($value)) : trim($value);

  // Convert input from parser to timestamp form. If $value is empty or blank
  // then strtotime() must not be used, otherwise it returns the current time.
  if (!empty($value) && !is_numeric($value)) {
    if (!($timestamp = strtotime($value))) {

      // Throw an exception if the date format was not recognized.
      $mapping_source = $mapping['source'];
      throw new FeedsValidationException("Value '{$value}' for '{$mapping_source}' could not be converted to a valid '{$target}' date.");
    }
  }
  else {
    $timestamp = $value;
  }

  // If the timestamp is valid then use it to set the target field in the node.
  if (is_numeric($timestamp) && $timestamp > 0) {
    $entity->{$target} = $timestamp;
  }
}

/**
 * Returns all content types for which scheduler has been enabled.
 *
 * @param string $action
 *   The action that needs to be checked. Can be 'publish' or 'unpublish'.
 *
 * @return \Drupal\node\NodeTypeInterface[]
 *   Array of NodeTypeInterface objects
 */
function _scheduler_get_scheduler_enabled_node_types($action) {
  $config = \Drupal::config('scheduler.settings');
  $node_types = NodeType::loadMultiple();
  return array_filter($node_types, function ($bundle) use ($action, $config) {

    /** @var \Drupal\node\NodeTypeInterface $bundle */
    return $bundle
      ->getThirdPartySetting('scheduler', $action . '_enable', $config
      ->get('default_' . $action . '_enable'));
  });
}

Functions

Namesort descending Description
scheduler_cron Implements hook_cron().
scheduler_cron_is_running Return whether Scheduler cron is running.
scheduler_entity_base_field_info Implements hook_entity_base_field_info().
scheduler_entity_extra_field_info Implements hook_entity_extra_field_info().
scheduler_feeds_processor_targets_alter Implements hook_feeds_processor_targets_alter().
scheduler_feeds_set_target Mapping callback for the Feeds module.
scheduler_form_devel_generate_form_content_alter Implements hook_form_FORM_ID_alter() for devel_generate_form_content.
scheduler_form_language_content_settings_form_alter Implements hook_form_FORM_ID_alter() for language_content_settings_form.
scheduler_form_node_form_alter Implements hook_form_FORM_ID_alter() for node_form().
scheduler_form_node_type_form_alter Implements hook_form_FORM_ID_alter() for node_type_form().
scheduler_help Implements hook_help().
scheduler_node_insert Implements hook_ENTITY_TYPE_insert() for node entities.
scheduler_node_presave Implements hook_ENTITY_TYPE_presave() for node entities.
scheduler_node_update Implements hook_ENTITY_TYPE_update() for node entities.
scheduler_node_view Implements hook_ENTITY_TYPE_view() for node entities.
scheduler_preprocess_node Prepares variables for node templates.
scheduler_views_data_alter Implements hook_views_data_alter().
_scheduler_get_scheduler_enabled_node_types Returns all content types for which scheduler has been enabled.
_scheduler_translation_validate Validation handler for language_content_settings_form.