You are here

public function SchedulerManager::unpublish in Scheduler 8

Same name and namespace in other branches
  1. 2.x src/SchedulerManager.php \Drupal\scheduler\SchedulerManager::unpublish()

Unpublish scheduled nodes.

Return value

bool TRUE if any node has been unpublished, FALSE otherwise.

Throws

\Drupal\scheduler\Exception\SchedulerMissingDateException

\Drupal\scheduler\Exception\SchedulerNodeTypeNotEnabledException

File

src/SchedulerManager.php, line 313

Class

SchedulerManager
Defines a scheduler manager.

Namespace

Drupal\scheduler

Code

public function unpublish() {
  $result = FALSE;
  $action = 'unpublish';

  // Select all nodes of the types that are enabled for scheduled unpublishing
  // and where unpublish_on is less than or equal to the current time.
  $nids = [];
  $scheduler_enabled_types = array_keys(_scheduler_get_scheduler_enabled_node_types($action));
  if (!empty($scheduler_enabled_types)) {
    $query = $this->entityTypeManager
      ->getStorage('node')
      ->getQuery()
      ->exists('unpublish_on')
      ->condition('unpublish_on', $this->time
      ->getRequestTime(), '<=')
      ->condition('type', $scheduler_enabled_types, 'IN')
      ->latestRevision()
      ->sort('unpublish_on')
      ->sort('nid');

    // Disable access checks for this query.
    // @see https://www.drupal.org/node/2700209
    $query
      ->accessCheck(FALSE);
    $nids = $query
      ->execute();
  }

  // Allow other modules to add to the list of nodes to be unpublished.
  $nids = array_unique(array_merge($nids, $this
    ->nidList($action)));

  // Allow other modules to alter the list of nodes to be unpublished.
  $this->moduleHandler
    ->alter('scheduler_nid_list', $nids, $action);

  /** @var \Drupal\node\NodeInterface[] $nodes */
  $nodes = $this
    ->loadNodes($nids);
  foreach ($nodes as $node_multilingual) {

    // The API calls could return nodes of types which are not enabled for
    // scheduled unpublishing. Do not process these.
    if (!$node_multilingual->type->entity
      ->getThirdPartySetting('scheduler', 'unpublish_enable', $this
      ->setting('default_unpublish_enable'))) {
      throw new SchedulerNodeTypeNotEnabledException(sprintf("Node %d '%s' will not be unpublished because node type '%s' is not enabled for scheduled unpublishing", $node_multilingual
        ->id(), $node_multilingual
        ->getTitle(), node_get_type_label($node_multilingual)));
    }
    $languages = $node_multilingual
      ->getTranslationLanguages();
    foreach ($languages as $language) {

      // The object returned by getTranslation() behaves the same as a $node.
      $node = $node_multilingual
        ->getTranslation($language
        ->getId());

      // If the current translation does not have an unpublish on value, or it
      // is later than the date we are processing then move on to the next.
      $unpublish_on = $node->unpublish_on->value;
      if (empty($unpublish_on) || $unpublish_on > $this->time
        ->getRequestTime()) {
        continue;
      }

      // Do not process the node if it still has a publish_on time which is in
      // the past, as this implies that scheduled publishing has been blocked
      // by one of the hook functions we provide, and is still being blocked
      // now that the unpublishing time has been reached.
      $publish_on = $node->publish_on->value;
      if (!empty($publish_on) && $publish_on <= $this->time
        ->getRequestTime()) {
        continue;
      }

      // Check that other modules allow the action on this node.
      if (!$this
        ->isAllowed($node, $action)) {
        continue;
      }

      // $node->setChangedTime($unpublish_on) will fail badly if an API call
      // has removed the date. Trap this as an exception here and give a
      // meaningful message.
      // @todo This will now never be thrown due to the empty(unpublish_on)
      // check above to cater for translations. Remove this exception?
      if (empty($unpublish_on)) {
        $field_definitions = $this->entityTypeManager
          ->getFieldDefinitions('node', $node
          ->getType());
        $field = (string) $field_definitions['unpublish_on']
          ->getLabel();
        throw new SchedulerMissingDateException(sprintf("Node %d '%s' will not be unpublished because field '%s' has no value", $node
          ->id(), $node
          ->getTitle(), $field));
      }

      // Trigger the PRE_UNPUBLISH event so that modules can react before the
      // node is unpublished.
      $event = new SchedulerEvent($node);
      $this
        ->dispatch($event, SchedulerEvents::PRE_UNPUBLISH);
      $node = $event
        ->getNode();

      // Update 'changed' timestamp.
      $node
        ->setChangedTime($unpublish_on);
      $create_unpublishing_revision = $node->type->entity
        ->getThirdPartySetting('scheduler', 'unpublish_revision', $this
        ->setting('default_unpublish_revision'));
      if ($create_unpublishing_revision) {
        $node
          ->setNewRevision();

        // Use a core date format to guarantee a time is included.
        $revision_log_message = $this
          ->t('Unpublished by Scheduler. The scheduled unpublishing date was @unpublish_on.', [
          '@unpublish_on' => $this->dateFormatter
            ->format($unpublish_on, 'short'),
        ]);

        // Create the new revision, setting message and revision timestamp.
        $node
          ->setRevisionLogMessage($revision_log_message)
          ->setRevisionCreationTime($this->time
          ->getRequestTime());
      }

      // Unset unpublish_on so the node will not get rescheduled by subsequent
      // calls to $node->save().
      $node->unpublish_on->value = NULL;

      // Invoke all implementations of hook_scheduler_unpublish_action() to
      // allow other modules to do the "unpublishing" process instead of
      // Scheduler.
      $hook = 'scheduler_unpublish_action';
      $processed = FALSE;
      $failed = FALSE;
      foreach ($this->moduleHandler
        ->getImplementations($hook) as $module) {
        $function = $module . '_' . $hook;
        $return = $function($node);
        $processed = $processed || $return === 1;
        $failed = $failed || $return === -1;
      }

      // Set up the log variables.
      $view_link = $node
        ->toLink($this
        ->t('View node'));
      $node_type = $this->entityTypeManager
        ->getStorage('node_type')
        ->load($node
        ->bundle());
      $node_type_link = $node_type
        ->toLink($this
        ->t('@label settings', [
        '@label' => $node_type
          ->label(),
      ]), 'edit-form');
      $logger_variables = [
        '@type' => $node_type
          ->label(),
        '%title' => $node
          ->getTitle(),
        'link' => $node_type_link
          ->toString() . ' ' . $view_link
          ->toString(),
        '@hook' => 'hook_' . $hook,
      ];
      if ($failed) {

        // At least one hook function returned a failure or exception, so stop
        // processing this node and move on to the next one.
        $this->logger
          ->warning('Unpublishing failed for %title. Calls to @hook returned a failure code.', $logger_variables);
        continue;
      }
      elseif ($processed) {

        // The node has 'unpublishing' processed by a module implementing the
        // hook, so no need to do anything more, apart from log this result.
        $this->logger
          ->notice('@type: scheduled processing of %title completed by calls to @hook.', $logger_variables);
      }
      else {

        // None of the above hook calls processed the node and there were no
        // errors detected so set the node to unpublished.
        $this->logger
          ->notice('@type: scheduled unpublishing of %title.', $logger_variables);
        $node
          ->setUnpublished();
      }

      // Invoke event to tell Rules that Scheduler has unpublished this node.
      if ($this->moduleHandler
        ->moduleExists('scheduler_rules_integration')) {
        _scheduler_rules_integration_dispatch_cron_event($node, 'unpublish');
      }

      // Trigger the UNPUBLISH event so that modules can react after the node
      // is unpublished.
      $event = new SchedulerEvent($node);
      $this
        ->dispatch($event, SchedulerEvents::UNPUBLISH);

      // Use the standard actions system to unpublish and save the node.
      $node = $event
        ->getNode();
      $action_id = 'node_unpublish_action';
      if ($this->moduleHandler
        ->moduleExists('workbench_moderation_actions')) {

        // workbench_moderation_actions module uses a custom action instead.
        $action_id = 'state_change__node__archived';
      }
      $this->entityTypeManager
        ->getStorage('action')
        ->load($action_id)
        ->getPlugin()
        ->execute($node);
      $result = TRUE;
    }
  }
  return $result;
}