DefaultProcessor.php 9.97 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\aggregator\Plugin\aggregator\processor\DefaultProcessor.
 */

namespace Drupal\aggregator\Plugin\aggregator\processor;

10
use Drupal\aggregator\ItemStorageInterface;
11
use Drupal\aggregator\Plugin\AggregatorPluginSettingsBase;
12
use Drupal\aggregator\Plugin\ProcessorInterface;
13
use Drupal\aggregator\FeedInterface;
14
use Drupal\Component\Utility\Unicode;
15
use Drupal\Core\Config\ConfigFactoryInterface;
16
use Drupal\Core\Datetime\DateFormatterInterface;
17
use Drupal\Core\Entity\Query\QueryInterface;
18
use Drupal\Core\Form\ConfigFormBaseTrait;
19
use Drupal\Core\Form\FormStateInterface;
20
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
21
use Drupal\Core\Routing\UrlGeneratorTrait;
22
use Symfony\Component\DependencyInjection\ContainerInterface;
23 24 25 26 27 28

/**
 * Defines a default processor implementation.
 *
 * Creates lightweight records from feed items.
 *
29
 * @AggregatorProcessor(
30 31 32 33 34
 *   id = "aggregator",
 *   title = @Translation("Default processor"),
 *   description = @Translation("Creates lightweight records from feed items.")
 * )
 */
35
class DefaultProcessor extends AggregatorPluginSettingsBase implements ProcessorInterface, ContainerFactoryPluginInterface {
36
  use ConfigFormBaseTrait;
37 38
  use UrlGeneratorTrait;

39 40 41
  /**
   * Contains the configuration object factory.
   *
42
   * @var \Drupal\Core\Config\ConfigFactoryInterface
43 44 45
   */
  protected $configFactory;

46 47 48 49 50 51 52 53
  /**
   * The entity query object for feed items.
   *
   * @var \Drupal\Core\Entity\Query\QueryInterface
   */
  protected $itemQuery;

  /**
54
   * The entity storage for items.
55
   *
56
   * @var \Drupal\aggregator\ItemStorageInterface
57 58 59
   */
  protected $itemStorage;

60 61 62
  /**
   * The date formatter service.
   *
63
   * @var \Drupal\Core\Datetime\DateFormatterInterface
64 65 66
   */
  protected $dateFormatter;

67 68 69 70 71 72 73
  /**
   * Constructs a DefaultProcessor object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
74
   * @param mixed $plugin_definition
75
   *   The plugin implementation definition.
76
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config
77
   *   The configuration factory object.
78 79
   * @param \Drupal\Core\Entity\Query\QueryInterface $item_query
   *   The entity query object for feed items.
80 81
   * @param \Drupal\aggregator\ItemStorageInterface $item_storage
   *   The entity storage for feed items.
82
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
83
   *   The date formatter service.
84
   */
85
  public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigFactoryInterface $config, QueryInterface $item_query, ItemStorageInterface $item_storage, DateFormatterInterface $date_formatter) {
86
    $this->configFactory = $config;
87 88
    $this->itemStorage = $item_storage;
    $this->itemQuery = $item_query;
89
    $this->dateFormatter = $date_formatter;
90 91 92 93 94 95 96 97
    // @todo Refactor aggregator plugins to ConfigEntity so merging
    //   the configuration here is not needed.
    parent::__construct($configuration + $this->getConfiguration(), $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
98
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
99 100 101 102
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
103 104
      $container->get('config.factory'),
      $container->get('entity.query')->get('aggregator_item'),
105
      $container->get('entity.manager')->getStorage('aggregator_item'),
106
      $container->get('date.formatter')
107 108
    );
  }
109

110 111 112 113 114 115 116
  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['aggregator.settings'];
  }

117
  /**
118
   * {@inheritdoc}
119
   */
120
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
121 122
    $config = $this->config('aggregator.settings');
    $processors = $config->get('processors');
123
    $info = $this->getPluginDefinition();
124 125
    $counts = array(3, 5, 10, 15, 20, 25);
    $items = array_map(function ($count) {
126
      return $this->formatPlural($count, '1 item', '@count items');
127 128
    }, array_combine($counts, $counts));
    $intervals = array(3600, 10800, 21600, 32400, 43200, 86400, 172800, 259200, 604800, 1209600, 2419200, 4838400, 9676800);
129
    $period = array_map(array($this->dateFormatter, 'formatInterval'), array_combine($intervals, $intervals));
130 131 132 133 134 135 136 137 138
    $period[AGGREGATOR_CLEAR_NEVER] = t('Never');

    $form['processors'][$info['id']] = array();
    // Only wrap into details if there is a basic configuration.
    if (isset($form['basic_conf'])) {
      $form['processors'][$info['id']] = array(
        '#type' => 'details',
        '#title' => t('Default processor settings'),
        '#description' => $info['description'],
139
        '#open' => in_array($info['id'], $processors),
140 141 142 143 144 145
      );
    }

    $form['processors'][$info['id']]['aggregator_summary_items'] = array(
      '#type' => 'select',
      '#title' => t('Number of items shown in listing pages'),
146
      '#default_value' => $config->get('source.list_max'),
147 148 149 150 151 152 153
      '#empty_value' => 0,
      '#options' => $items,
    );

    $form['processors'][$info['id']]['aggregator_clear'] = array(
      '#type' => 'select',
      '#title' => t('Discard items older than'),
154
      '#default_value' => $config->get('items.expire'),
155
      '#options' => $period,
156
      '#description' => t('Requires a correctly configured <a href=":cron">cron maintenance task</a>.', array(':cron' => $this->url('system.status'))),
157 158
    );

159 160
    $lengths = array(0, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000);
    $options = array_map(function($length) {
161
      return ($length == 0) ? t('Unlimited') : $this->formatPlural($length, '1 character', '@count characters');
162 163
    }, array_combine($lengths, $lengths));

164 165 166
    $form['processors'][$info['id']]['aggregator_teaser_length'] = array(
      '#type' => 'select',
      '#title' => t('Length of trimmed description'),
167
      '#default_value' => $config->get('items.teaser_length'),
168
      '#options' => $options,
169
      '#description' => t('The maximum number of characters used in the trimmed version of content.'),
170 171 172 173 174
    );
    return $form;
  }

  /**
175
   * {@inheritdoc}
176
   */
177
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
178 179 180
    $this->configuration['items']['expire'] = $form_state->getValue('aggregator_clear');
    $this->configuration['items']['teaser_length'] = $form_state->getValue('aggregator_teaser_length');
    $this->configuration['source']['list_max'] = $form_state->getValue('aggregator_summary_items');
181 182
    // @todo Refactor aggregator plugins to ConfigEntity so this is not needed.
    $this->setConfiguration($this->configuration);
183 184 185
  }

  /**
186
   * {@inheritdoc}
187
   */
188
  public function process(FeedInterface $feed) {
189 190 191 192
    if (!is_array($feed->items)) {
      return;
    }
    foreach ($feed->items as $item) {
193
      // @todo: The default entity view builder always returns an empty
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
      //   array, which is ignored in aggregator_save_item() currently. Should
      //   probably be fixed.
      if (empty($item['title'])) {
        continue;
      }

      // Save this item. Try to avoid duplicate entries as much as possible. If
      // we find a duplicate entry, we resolve it and pass along its ID is such
      // that we can update it if needed.
      if (!empty($item['guid'])) {
        $values = array('fid' => $feed->id(), 'guid' => $item['guid']);
      }
      elseif ($item['link'] && $item['link'] != $feed->link && $item['link'] != $feed->url) {
        $values = array('fid' => $feed->id(), 'link' => $item['link']);
      }
      else {
        $values = array('fid' => $feed->id(), 'title' => $item['title']);
      }

      // Try to load an existing entry.
      if ($entry = entity_load_multiple_by_properties('aggregator_item', $values)) {
        $entry = reset($entry);
      }
      else {
218
        $entry = entity_create('aggregator_item', array('langcode' => $feed->language()->getId()));
219 220
      }
      if ($item['timestamp']) {
221
        $entry->setPostedTime($item['timestamp']);
222 223 224
      }

      // Make sure the item title and author fit in the 255 varchar column.
225 226
      $entry->setTitle(Unicode::truncate($item['title'], 255, TRUE, TRUE));
      $entry->setAuthor(Unicode::truncate($item['author'], 255, TRUE, TRUE));
227

228 229 230
      $entry->setFeedId($feed->id());
      $entry->setLink($item['link']);
      $entry->setGuid($item['guid']);
231 232 233 234 235 236 237

      $description = '';
      if (!empty($item['description'])) {
        $description = $item['description'];
      }
      $entry->setDescription($description);

238 239 240 241 242
      $entry->save();
    }
  }

  /**
243
   * {@inheritdoc}
244
   */
245
  public function delete(FeedInterface $feed) {
246 247
    if ($items = $this->itemStorage->loadByFeed($feed->id())) {
      $this->itemStorage->delete($items);
248 249
    }
    // @todo This should be moved out to caller with a different message maybe.
250
    drupal_set_message(t('The news items from %site have been deleted.', array('%site' => $feed->label())));
251 252 253 254 255 256 257
  }

  /**
   * Implements \Drupal\aggregator\Plugin\ProcessorInterface::postProcess().
   *
   * Expires items from a feed depending on expiration settings.
   */
258
  public function postProcess(FeedInterface $feed) {
259
    $aggregator_clear = $this->configuration['items']['expire'];
260 261

    if ($aggregator_clear != AGGREGATOR_CLEAR_NEVER) {
262
      // Delete all items that are older than flush item timer.
263
      $age = REQUEST_TIME - $aggregator_clear;
264 265 266 267 268 269 270
      $result = $this->itemQuery
        ->condition('fid', $feed->id())
        ->condition('timestamp', $age, '<')
        ->execute();
      if ($result) {
        $entities = $this->itemStorage->loadMultiple($result);
        $this->itemStorage->delete($entities);
271 272 273 274
      }
    }
  }

275 276 277 278 279 280 281 282 283 284 285
  /**
   * {@inheritdoc}
   */
  public function getConfiguration() {
    return $this->configFactory->get('aggregator.settings')->get();
  }

  /**
   * {@inheritdoc}
   */
  public function setConfiguration(array $configuration) {
286
    $config = $this->config('aggregator.settings');
287 288 289 290 291 292
    foreach ($configuration as $key => $value) {
      $config->set($key, $value);
    }
    $config->save();
  }

293
}