AggregatorController.php 14.3 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\aggregator\Controller\AggregatorController.
6 7
 */

8
namespace Drupal\aggregator\Controller;
9

10
use Drupal\Component\Utility\Xss;
11
use Drupal\Core\Controller\ControllerBase;
12
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
13 14 15
use Drupal\aggregator\CategoryStorageControllerInterface;
use Drupal\aggregator\FeedInterface;
use Drupal\aggregator\ItemInterface;
16
use Drupal\Core\Database\Connection;
17 18
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\HttpFoundation\Response;
20
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
21 22 23 24

/**
 * Returns responses for aggregator module routes.
 */
25
class AggregatorController extends ControllerBase implements ContainerInjectionInterface {
26

27
  /**
28
   * The database connection.
29
   *
30
   * @var \Drupal\Core\Database\Connection;
31
   */
32
  protected $database;
33 34

  /**
35
   * The category storage controller.
36
   *
37
   * @var \Drupal\aggregator\CategoryStorageControllerInterface
38
   */
39
  protected $categoryStorage;
40

41
  /**
42
   * Constructs a \Drupal\aggregator\Controller\AggregatorController object.
43
   *
44 45
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection.
46 47
   * @param \Drupal\aggregator\CategoryStorageControllerInterface $category_storage
   *   The category storage service.
48
   */
49
  public function __construct(Connection $database, CategoryStorageControllerInterface $category_storage) {
50
    $this->database = $database;
51
    $this->categoryStorage = $category_storage;
52 53 54 55 56 57
  }

  /**
   * {inheritdoc}
   */
  public static function create(ContainerInterface $container) {
58
    return new static(
59
      $container->get('database'),
60
      $container->get('aggregator.category.storage')
61
    );
62 63 64 65 66 67 68 69 70
  }

  /**
   * Presents the aggregator feed creation form.
   *
   * @return array
   *   A form array as expected by drupal_render().
   */
  public function feedAdd() {
71 72
    $entity_manager = $this->entityManager();
    $feed = $entity_manager->getStorageController('aggregator_feed')
73 74 75
      ->create(array(
        'refresh' => 3600,
      ));
76 77 78 79 80 81 82 83 84 85 86 87 88 89
    return $entity_manager->getForm($feed);
  }

  /**
   * Displays all the items captured from the particular feed.
   *
   * @param \Drupal\aggregator\FeedInterface $aggregator_feed
   *   The feed for which to display all items.
   *
   * @return array
   *   The rendered list of items for the feed.
   */
  public function viewFeed(FeedInterface $aggregator_feed) {
    $entity_manager = $this->entityManager();
90
    $feed_source = $entity_manager->getViewBuilder('aggregator_feed')
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
      ->view($aggregator_feed, 'default');
    // Load aggregator feed item for the particular feed id.
    $items = $entity_manager->getStorageController('aggregator_item')->loadByFeed($aggregator_feed->id());
    // Print the feed items.
    $build = $this->buildPageList($items, $feed_source);
    return $build;
  }

  /**
   * Displays feed items aggregated in a category.
   *
   * @param int $cid
   *   The category id for which to list all of the aggregated items.
   *
   * @return array
   *   The render array with list of items for the feed.
   */
  public function viewCategory($cid) {
    $items = $this->entityManager()->getStorageController('aggregator_item')->loadByCategory($cid);
    $build = $this->buildPageList($items);
    return $build;
  }

  /**
   * Builds a listing of aggregator feed items.
   *
   * @param \Drupal\aggregator\ItemInterface[] $items
   *   The items to be listed.
   * @param array|string $feed_source
   *   The feed source URL.
   *
   * @return array
   *   The rendered list of items for the feed.
   */
  protected function buildPageList(array $items, $feed_source = '') {
    // Assemble output.
    $build = array(
      '#type' => 'container',
      '#attributes' => array('class' => array('aggregator-wrapper')),
    );
    $build['feed_source'] = is_array($feed_source) ? $feed_source : array('#markup' => $feed_source);
    if ($items) {
133
      $build['items'] = $this->entityManager()->getViewBuilder('aggregator_item')
134 135 136 137
        ->viewMultiple($items, 'default');
      $build['pager'] = array('#theme' => 'pager');
    }
    return $build;
138 139
  }

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
  /**
   * Refreshes a feed, then redirects to the overview page.
   *
   * @param \Drupal\aggregator\FeedInterface $aggregator_feed
   *   An object describing the feed to be refreshed.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request object containing the search string.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirection to the admin overview page.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
   *   If the query token is missing or invalid.
   */
  public function feedRefresh(FeedInterface $aggregator_feed, Request $request) {
    // @todo CSRF tokens are validated in page callbacks rather than access
    //   callbacks, because access callbacks are also invoked during menu link
    //   generation. Add token support to routing: http://drupal.org/node/755584.
    $token = $request->query->get('token');
    if (!isset($token) || !drupal_valid_token($token, 'aggregator/update/' . $aggregator_feed->id())) {
      throw new AccessDeniedHttpException();
    }

    // @todo after https://drupal.org/node/1972246 find a new place for it.
    aggregator_refresh($aggregator_feed);
165
    return $this->redirect('aggregator.admin_overview');
166 167
  }

168 169 170 171 172 173 174
  /**
   * Displays the aggregator administration page.
   *
   * @return array
   *   A render array as expected by drupal_render().
   */
  public function adminOverview() {
175
    $result = $this->database->query('SELECT f.fid, f.title, f.url, f.refresh, f.checked, f.link, f.description, f.hash, f.etag, f.modified, f.image, COUNT(i.iid) AS items FROM {aggregator_feed} f LEFT JOIN {aggregator_item} i ON f.fid = i.fid GROUP BY f.fid, f.title, f.url, f.refresh, f.checked, f.link, f.description, f.hash, f.etag, f.modified, f.image ORDER BY f.title');
176

177
    $header = array($this->t('Title'), $this->t('Items'), $this->t('Last update'), $this->t('Next update'), $this->t('Operations'));
178 179 180 181 182
    $rows = array();
    foreach ($result as $feed) {
      $row = array();
      $row[] = l($feed->title, "aggregator/sources/$feed->fid");
      $row[] = format_plural($feed->items, '1 item', '@count items');
183 184
      $row[] = ($feed->checked ? $this->t('@time ago', array('@time' => format_interval(REQUEST_TIME - $feed->checked))) : $this->t('never'));
      $row[] = ($feed->checked && $feed->refresh ? $this->t('%time left', array('%time' => format_interval($feed->checked + $feed->refresh - REQUEST_TIME))) : $this->t('never'));
185 186
      $links = array();
      $links['edit'] = array(
187
        'title' => $this->t('Edit'),
188 189
        'route_name' => 'aggregator.feed_edit',
        'route_parameters' => array('aggregator_feed' => $feed->fid),
190 191
      );
      $links['delete'] = array(
192
        'title' => $this->t('Delete'),
193 194
        'route_name' => 'aggregator.feed_delete',
        'route_parameters' => array('aggregator_feed' => $feed->fid),
195 196
      );
      $links['remove'] = array(
197
        'title' => $this->t('Remove items'),
198 199
        'route_name' => 'aggregator.feed_items_delete',
        'route_parameters' => array('aggregator_feed' => $feed->fid),
200 201
      );
      $links['update'] = array(
202
        'title' => $this->t('Update items'),
203 204
        'route_name' => 'aggregator.feed_refresh',
        'route_parameters' => array('aggregator_feed' => $feed->fid),
205 206 207 208 209 210 211 212 213 214 215
        'query' => array('token' => drupal_get_token("aggregator/update/$feed->fid")),
      );
      $row[] = array(
        'data' => array(
          '#type' => 'operations',
          '#links' => $links,
        ),
      );
      $rows[] = $row;
    }
    $build['feeds'] = array(
216
      '#prefix' => '<h3>' . $this->t('Feed overview') . '</h3>',
217 218 219
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $rows,
220
      '#empty' => $this->t('No feeds available. <a href="@link">Add feed</a>.', array('@link' => $this->urlGenerator()->generateFromPath('admin/config/services/aggregator/add/feed'))),
221 222 223 224
    );

    $result = $this->database->query('SELECT c.cid, c.title, COUNT(ci.iid) as items FROM {aggregator_category} c LEFT JOIN {aggregator_category_item} ci ON c.cid = ci.cid GROUP BY c.cid, c.title ORDER BY title');

225
    $header = array($this->t('Title'), $this->t('Items'), $this->t('Operations'));
226 227 228 229 230 231 232
    $rows = array();
    foreach ($result as $category) {
      $row = array();
      $row[] = l($category->title, "aggregator/categories/$category->cid");
      $row[] = format_plural($category->items, '1 item', '@count items');
      $links = array();
      $links['edit'] = array(
233
        'title' => $this->t('Edit'),
234 235
        'route_name' => 'aggregator.category_admin_edit',
        'route_parameters' => array('cid' => $category->cid),
236
      );
237
      $links['delete'] = array(
238
        'title' => $this->t('Delete'),
239 240
        'route_name' => 'aggregator.category_delete',
        'route_parameters' => array('cid' => $category->cid),
241
      );
242 243 244 245 246 247 248 249 250
      $row[] = array(
        'data' => array(
          '#type' => 'operations',
          '#links' => $links,
        ),
      );
      $rows[] = $row;
    }
    $build['categories'] = array(
251
      '#prefix' => '<h3>' . $this->t('Category overview') . '</h3>',
252 253 254
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $rows,
255
      '#empty' => $this->t('No categories available. <a href="@link">Add category</a>.', array('@link' => $this->urlGenerator()->generateFromPath('admin/config/services/aggregator/add/category'))),
256 257 258 259 260
    );

    return $build;
  }

261 262 263 264 265 266 267
  /**
   * Displays all the categories used by the Aggregator module.
   *
   * @return array
   *   A render array.
   */
  public function categories() {
268
    $entity_manager = $this->entityManager();
269 270 271 272 273 274 275
    $result = $this->database->query('SELECT c.cid, c.title, c.description FROM {aggregator_category} c LEFT JOIN {aggregator_category_item} ci ON c.cid = ci.cid LEFT JOIN {aggregator_item} i ON ci.iid = i.iid GROUP BY c.cid, c.title, c.description');

    $build = array(
      '#type' => 'container',
      '#attributes' => array('class' => array('aggregator-wrapper')),
      '#sorted' => TRUE,
    );
276
    $aggregator_summary_items = $this->config('aggregator.settings')->get('source.list_max');
277 278 279
    foreach ($result as $category) {
      $summary_items = array();
      if ($aggregator_summary_items) {
280 281
        $items = $entity_manager->getStorageController('aggregator_item')->loadByCategory($category->cid);
        if ($items) {
282
          $summary_items = $entity_manager->getViewBuilder('aggregator_item')->viewMultiple($items, 'summary');
283 284
        }
      }
285
      $category->url = $this->urlGenerator()->generateFromPath('aggregator/categories/' . $category->cid);
286 287 288 289 290 291 292 293 294
      $build[$category->cid] = array(
        '#theme' => 'aggregator_summary_items',
        '#summary_items' => $summary_items,
        '#source' => $category,
      );
    }
    return $build;
  }

295 296 297 298 299 300 301
  /**
   * Displays the most recent items gathered from any feed.
   *
   * @return string
   *   The rendered list of items for the feed.
   */
  public function pageLast() {
302
    $items = $this->entityManager()->getStorageController('aggregator_item')->loadAll();
303 304 305
    $build = $this->buildPageList($items);
    $build['#attached']['drupal_add_feed'][] = array('aggregator/rss', $this->config('system.site')->get('name') . ' ' . $this->t('aggregator'));
    return $build;
306
  }
307 308 309 310 311 312 313 314

  /**
   * Displays all the feeds used by the Aggregator module.
   *
   * @return array
   *   A render array as expected by drupal_render().
   */
  public function sources() {
315
    $entity_manager = $this->entityManager();
316

317
    $feeds = $entity_manager->getStorageController('aggregator_feed')->loadMultiple();
318 319 320 321 322 323 324 325 326 327

    $build = array(
      '#type' => 'container',
      '#attributes' => array('class' => array('aggregator-wrapper')),
      '#sorted' => TRUE,
    );

    foreach ($feeds as $feed) {
      // Most recent items:
      $summary_items = array();
328
      $aggregator_summary_items = $this->config('aggregator.settings')
329 330
        ->get('source.list_max');
      if ($aggregator_summary_items) {
331 332 333
        $items = $entity_manager->getStorageController('aggregator_item')
          ->loadByFeed($feed->id());
        if ($items) {
334
          $summary_items = $entity_manager->getViewBuilder('aggregator_item')
335 336 337
            ->viewMultiple($items, 'summary');
        }
      }
338
      $feed->url = $this->urlGenerator()->generateFromRoute('aggregator.feed_view', array('aggregator_feed' => $feed->id()));
339 340 341 342 343 344 345 346 347
      $build[$feed->id()] = array(
        '#theme' => 'aggregator_summary_items',
        '#summary_items' => $summary_items,
        '#source' => $feed,
      );
    }
    $build['feed_icon'] = array(
      '#theme' => 'feed_icon',
      '#url' => 'aggregator/opml',
348
      '#title' => $this->t('OPML feed'),
349 350 351 352
    );
    return $build;
  }

353
  /**
354 355 356 357 358 359 360 361
   * Generates an OPML representation of all feeds or feeds by category.
   *
   * @param int $cid
   *   (optional) If set, feeds are exported only from a category with this ID.
   *   Otherwise, all feeds are exported. Defaults to NULL.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   The response containing the OPML.
362 363
   */
  public function opmlPage($cid = NULL) {
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
    if ($cid) {
      $result = $this->database->query('SELECT f.title, f.url FROM {aggregator_feed} f LEFT JOIN {aggregator_category_feed} c on f.fid = c.fid WHERE c.cid = :cid ORDER BY title', array(':cid' => $cid));
    }
    else {
      $result = $this->database->query('SELECT * FROM {aggregator_feed} ORDER BY title');
    }

    $feeds = $result->fetchAll();
    $aggregator_page_opml = array(
      '#theme' => 'aggregator_page_opml',
      '#feeds' => $feeds,
    );
    $output = drupal_render($aggregator_page_opml);

    $response = new Response();
    $response->headers->set('Content-Type', 'text/xml; charset=utf-8');
    $response->setContent($output);

    return $response;
383 384
  }

385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
  /**
   * Route title callback.
   *
   * @param \Drupal\aggregator\FeedInterface $aggregator_feed
   *   The aggregator feed.
   *
   * @return string
   *   The feed label.
   */
  public function feedTitle(FeedInterface $aggregator_feed) {
    return Xss::filter($aggregator_feed->label());
  }

  /**
   * Route title callback.
   *
   * @param int $cid
   *   The category ID.
   *
   * @return string
   *   The category label.
   */
  public function categoryTitle($cid) {
    $category = $this->categoryStorage->load($cid);
    return Xss::filter($category->title);
  }

412
}