Issue #3264120 by Spokje, catch, Taran2L, danflanagan8, xjm, quietone, ckrina: Remove aggregator module and our dependency on Laminas Feed

merge-requests/1968/head
Alex Pott 2022-03-29 14:38:11 +01:00
parent 4d32bbccb8
commit 0e2ea433bf
No known key found for this signature in database
GPG Key ID: BDA67E7EE836E5CE
202 changed files with 18 additions and 125383 deletions

202
composer.lock generated
View File

@ -440,7 +440,7 @@
"dist": {
"type": "path",
"url": "core",
"reference": "ac2e42b6e2a05971e9324054cd4ec367fd15153f"
"reference": "1e12f175c473069f046c6c6252308444f7581692"
},
"require": {
"asm89/stack-cors": "^2.0.2",
@ -462,7 +462,6 @@
"ext-xml": "*",
"guzzlehttp/guzzle": "^7.3.0",
"guzzlehttp/psr7": "^2.2.0",
"laminas/laminas-feed": "^2.12",
"masterminds/html5": "^2.1",
"pear/archive_tar": "^1.4.14",
"php": ">=8.1.0",
@ -488,7 +487,6 @@
},
"replace": {
"drupal/action": "self.version",
"drupal/aggregator": "self.version",
"drupal/automated_cron": "self.version",
"drupal/ban": "self.version",
"drupal/bartik": "self.version",
@ -1136,204 +1134,6 @@
],
"time": "2022-03-20T21:55:58+00:00"
},
{
"name": "laminas/laminas-escaper",
"version": "2.9.0",
"source": {
"type": "git",
"url": "https://github.com/laminas/laminas-escaper.git",
"reference": "891ad70986729e20ed2e86355fcf93c9dc238a5f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laminas/laminas-escaper/zipball/891ad70986729e20ed2e86355fcf93c9dc238a5f",
"reference": "891ad70986729e20ed2e86355fcf93c9dc238a5f",
"shasum": ""
},
"require": {
"php": "^7.3 || ~8.0.0 || ~8.1.0"
},
"conflict": {
"zendframework/zend-escaper": "*"
},
"require-dev": {
"laminas/laminas-coding-standard": "~2.3.0",
"phpunit/phpunit": "^9.3",
"psalm/plugin-phpunit": "^0.12.2",
"vimeo/psalm": "^3.16"
},
"suggest": {
"ext-iconv": "*",
"ext-mbstring": "*"
},
"type": "library",
"autoload": {
"psr-4": {
"Laminas\\Escaper\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"description": "Securely and safely escape HTML, HTML attributes, JavaScript, CSS, and URLs",
"homepage": "https://laminas.dev",
"keywords": [
"escaper",
"laminas"
],
"support": {
"chat": "https://laminas.dev/chat",
"docs": "https://docs.laminas.dev/laminas-escaper/",
"forum": "https://discourse.laminas.dev",
"issues": "https://github.com/laminas/laminas-escaper/issues",
"rss": "https://github.com/laminas/laminas-escaper/releases.atom",
"source": "https://github.com/laminas/laminas-escaper"
},
"funding": [
{
"url": "https://funding.communitybridge.org/projects/laminas-project",
"type": "community_bridge"
}
],
"time": "2021-09-02T17:10:53+00:00"
},
{
"name": "laminas/laminas-feed",
"version": "2.16.0",
"source": {
"type": "git",
"url": "https://github.com/laminas/laminas-feed.git",
"reference": "cbd0e10c867a1efa6594164d229d8caf4a4ae4c7"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laminas/laminas-feed/zipball/cbd0e10c867a1efa6594164d229d8caf4a4ae4c7",
"reference": "cbd0e10c867a1efa6594164d229d8caf4a4ae4c7",
"shasum": ""
},
"require": {
"ext-dom": "*",
"ext-libxml": "*",
"laminas/laminas-escaper": "^2.9",
"laminas/laminas-stdlib": "^3.6",
"php": "^7.3 || ~8.0.0 || ~8.1.0"
},
"conflict": {
"laminas/laminas-servicemanager": "<3.3",
"zendframework/zend-feed": "*"
},
"require-dev": {
"laminas/laminas-cache": "^2.7.2",
"laminas/laminas-coding-standard": "~2.2.1",
"laminas/laminas-db": "^2.13.3",
"laminas/laminas-http": "^2.15",
"laminas/laminas-servicemanager": "^3.7",
"laminas/laminas-validator": "^2.15",
"phpunit/phpunit": "^9.5.5",
"psalm/plugin-phpunit": "^0.13.0",
"psr/http-message": "^1.0.1",
"vimeo/psalm": "^4.1"
},
"suggest": {
"laminas/laminas-cache": "Laminas\\Cache component, for optionally caching feeds between requests",
"laminas/laminas-db": "Laminas\\Db component, for use with PubSubHubbub",
"laminas/laminas-http": "Laminas\\Http for PubSubHubbub, and optionally for use with Laminas\\Feed\\Reader",
"laminas/laminas-servicemanager": "Laminas\\ServiceManager component, for easily extending ExtensionManager implementations",
"laminas/laminas-validator": "Laminas\\Validator component, for validating email addresses used in Atom feeds and entries when using the Writer subcomponent",
"psr/http-message": "PSR-7 ^1.0.1, if you wish to use Laminas\\Feed\\Reader\\Http\\Psr7ResponseDecorator"
},
"type": "library",
"autoload": {
"psr-4": {
"Laminas\\Feed\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"description": "provides functionality for consuming RSS and Atom feeds",
"homepage": "https://laminas.dev",
"keywords": [
"feed",
"laminas"
],
"support": {
"chat": "https://laminas.dev/chat",
"docs": "https://docs.laminas.dev/laminas-feed/",
"forum": "https://discourse.laminas.dev",
"issues": "https://github.com/laminas/laminas-feed/issues",
"rss": "https://github.com/laminas/laminas-feed/releases.atom",
"source": "https://github.com/laminas/laminas-feed"
},
"funding": [
{
"url": "https://funding.communitybridge.org/projects/laminas-project",
"type": "community_bridge"
}
],
"time": "2021-12-17T09:12:35+00:00"
},
{
"name": "laminas/laminas-stdlib",
"version": "3.7.1",
"source": {
"type": "git",
"url": "https://github.com/laminas/laminas-stdlib.git",
"reference": "bcd869e2fe88d567800057c1434f2380354fe325"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laminas/laminas-stdlib/zipball/bcd869e2fe88d567800057c1434f2380354fe325",
"reference": "bcd869e2fe88d567800057c1434f2380354fe325",
"shasum": ""
},
"require": {
"php": "^7.3 || ~8.0.0 || ~8.1.0"
},
"conflict": {
"zendframework/zend-stdlib": "*"
},
"require-dev": {
"laminas/laminas-coding-standard": "~2.3.0",
"phpbench/phpbench": "^1.0",
"phpunit/phpunit": "^9.3.7",
"psalm/plugin-phpunit": "^0.16.0",
"vimeo/psalm": "^4.7"
},
"type": "library",
"autoload": {
"psr-4": {
"Laminas\\Stdlib\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"description": "SPL extensions, array utilities, error handlers, and more",
"homepage": "https://laminas.dev",
"keywords": [
"laminas",
"stdlib"
],
"support": {
"chat": "https://laminas.dev/chat",
"docs": "https://docs.laminas.dev/laminas-stdlib/",
"forum": "https://discourse.laminas.dev",
"issues": "https://github.com/laminas/laminas-stdlib/issues",
"rss": "https://github.com/laminas/laminas-stdlib/releases.atom",
"source": "https://github.com/laminas/laminas-stdlib"
},
"funding": [
{
"url": "https://funding.communitybridge.org/projects/laminas-project",
"type": "community_bridge"
}
],
"time": "2022-01-21T15:50:46+00:00"
},
{
"name": "masterminds/html5",
"version": "2.7.5",

View File

@ -16,9 +16,6 @@
"guzzlehttp/guzzle": "7.4.1",
"guzzlehttp/promises": "1.5.1",
"guzzlehttp/psr7": "2.2.1",
"laminas/laminas-escaper": "2.9.0",
"laminas/laminas-feed": "2.16.0",
"laminas/laminas-stdlib": "3.7.1",
"masterminds/html5": "2.7.5",
"pear/archive_tar": "1.4.14",
"pear/console_getopt": "v1.4.3",

View File

@ -13,8 +13,6 @@
"**/LICENSE.txt",
"../**/LICENSE.txt",
"modules/**/Migrate*Test.php",
"modules/aggregator/tests/fixtures/drupal6.php",
"modules/aggregator/tests/fixtures/drupal7.php",
"modules/ckeditor5/js/build/*",
"modules/color/preview.html",
"modules/color/tests/modules/color_test/themes/color_test_theme/color/preview.html",

View File

@ -307,11 +307,10 @@ INSTALLATION
7. Set up independent "cron" maintenance jobs.
Many Drupal modules have tasks that must be run periodically, including the
Search module (building and updating the index used for keyword searching),
the Aggregator module (retrieving feeds from other sites), and the System
module (performing routine maintenance and pruning of database tables). These
tasks are known as "cron maintenance tasks", named after the Unix/Linux
"cron" utility.
Search module (building and updating the index used for keyword searching)
and the System module (performing routine maintenance and pruning of
database tables). These tasks are known as "cron maintenance tasks", named
after the Unix/Linux "cron" utility.
When you install Drupal, its built-in cron feature is enabled, which
automatically runs the cron tasks periodically, triggered by people visiting

View File

@ -58,9 +58,6 @@ maintainer. Current subsystem maintainers:
Actions
- ?
Aggregator
- ?
Ajax
- Alex Bronstein 'effulgentsia' https://www.drupal.org/u/effulgentsia
- Tim Plunkett 'tim.plunkett' https://www.drupal.org/u/tim.plunkett

View File

@ -35,7 +35,6 @@
"doctrine/annotations": "^1.12",
"guzzlehttp/guzzle": "^7.3.0",
"guzzlehttp/psr7": "^2.2.0",
"laminas/laminas-feed": "^2.12",
"egulias/email-validator": "^2.1.22|^3.0",
"masterminds/html5": "^2.1",
"symfony/psr-http-message-bridge": "^2.0",
@ -49,7 +48,6 @@
},
"replace": {
"drupal/action": "self.version",
"drupal/aggregator": "self.version",
"drupal/automated_cron": "self.version",
"drupal/bartik": "self.version",
"drupal/ban": "self.version",

View File

@ -162,9 +162,7 @@
* implements \GuzzleHttp\ClientInterface. See the
* @link container Services topic @endlink for more information on
* services. If you cannot use dependency injection to retrieve this
* service, the \Drupal::httpClient() method is available. A good example
* of how to use this service can be found in
* \Drupal\aggregator\Plugin\aggregator\fetcher\DefaultFetcher
* service, the \Drupal::httpClient() method is available.
* - \Drupal\Component\Serialization\Json (JSON encoding and decoding).
* - PHP has functions and classes for parsing XML; see
* http://php.net/manual/refs.xml.php
@ -1833,14 +1831,13 @@
* where a strict FIFO ordering will likely not be preserved. Another example
* would be an in-memory queue backend which might lose items if it crashes.
* However, such a backend would be able to deal with significantly more writes
* than a reliable queue and for many tasks this is more important. See
* aggregator_cron() for an example of how to effectively use a non-reliable
* queue. Another example is doing Twitter statistics -- the small possibility
* of losing a few items is insignificant next to power of the queue being able
* to keep up with writes. As described in the processing section, regardless
* of the queue being reliable or not, the processing code should be aware that
* an item might be handed over for processing more than once (because the
* processing code might time out before it finishes).
* than a reliable queue and for many tasks this is more important. Another
* example is doing Twitter statistics -- the small possibility of losing a
* few items is insignificant next to power of the queue being able to keep
* up with writes. As described in the processing section, regardless of the
* queue being reliable or not, the processing code should be aware that an
* might be handed over for processing more than once (because the processing
* code might time out before it finishes).
* @}
*/
@ -1929,8 +1926,8 @@ function hook_cron() {
// Long-running operation example, leveraging a queue:
// Queue news feeds for updates once their refresh interval has elapsed.
$queue = \Drupal::queue('aggregator_feeds');
$ids = \Drupal::entityTypeManager()->getStorage('aggregator_feed')->getFeedIdsToRefresh();
$queue = \Drupal::queue('mymodule.feeds');
$ids = \Drupal::entityTypeManager()->getStorage('mymodule_feed')->getFeedIdsToRefresh();
foreach (Feed::loadMultiple($ids) as $feed) {
if ($queue->createItem($feed)) {
// Add timestamp to avoid queueing item more than once.
@ -1938,7 +1935,7 @@ function hook_cron() {
$feed->save();
}
}
$ids = \Drupal::entityQuery('aggregator_feed')
$ids = \Drupal::entityQuery('mymodule_feed')
->accessCheck(FALSE)
->condition('queued', REQUEST_TIME - (3600 * 6), '<')
->execute();
@ -1979,7 +1976,7 @@ function hook_data_type_info_alter(&$data_types) {
function hook_queue_info_alter(&$queues) {
// This site has many feeds so let's spend 90 seconds on each cron run
// updating feeds instead of the default 60.
$queues['aggregator_feeds']['cron']['time'] = 90;
$queues['mymodule_feeds']['cron']['time'] = 90;
}
/**

View File

@ -29,9 +29,6 @@ class Composer {
'guzzlehttp/psr7' => ['tests'],
'instaclick/php-webdriver' => ['doc', 'test'],
'justinrainbow/json-schema' => ['demo'],
'laminas/laminas-escaper' => ['doc'],
'laminas/laminas-feed' => ['doc'],
'laminas/laminas-stdlib' => ['doc'],
'masterminds/html5' => ['bin', 'test'],
'mikey179/vfsStream' => ['src/test'],
'myclabs/deep-copy' => ['doc'],

View File

@ -1,57 +0,0 @@
<?php
/**
* @file
* Aggregator API documentation.
*/
/**
* @addtogroup hooks
* @{
*/
/**
* Perform alterations on the available fetchers.
*
* @param array[] $info
* Array of fetcher plugins
*/
function hook_aggregator_fetcher_info_alter(array &$info) {
if (empty($info['foo_fetcher'])) {
return;
}
$info['foo_fetcher']['class'] = Drupal\foo\Plugin\aggregator\fetcher\FooDefaultFetcher::class;
}
/**
* Perform alterations on the available parsers.
*
* @param array[] $info
* Array of parser plugins
*/
function hook_aggregator_parser_info_alter(array &$info) {
if (empty($info['foo_parser'])) {
return;
}
$info['foo_parser']['class'] = Drupal\foo\Plugin\aggregator\parser\FooDefaultParser::class;
}
/**
* Perform alterations on the available processors.
*
* @param array[] $info
* Array of processor plugins
*/
function hook_aggregator_processor_info_alter(array &$info) {
if (empty($info['foo_processor'])) {
return;
}
$info['foo_processor']['class'] = Drupal\foo\Plugin\aggregator\processor\FooDefaultProcessor::class;
}
/**
* @} End of "addtogroup hooks".
*/

View File

@ -1,9 +0,0 @@
name: Aggregator
type: module
description: 'Gathers and displays syndicated content (RSS, RDF, and Atom feeds) from external sources.'
package: Core
version: VERSION
configure: aggregator.admin_settings
dependencies:
- drupal:file
- drupal:options

View File

@ -1,13 +0,0 @@
<?php
/**
* @file
* Install, update and uninstall functions for the aggregator module.
*/
/**
* Implements hook_update_last_removed().
*/
function aggregator_update_last_removed() {
return 8501;
}

View File

@ -1,11 +0,0 @@
aggregator.feed_add:
route_name: aggregator.feed_add
title: 'Add feed'
appears_on:
- 'aggregator.admin_overview'
aggregator.opml_add:
route_name: aggregator.opml_add
title: 'Import OPML'
appears_on:
- 'aggregator.admin_overview'

View File

@ -1,13 +0,0 @@
aggregator.admin_overview:
title: 'Aggregator'
description: 'Add feeds or import OPMLs to gather external content and configure how often they are updated.'
route_name: aggregator.admin_overview
parent: system.admin_config_services
weight: 10
aggregator.page_last:
title: 'Aggregator'
weight: 5
route_name: aggregator.page_last
aggregator.feed_add:
title: 'Add feed'
route_name: aggregator.feed_add

View File

@ -1,24 +0,0 @@
aggregator.admin_overview:
route_name: aggregator.admin_overview
title: 'List'
base_route: aggregator.admin_overview
aggregator.admin_settings:
route_name: aggregator.admin_settings
title: 'Settings'
weight: 100
base_route: aggregator.admin_overview
entity.aggregator_feed.canonical:
route_name: entity.aggregator_feed.canonical
base_route: entity.aggregator_feed.canonical
title: View
entity.aggregator_feed.edit_form:
route_name: entity.aggregator_feed.edit_form
base_route: entity.aggregator_feed.canonical
title: 'Configure'
weight: 10
entity.aggregator_feed.delete_form:
route_name: entity.aggregator_feed.delete_form
base_route: entity.aggregator_feed.canonical
title: Delete
weight: 20

View File

@ -1,220 +0,0 @@
<?php
/**
* @file
* Used to aggregate syndicated content (RSS, RDF, and Atom).
*/
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\aggregator\Entity\Feed;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implements hook_help().
*/
function aggregator_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.aggregator':
$path_validator = \Drupal::pathValidator();
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Aggregator module is an on-site syndicator and news reader that gathers and displays fresh content from RSS-, RDF-, and Atom-based feeds made available across the web. Thousands of sites (particularly news sites and blogs) publish their latest headlines in feeds, using a number of standardized XML-based formats. For more information, see the <a href=":aggregator-module">online documentation for the Aggregator module</a>.', [':aggregator-module' => 'https://www.drupal.org/documentation/modules/aggregator']) . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
// Check if the aggregator sources View is enabled.
if ($url = $path_validator->getUrlIfValid('aggregator/sources')) {
$output .= '<dt>' . t('Viewing feeds') . '</dt>';
$output .= '<dd>' . t('Users view feed content in the <a href=":aggregator">main aggregator display</a>, or by <a href=":aggregator-sources">their source</a> (usually via an RSS feed reader). The most recent content in a feed can be displayed as a block through the <a href=":admin-block">Blocks administration page</a>.', [':aggregator' => Url::fromRoute('aggregator.page_last')->toString(), ':aggregator-sources' => $url->toString(), ':admin-block' => (\Drupal::moduleHandler()->moduleExists('block')) ? Url::fromRoute('block.admin_display')->toString() : '#']) . '</dd>';
}
$output .= '<dt>' . t('Adding, editing, and deleting feeds') . '</dt>';
$output .= '<dd>' . t('Administrators can add, edit, and delete feeds, and choose how often to check each feed for newly updated items on the <a href=":feededit">Aggregator administration page</a>.', [':feededit' => Url::fromRoute('aggregator.admin_overview')->toString()]) . '</dd>';
$output .= '<dt>' . t('Configuring the display of feed items') . '</dt>';
$output .= '<dd>' . t('Administrators can choose how many items are displayed in the listing pages, which HTML tags are allowed in the content of feed items, and whether they should be trimmed to a maximum number of characters on the <a href=":settings">Aggregator settings page</a>.', [':settings' => Url::fromRoute('aggregator.admin_settings')->toString()]) . '</dd>';
$output .= '<dt>' . t('Discarding old feed items') . '</dt>';
$output .= '<dd>' . t('Administrators can choose whether to discard feed items that are older than a specified period of time on the <a href=":settings">Aggregator settings page</a>. This requires a correctly configured cron maintenance task (see below).', [':settings' => Url::fromRoute('aggregator.admin_settings')->toString()]) . '<dd>';
$output .= '<dt>' . t('<abbr title="Outline Processor Markup Language">OPML</abbr> integration') . '</dt>';
// Check if the aggregator opml View is enabled.
if ($url = $path_validator->getUrlIfValid('aggregator/opml')) {
$output .= '<dd>' . t('A <a href=":aggregator-opml">machine-readable OPML file</a> of all feeds is available. OPML is an XML-based file format used to share outline-structured information such as a list of RSS feeds. Feeds can also be <a href=":import-opml">imported via an OPML file</a>.', [':aggregator-opml' => $url->toString(), ':import-opml' => Url::fromRoute('aggregator.opml_add')->toString()]) . '</dd>';
}
$output .= '<dt>' . t('Configuring cron') . '</dt>';
$output .= '<dd>' . t('A working <a href=":cron">cron maintenance task</a> is required to update feeds automatically.', [':cron' => Url::fromRoute('system.cron_settings')->toString()]) . '</dd>';
$output .= '</dl>';
return $output;
case 'aggregator.admin_overview':
// Don't use placeholders for possibility to change URLs for translators.
$output = '<p>' . t('Many sites publish their headlines and posts in feeds, using a number of standardized XML-based formats. The aggregator supports <a href="http://en.wikipedia.org/wiki/Rss">RSS</a>, <a href="http://en.wikipedia.org/wiki/Resource_Description_Framework">RDF</a>, and <a href="http://en.wikipedia.org/wiki/Atom_%28standard%29">Atom</a>.') . '</p>';
// cspell:ignore addfeed
$output .= '<p>' . t('Current feeds are listed below, and <a href=":addfeed">new feeds may be added</a>. For each feed, the <em>@block_name</em> block may be enabled at the <a href=":block">block layout page</a>.', [':addfeed' => Url::fromRoute('aggregator.feed_add')->toString(), '@block_name' => t('Aggregator feed'), ':block' => (\Drupal::moduleHandler()->moduleExists('block')) ? Url::fromRoute('block.admin_display')->toString() : '#']) . '</p>';
return $output;
case 'aggregator.feed_add':
return '<p>' . t('Add a feed in RSS, RDF or Atom format. A feed may only have one entry.') . '</p>';
case 'aggregator.opml_add':
return '<p>' . t('<abbr title="Outline Processor Markup Language">OPML</abbr> is an XML format for exchanging feeds between aggregators. A single OPML document may contain many feeds. Aggregator uses this file to import all feeds at once. Upload a file from your computer or enter a URL where the OPML file can be downloaded.') . '</p>';
}
}
/**
* Implements hook_theme().
*/
function aggregator_theme() {
return [
'aggregator_feed' => [
'render element' => 'elements',
'file' => 'aggregator.theme.inc',
],
'aggregator_item' => [
'render element' => 'elements',
'file' => 'aggregator.theme.inc',
],
];
}
/**
* Implements hook_entity_extra_field_info().
*
* By default this function creates pseudo-fields that mask the description and
* image base fields. These pseudo-fields are omitted if:
* - a module makes the field's display configurable via the field UI by means
* of BaseFieldDefinition::setDisplayConfigurable()
* - AND the additional entity type property
* 'enable_base_field_custom_preprocess_skipping' has been set using
* hook_entity_type_build().
*/
function aggregator_entity_extra_field_info() {
$extra = [];
$entity_type_manager = \Drupal::entityTypeManager();
$entity_field_manager = \Drupal::service('entity_field.manager');
$extra['aggregator_feed']['aggregator_feed'] = [
'display' => [
'items' => [
'label' => t('Items'),
'description' => t('Items associated with this feed'),
'weight' => 0,
],
'more_link' => [
'label' => t('More link'),
'description' => t('A more link to the feed detail page'),
'weight' => 5,
],
'feed_icon' => [
'label' => t('Feed icon'),
'description' => t('An icon that links to the feed URL'),
'weight' => 6,
],
],
];
// Create Feed image and description pseudo-fields. Skip this if the field
// display is configurable and skipping has been enabled.
// @todo https://www.drupal.org/project/drupal/issues/3015623
// Eventually delete this code and matching lines in FeedViewBuilder. Using
// field formatters is more flexible and consistent.
$skip_custom_preprocessing = $entity_type_manager->getDefinition('aggregator_feed')->get('enable_base_field_custom_preprocess_skipping');
$base_field_definitions = $entity_field_manager->getBaseFieldDefinitions('aggregator_feed');
if (!$skip_custom_preprocessing || !$base_field_definitions['image']->isDisplayConfigurable('view')) {
$extra['aggregator_feed']['aggregator_feed']['display']['image'] = [
'label' => t('Image'),
'description' => t('The feed image'),
'weight' => 2,
];
}
if (!$skip_custom_preprocessing || !$base_field_definitions['description']->isDisplayConfigurable('view')) {
$extra['aggregator_feed']['aggregator_feed']['display']['description'] = [
'label' => t('Description'),
'description' => t('The description of this feed'),
'weight' => 3,
];
}
// Create Item description pseudo-field. Skip this if the field display is
// configurable and skipping has been enabled.
// @todo https://www.drupal.org/project/drupal/issues/3015623
// Eventually delete this code and matching lines in ItemViewBuilder. Using
// field formatters is more flexible and consistent.
$skip_custom_preprocessing = $entity_type_manager->getDefinition('aggregator_item')->get('enable_base_field_custom_preprocess_skipping');
$base_field_definitions = $entity_field_manager->getBaseFieldDefinitions('aggregator_item');
if (!$skip_custom_preprocessing || !$base_field_definitions['description']->isDisplayConfigurable('view')) {
$extra['aggregator_item']['aggregator_item']['display']['description'] = [
'label' => t('Description'),
'description' => t('The description of this feed item'),
'weight' => 2,
];
}
return $extra;
}
/**
* Implements hook_cron().
*
* Queues news feeds for updates once their refresh interval has elapsed.
*/
function aggregator_cron() {
$queue = \Drupal::queue('aggregator_feeds');
$ids = \Drupal::entityTypeManager()->getStorage('aggregator_feed')->getFeedIdsToRefresh();
foreach (Feed::loadMultiple($ids) as $feed) {
if ($queue->createItem($feed)) {
// Add timestamp to avoid queueing item more than once.
$feed->setQueuedTime(REQUEST_TIME);
$feed->save();
}
}
// Delete queued timestamp after 6 hours assuming the update has failed.
$ids = \Drupal::entityQuery('aggregator_feed')
->accessCheck(FALSE)
->condition('queued', REQUEST_TIME - (3600 * 6), '<')
->execute();
if ($ids) {
$feeds = Feed::loadMultiple($ids);
foreach ($feeds as $feed) {
$feed->setQueuedTime(0);
$feed->save();
}
}
}
/**
* Gets the list of allowed tags.
*
* @return array
* The list of allowed tags.
*
* @internal
*/
function _aggregator_allowed_tags() {
return preg_split('/\s+|<|>/', \Drupal::config('aggregator.settings')->get('items.allowed_html'), -1, PREG_SPLIT_NO_EMPTY);
}
/**
* Implements hook_preprocess_HOOK() for block templates.
*/
function aggregator_preprocess_block(&$variables) {
if ($variables['configuration']['provider'] == 'aggregator') {
$variables['attributes']['role'] = 'complementary';
}
}
/**
* Implements hook_jsonapi_ENTITY_TYPE_filter_access() for 'aggregator_feed'.
*/
function aggregator_jsonapi_aggregator_feed_filter_access(EntityTypeInterface $entity_type, AccountInterface $account) {
// @see \Drupal\aggregator\FeedAccessControlHandler::checkAccess()
return ([
JSONAPI_FILTER_AMONG_ALL => AccessResult::allowedIfHasPermission($account, 'access news feeds'),
]);
}

View File

@ -1,4 +0,0 @@
administer news feeds:
title: 'Administer news feeds'
access news feeds:
title: 'View news feeds'

View File

@ -1,58 +0,0 @@
aggregator.admin_overview:
path: '/admin/config/services/aggregator'
defaults:
_controller: '\Drupal\aggregator\Controller\AggregatorController::adminOverview'
_title: 'Aggregator'
requirements:
_permission: 'administer news feeds'
aggregator.admin_settings:
path: '/admin/config/services/aggregator/settings'
defaults:
_form: '\Drupal\aggregator\Form\SettingsForm'
_title: 'Aggregator settings'
requirements:
_permission: 'administer news feeds'
aggregator.feed_items_delete:
path: '/admin/config/services/aggregator/delete/{aggregator_feed}'
defaults:
_entity_form: 'aggregator_feed.delete_items'
_title: 'Delete items'
requirements:
_permission: 'administer news feeds'
aggregator.feed_refresh:
path: '/admin/config/services/aggregator/update/{aggregator_feed}'
defaults:
_controller: '\Drupal\aggregator\Controller\AggregatorController::feedRefresh'
_title: 'Update items'
requirements:
_permission: 'administer news feeds'
_csrf_token: 'TRUE'
aggregator.opml_add:
path: '/admin/config/services/aggregator/add/opml'
defaults:
_form: '\Drupal\aggregator\Form\OpmlFeedAdd'
_title: 'Import OPML'
requirements:
_permission: 'administer news feeds'
aggregator.feed_add:
path: '/aggregator/sources/add'
defaults:
_controller: '\Drupal\aggregator\Controller\AggregatorController::feedAdd'
_title: 'Add feed'
requirements:
_permission: 'administer news feeds'
options:
_admin_route: TRUE
aggregator.page_last:
path: '/aggregator'
defaults:
_controller: '\Drupal\aggregator\Controller\AggregatorController::pageLast'
_title: 'Aggregator'
requirements:
_permission: 'access news feeds'

View File

@ -1,22 +0,0 @@
services:
plugin.manager.aggregator.fetcher:
class: Drupal\aggregator\Plugin\AggregatorPluginManager
arguments: [fetcher, '@container.namespaces', '@cache.discovery', '@module_handler']
plugin.manager.aggregator.parser:
class: Drupal\aggregator\Plugin\AggregatorPluginManager
arguments: [parser, '@container.namespaces', '@cache.discovery', '@module_handler']
plugin.manager.aggregator.processor:
class: Drupal\aggregator\Plugin\AggregatorPluginManager
arguments: [processor, '@container.namespaces', '@cache.discovery', '@module_handler']
aggregator.items.importer:
class: Drupal\aggregator\ItemsImporter
arguments: ['@config.factory', '@plugin.manager.aggregator.fetcher', '@plugin.manager.aggregator.parser', '@plugin.manager.aggregator.processor', '@logger.channel.aggregator']
logger.channel.aggregator:
parent: logger.channel_base
arguments: ['aggregator']
feed.bridge.reader:
class: Drupal\aggregator\ZfExtensionManagerSfContainer
calls:
- [setContainer, ['@service_container']]
- [setStandalone, ['\Laminas\Feed\Reader\StandaloneExtensionManager']]
arguments: ['feed.reader.']

View File

@ -1,84 +0,0 @@
<?php
/**
* @file
* Preprocessors and theme functions of Aggregator module.
*/
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Render\Element;
/**
* Prepares variables for aggregator item templates.
*
* Default template: aggregator-item.html.twig.
*
* By default this function performs special preprocessing to create a separate
* variable for the title base field. This preprocessing is skipped if:
* - a module makes the field's display configurable via the field UI by means
* of BaseFieldDefinition::setDisplayConfigurable()
* - AND the additional entity type property
* 'enable_base_field_custom_preprocess_skipping' has been set using
* hook_entity_type_build().
*
* @param array $variables
* An associative array containing:
* - elements: An array of elements to display in view mode.
*/
function template_preprocess_aggregator_item(&$variables) {
$item = $variables['elements']['#aggregator_item'];
// Helpful $content variable for templates.
foreach (Element::children($variables['elements']) as $key) {
$variables['content'][$key] = $variables['elements'][$key];
}
$variables['url'] = UrlHelper::stripDangerousProtocols($item->getLink());
// Make title field available separately. Skip this custom preprocessing if
// the field display is configurable and skipping has been enabled.
// @todo https://www.drupal.org/project/drupal/issues/3015623
// Eventually delete this code and matching template lines. Using
// $variables['content'] is more flexible and consistent.
$skip_custom_preprocessing = $item->getEntityType()->get('enable_base_field_custom_preprocess_skipping');
if (!$skip_custom_preprocessing || !$item->getFieldDefinition('title')->isDisplayConfigurable('view')) {
$variables['title'] = $item->label();
}
}
/**
* Prepares variables for aggregator feed templates.
*
* Default template: aggregator-feed.html.twig.
*
* By default this function performs special preprocessing to create a separate
* variable for the title base field. This preprocessing is skipped if:
* - a module makes the field's display configurable via the field UI by means
* of BaseFieldDefinition::setDisplayConfigurable()
* - AND the additional entity type property
* 'enable_base_field_custom_preprocess_skipping' has been set using
* hook_entity_type_build().
*
* @param array $variables
* An associative array containing:
* - elements: An array of elements to display in view mode.
*/
function template_preprocess_aggregator_feed(&$variables) {
$feed = $variables['elements']['#aggregator_feed'];
// Helpful $content variable for templates.
foreach (Element::children($variables['elements']) as $key) {
$variables['content'][$key] = $variables['elements'][$key];
}
$variables['full'] = $variables['elements']['#view_mode'] == 'full';
// Make title field available separately. Skip this custom preprocessing if
// the field display is configurable and skipping has been enabled.
// @todo https://www.drupal.org/project/drupal/issues/3015623
// Eventually delete this code and matching template lines. Using
// $variables['content'] is more flexible and consistent.
$skip_custom_preprocessing = $feed->getEntityType()->get('enable_base_field_custom_preprocess_skipping');
if (!$skip_custom_preprocessing || !$feed->getFieldDefinition('title')->isDisplayConfigurable('view')) {
$variables['title'] = $feed->label();
}
}

View File

@ -1,10 +0,0 @@
fetcher: aggregator
parser: aggregator
processors:
- aggregator
items:
allowed_html: '<a> <b> <br> <dd> <dl> <dt> <em> <i> <li> <ol> <p> <strong> <u> <ul>'
teaser_length: 600
expire: 9676800
source:
list_max: 3

View File

@ -1,38 +0,0 @@
langcode: en
status: true
dependencies:
module:
- aggregator
id: aggregator_feed.aggregator_feed.default
targetEntityType: aggregator_feed
bundle: aggregator_feed
mode: default
content:
checked:
type: timestamp_ago
label: inline
settings: { }
third_party_settings: { }
weight: 1
region: content
description:
weight: 3
region: content
feed_icon:
weight: 5
region: content
image:
weight: 2
region: content
items:
weight: 0
region: content
link:
type: uri_link
label: inline
settings: { }
third_party_settings: { }
weight: 4
region: content
hidden:
more_link: true

View File

@ -1,24 +0,0 @@
langcode: en
status: true
dependencies:
config:
- core.entity_view_mode.aggregator_feed.summary
module:
- aggregator
id: aggregator_feed.aggregator_feed.summary
targetEntityType: aggregator_feed
bundle: aggregator_feed
mode: summary
content:
items:
weight: 0
region: content
more_link:
weight: 1
region: content
hidden:
checked: true
description: true
feed_icon: true
image: true
link: true

View File

@ -1,20 +0,0 @@
langcode: en
status: true
dependencies:
config:
- core.entity_view_mode.aggregator_item.summary
module:
- aggregator
id: aggregator_item.aggregator_item.summary
targetEntityType: aggregator_item
bundle: aggregator_item
mode: summary
content:
timestamp:
weight: 0
region: content
hidden:
author: true
description: true
feed: true
link: true

View File

@ -1,9 +0,0 @@
langcode: en
status: true
dependencies:
module:
- aggregator
id: aggregator_feed.summary
label: Summary
targetEntityType: aggregator_feed
cache: true

View File

@ -1,9 +0,0 @@
langcode: en
status: true
dependencies:
module:
- aggregator
id: aggregator_item.summary
label: Summary
targetEntityType: aggregator_item
cache: true

View File

@ -1,160 +0,0 @@
langcode: en
status: true
dependencies:
module:
- aggregator
- user
id: aggregator_rss_feed
label: 'Aggregator RSS feed'
module: aggregator
description: ''
tag: aggregator
base_table: aggregator_item
base_field: iid
display:
default:
id: default
display_title: Default
display_plugin: default
position: 0
display_options:
title: 'Aggregator RSS feed'
fields:
iid:
id: iid
table: aggregator_item
field: iid
relationship: none
group_type: group
admin_label: ''
entity_type: aggregator_item
entity_field: iid
plugin_id: field
label: 'Item ID'
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: true
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
type: number_integer
pager:
type: full
options:
offset: 0
items_per_page: 10
total_pages: 0
id: 0
tags:
next: 'Next '
previous: ' Previous'
first: '« First'
last: 'Last »'
expose:
items_per_page: false
items_per_page_label: 'Items per page'
items_per_page_options: '5, 10, 25, 50'
items_per_page_options_all: false
items_per_page_options_all_label: '- All -'
offset: false
offset_label: Offset
quantity: 9
exposed_form:
type: basic
options:
submit_button: Apply
reset_button: false
reset_button_label: Reset
exposed_sorts_label: 'Sort by'
expose_sort_order: true
sort_asc_label: Asc
sort_desc_label: Desc
access:
type: perm
options:
perm: 'access news feeds'
cache:
type: tag
options: { }
empty: { }
sorts: { }
arguments: { }
filters: { }
style:
type: default
row:
type: 'entity:aggregator_item'
query:
type: views_query
options:
query_comment: ''
disable_sql_rewrite: false
distinct: false
replica: false
query_tags: { }
relationships: { }
header: { }
footer: { }
display_extenders: { }
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url.query_args
- user.permissions
tags: { }
cacheable: false
feed_items:
id: feed_items
display_title: Feed
display_plugin: feed
position: 1
display_options:
defaults:
arguments: true
display_description: ''
display_extenders: { }
path: aggregator/rss
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- user.permissions
tags: { }
cacheable: false

View File

@ -1,428 +0,0 @@
langcode: en
status: true
dependencies:
config:
- core.entity_view_mode.aggregator_feed.summary
- system.menu.tools
module:
- aggregator
- user
id: aggregator_sources
label: 'Aggregator sources'
module: aggregator
description: ''
tag: aggregator
base_table: aggregator_feed
base_field: fid
display:
default:
id: default
display_title: Default
display_plugin: default
position: 0
display_options:
title: Sources
fields:
fid:
id: fid
table: aggregator_feed
field: fid
relationship: none
group_type: group
admin_label: ''
entity_type: aggregator_feed
entity_field: fid
plugin_id: field
label: ''
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: true
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
type: number_integer
pager:
type: full
options:
offset: 0
items_per_page: 10
total_pages: null
id: 0
tags:
next: 'Next '
previous: ' Previous'
first: '« First'
last: 'Last »'
expose:
items_per_page: false
items_per_page_label: 'Items per page'
items_per_page_options: '5, 10, 25, 50'
items_per_page_options_all: false
items_per_page_options_all_label: '- All -'
offset: false
offset_label: Offset
quantity: 9
exposed_form:
type: basic
options:
submit_button: Apply
reset_button: false
reset_button_label: Reset
exposed_sorts_label: 'Sort by'
expose_sort_order: true
sort_asc_label: Asc
sort_desc_label: Desc
access:
type: perm
options:
perm: 'access news feeds'
cache:
type: tag
options: { }
empty: { }
sorts: { }
arguments: { }
filters: { }
style:
type: default
row:
type: 'entity:aggregator_feed'
options:
relationship: none
view_mode: summary
query:
type: views_query
options:
query_comment: ''
disable_sql_rewrite: false
distinct: false
replica: false
query_tags: { }
relationships: { }
header: { }
footer: { }
display_extenders: { }
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url.query_args
- user.permissions
tags: { }
feed_1:
id: feed_1
display_title: Feed
display_plugin: feed
position: 2
display_options:
title: 'OPML feed'
fields:
title:
id: title
table: aggregator_feed
field: title
relationship: none
group_type: group
admin_label: ''
entity_type: aggregator_feed
entity_field: title
plugin_id: field
label: ''
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: false
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
click_sort_column: value
type: aggregator_title
settings:
display_as_link: false
group_column: value
group_columns: { }
group_rows: true
delta_limit: 0
delta_offset: 0
delta_reversed: false
delta_first_last: false
multi_type: separator
separator: ', '
field_api_classes: false
url:
id: url
table: aggregator_feed
field: url
relationship: none
group_type: group
admin_label: ''
entity_type: aggregator_feed
entity_field: url
plugin_id: url
label: ''
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: false
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
display_as_link: false
description:
id: description
table: aggregator_feed
field: description
relationship: none
group_type: group
admin_label: ''
entity_type: aggregator_feed
entity_field: description
plugin_id: xss
label: ''
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: false
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
link:
id: link
table: aggregator_feed
field: link
relationship: none
group_type: group
admin_label: ''
entity_type: aggregator_feed
entity_field: link
plugin_id: url
label: ''
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: false
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
display_as_link: false
style:
type: opml
options:
grouping: { }
row:
type: opml_fields
options:
type_field: rss
text_field: title
created_field: ''
description_field: description
html_url_field: link
language_field: ''
xml_url_field: url
url_field: ''
defaults:
title: false
fields: false
display_extenders: { }
path: aggregator/opml
sitename_title: true
displays:
page_1: page_1
default: '0'
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- user.permissions
tags: { }
page_1:
id: page_1
display_title: Page
display_plugin: page
position: 1
display_options:
display_extenders: { }
path: aggregator/sources
menu:
type: normal
title: Sources
description: ''
weight: 0
menu_name: tools
context: '0'
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url.query_args
- user.permissions
tags: { }

View File

@ -1,57 +0,0 @@
# Schema for the configuration files of the aggregator module.
aggregator.settings:
type: config_object
label: 'Aggregator settings'
mapping:
fetcher:
type: string
label: 'Fetcher'
parser:
type: string
label: 'Parser'
processors:
type: sequence
label: 'Processors'
sequence:
type: string
label: 'Processor'
items:
type: mapping
label: 'Items'
mapping:
allowed_html:
type: string
label: 'Allowed HTML tags'
teaser_length:
type: integer
label: 'Length of trimmed description'
expire:
type: integer
label: 'Discard items older than'
source:
type: mapping
label: 'Source'
mapping:
list_max:
type: integer
label: 'Number of items shown in listing pages'
block.settings.aggregator_feed_block:
type: block_settings
label: 'Aggregator feed block'
mapping:
block_count:
type: integer
label: 'Block count'
feed:
type: string
label: 'Feed'
field.formatter.settings.aggregator_title:
type: mapping
label: 'Formatter settings'
mapping:
display_as_link:
type: boolean
label: 'Display as link'

View File

@ -1,24 +0,0 @@
# Schema for the views plugins of the Aggregator module.
views.argument.aggregator_fid:
type: views.argument.numeric
label: 'Aggregator feed ID'
views.argument.aggregator_iid:
type: views.argument.numeric
label: 'Aggregator item ID'
views.field.aggregator_title_link:
type: views_field
label: 'Title link'
mapping:
display_as_link:
type: boolean
views.row.aggregator_rss:
type: views_row
label: 'Aggregator item row'
mapping:
view_mode:
type: string
label: 'Display type'

View File

@ -1,18 +0,0 @@
---
label: 'Creating a feed'
related:
- aggregator.overview
- aggregator.managing
---
{% set aggregator_overview_url = render_var(url('aggregator.admin_overview')) %}
<h2>{% trans %}Goal{% endtrans %}</h2>
<p>{% trans %}Create a new feed to display syndicated data from an outside source on your website, or import an OPML file to create multiple feeds.{% endtrans %}</p>
<h2>{% trans %}Steps{% endtrans %}</h2>
<ol>
<li>{% trans %}In the <em>Manage</em> administrative menu, navigate to <em>Configuration</em> &gt; <em>Web services</em> &gt; <a href="{{ aggregator_overview_url }}"><em>Aggregator</em></a>.{% endtrans %}</li>
<li>{% trans %}Click <em>Add feed</em> if you have an individual feed URL to add, or <em>Import OPML</em> if you have an OPML-formatted list of feeds to add.{% endtrans %}</li>
<li>{% trans %}If you clicked <em>Add feed</em>, enter a <em>Title</em> for the feed and the <em>URL</em> of the feed. Select an <em>Update interval</em> and click <em>Save</em>.{% endtrans %}</li>
<li>{% trans %}If you clicked <em>Import OPML</em>, either choose an <em>OPML file</em> from your local computer or enter an <em>OPML Remote URL</em> to import an OPML list from a URL. Select an <em>Update interval</em> and click <em>Import</em>.{% endtrans %}</li>
<li>{% trans %}In the <em>Manage</em> administrative menu, navigate back to <em>Configuration</em> &gt; <em>Web services</em> &gt; <a href="{{ aggregator_overview_url }}"><em>Aggregator</em></a>. You should see the new feed or feeds that you added in the list under <em>Feed overview</em>.{% endtrans %}</li>
<li>{% trans %}To verify that your feed is working, click <em>Update items</em> in the <em>Operations</em> list for your feed, and then click the feed name to view the imported items on the standard provided feed page.{% endtrans %}</li>
</ol>

View File

@ -1,17 +0,0 @@
---
label: 'Managing and configuring an existing feed'
related:
- aggregator.overview
- aggregator.creating
---
{% set aggregator_overview_url = render_var(url('aggregator.admin_overview')) %}
<h2>{% trans %}Goal{% endtrans %}</h2>
<p>{% trans %}Manage an existing feed or change its configuration.{% endtrans %}</p>
<h2>{% trans %}Steps{% endtrans %}</h2>
<ol>
<li>{% trans %}In the <em>Manage</em> administrative menu, navigate to <em>Configuration</em> &gt; <em>Web services</em>&gt; <a href="{{ aggregator_overview_url }}"><em>Aggregator</em></a>.{% endtrans %}</li>
<li>{% trans %}Click <em>Edit</em> in the <em>Operations</em> list for the feed you want to configure. Enter new values and click <em>Save</em>.{% endtrans %}</li>
<li>{% trans %}Optionally, delete the previously-imported items from the feed by clicking <em>Delete items</em> in the <em>Operations</em> list for the feed.{% endtrans %}</li>
<li>{% trans %}Optionally, import new items from the feed by clicking <em>Update items</em> in the <em>Operations</em> list for the feed. You can also run the site Cron process to import items into all feeds, depending on the configured <em>Update interval</em> for each feed.{% endtrans %}</li>
<li>{% trans %}Optionally, click <em>Settings</em> to configure the settings for all feeds, including the <em>Number of items shown in listing pages</em> and how long to keep old items from feeds on your site. Click <em>Save configuration</em>.{% endtrans %}</li>
</ol>

View File

@ -1,23 +0,0 @@
---
label: 'Importing syndicated content'
top_level: true
related:
- block.place
---
{% set creating_topic = render_var(help_topic_link('aggregator.creating')) %}
{% set managing_topic = render_var(help_topic_link('aggregator.managing')) %}
<h2>{% trans %}What is a feed?{% endtrans %}</h2>
<p>{% trans %}A feed is syndicated content data provided by a source outside of your website, which is imported into your website.{% endtrans %}</p>
<h2>{% trans %}What is OPML?{% endtrans %}</h2>
<p>{% trans %}OPML (Outline Processor Markup Language) is a specification for making hierarchical lists, which is commonly used for lists of feeds.{% endtrans %}</p>
<h2>{% trans %}What are the options for updating feed items?{% endtrans %}</h2>
<p>{% trans %}Feeds are <em>updated</em> (new items imported) each time your site's cron task runs, if the selected <em>Update interval</em> for the feed has passed. You can also update feeds manually; see {{ managing_topic }} for details.{% endtrans %}</p>
<h2>{% trans %}What are the options for displaying feeds?{% endtrans %}</h2>
<p>{% trans %}Using the core Aggregator, Views, Views UI, and Block modules, you can display feed data in your site in various ways (see related topics for more information):{% endtrans %}</p>
<ul>
<li>{% trans %}After creating and updating a feed, view the feed page provided by the core Aggregator module, which displays recent imported items; see {{ creating_topic }} for details.{% endtrans %}</li>
<li>{% trans %}Place the <em>Aggregator feed</em> block in a region of your theme; each block you place lists the most recent items from one feed.{% endtrans %}</li>
<li>{% trans %}Create a custom view that shows either <em>Aggregator feed</em> (feeds) or <em>Aggregator feed item</em> (items from feeds).{% endtrans %}</li>
</ul>
<h2>{% trans %}Overview of aggregation{% endtrans %}</h2>
<p>{% trans %}The core Aggregator module allows you to add, edit, and delete feeds, choose how often to import items from feeds, and display the feeds. See the related topics below for specific tasks.{% endtrans %}</p>

View File

@ -1,21 +0,0 @@
id: d6_aggregator_feed
label: Aggregator feeds
audit: true
migration_tags:
- Drupal 6
- Content
source:
plugin: aggregator_feed
process:
fid: fid
title: title
url: url
refresh: refresh
checked: checked
link: link
description: description
image: image
etag: etag
modified: modified
destination:
plugin: entity:aggregator_feed

View File

@ -1,25 +0,0 @@
id: d6_aggregator_item
label: Aggregator items
audit: true
migration_tags:
- Drupal 6
- Content
source:
plugin: aggregator_item
process:
iid: iid
fid:
plugin: migration_lookup
migration: d6_aggregator_feed
source: fid
title: title
link: link
author: author
description: description
timestamp: timestamp
guid: guid
destination:
plugin: entity:aggregator_item
migration_dependencies:
required:
- d6_aggregator_feed

View File

@ -1,27 +0,0 @@
id: d6_aggregator_settings
label: Aggregator configuration
migration_tags:
- Drupal 6
- Configuration
source:
plugin: variable
variables:
- aggregator_fetcher
- aggregator_parser
- aggregator_processors
- aggregator_allowed_html_tags
- aggregator_teaser_length
- aggregator_clear
- aggregator_summary_items
source_module: aggregator
process:
fetcher: aggregator_fetcher
parser: aggregator_parser
processors: aggregator_processors
'items/allowed_html': aggregator_allowed_html_tags
'items/teaser_length': aggregator_teaser_length
'items/expire': aggregator_clear
'source/list_max': aggregator_summary_items
destination:
plugin: config
config_name: aggregator.settings

View File

@ -1,22 +0,0 @@
id: d7_aggregator_feed
label: Aggregator feeds
audit: true
migration_tags:
- Drupal 7
- Content
source:
plugin: aggregator_feed
process:
fid: fid
title: title
url: url
refresh: refresh
checked: checked
queued: queued
link: link
description: description
image: image
etag: etag
modified: modified
destination:
plugin: entity:aggregator_feed

View File

@ -1,25 +0,0 @@
id: d7_aggregator_item
label: Aggregator items
audit: true
migration_tags:
- Drupal 7
- Content
source:
plugin: aggregator_item
process:
iid: iid
fid:
plugin: migration_lookup
migration: d7_aggregator_feed
source: fid
title: title
link: link
author: author
description: description
timestamp: timestamp
guid: guid
destination:
plugin: entity:aggregator_item
migration_dependencies:
required:
- d7_aggregator_feed

View File

@ -1,27 +0,0 @@
id: d7_aggregator_settings
label: Aggregator configuration
migration_tags:
- Drupal 7
- Configuration
source:
plugin: variable
variables:
- aggregator_fetcher
- aggregator_parser
- aggregator_processors
- aggregator_allowed_html_tags
- aggregator_teaser_length
- aggregator_clear
- aggregator_summary_items
source_module: aggregator
process:
fetcher: aggregator_fetcher
parser: aggregator_parser
processors: aggregator_processors
'items/allowed_html': aggregator_allowed_html_tags
'items/teaser_length': aggregator_teaser_length
'items/expire': aggregator_clear
'source/list_max': aggregator_summary_items
destination:
plugin: config
config_name: aggregator.settings

View File

@ -1,5 +0,0 @@
finished:
6:
aggregator: aggregator
7:
aggregator: aggregator

View File

@ -1,51 +0,0 @@
<?php
namespace Drupal\aggregator;
use Drupal\views\EntityViewsData;
/**
* Provides the views data for the aggregator feed entity type.
*/
class AggregatorFeedViewsData extends EntityViewsData {
/**
* {@inheritdoc}
*/
public function getViewsData() {
$data = parent::getViewsData();
$data['aggregator_feed']['table']['join'] = [
'aggregator_item' => [
'left_field' => 'fid',
'field' => 'fid',
],
];
$data['aggregator_feed']['fid']['help'] = $this->t('The unique ID of the aggregator feed.');
$data['aggregator_feed']['fid']['argument']['id'] = 'aggregator_fid';
$data['aggregator_feed']['fid']['argument']['name field'] = 'title';
$data['aggregator_feed']['fid']['argument']['numeric'] = TRUE;
$data['aggregator_feed']['fid']['filter']['id'] = 'numeric';
$data['aggregator_feed']['title']['help'] = $this->t('The title of the aggregator feed.');
$data['aggregator_feed']['title']['field']['default_formatter'] = 'aggregator_title';
$data['aggregator_feed']['argument']['id'] = 'string';
$data['aggregator_feed']['url']['help'] = $this->t('The fully-qualified URL of the feed.');
$data['aggregator_feed']['link']['help'] = $this->t('The link to the source URL of the feed.');
$data['aggregator_feed']['checked']['help'] = $this->t('The date the feed was last checked for new content.');
$data['aggregator_feed']['description']['help'] = $this->t('The description of the aggregator feed.');
$data['aggregator_feed']['description']['field']['click sortable'] = FALSE;
$data['aggregator_feed']['modified']['help'] = $this->t('The date of the most recent new content on the feed.');
return $data;
}
}

View File

@ -1,45 +0,0 @@
<?php
namespace Drupal\aggregator;
use Drupal\views\EntityViewsData;
/**
* Provides the views data for the aggregator item entity type.
*/
class AggregatorItemViewsData extends EntityViewsData {
/**
* {@inheritdoc}
*/
public function getViewsData() {
$data = parent::getViewsData();
$data['aggregator_item']['table']['base']['help'] = $this->t('Aggregator items are imported from external RSS and Atom news feeds.');
$data['aggregator_item']['iid']['help'] = $this->t('The unique ID of the aggregator item.');
$data['aggregator_item']['iid']['argument']['id'] = 'aggregator_iid';
$data['aggregator_item']['iid']['argument']['name field'] = 'title';
$data['aggregator_item']['iid']['argument']['numeric'] = TRUE;
$data['aggregator_item']['title']['help'] = $this->t('The title of the aggregator item.');
$data['aggregator_item']['title']['field']['default_formatter'] = 'aggregator_title';
$data['aggregator_item']['link']['help'] = $this->t('The link to the original source URL of the item.');
$data['aggregator_item']['author']['help'] = $this->t('The author of the original imported item.');
$data['aggregator_item']['author']['field']['default_formatter'] = 'aggregator_xss';
$data['aggregator_item']['guid']['help'] = $this->t('The guid of the original imported item.');
$data['aggregator_item']['description']['help'] = $this->t('The actual content of the imported item.');
$data['aggregator_item']['description']['field']['default_formatter'] = 'aggregator_xss';
$data['aggregator_item']['description']['field']['click sortable'] = FALSE;
$data['aggregator_item']['timestamp']['help'] = $this->t('The date the original feed item was posted. (With some feeds, this will be the date it was imported.)');
return $data;
}
}

View File

@ -1,48 +0,0 @@
<?php
namespace Drupal\aggregator\Annotation;
use Drupal\Component\Annotation\Plugin;
/**
* Defines a Plugin annotation object for aggregator fetcher plugins.
*
* Plugin Namespace: Plugin\aggregator\fetcher
*
* For a working example, see \Drupal\aggregator\Plugin\aggregator\fetcher\DefaultFetcher
*
* @see \Drupal\aggregator\Plugin\AggregatorPluginManager
* @see \Drupal\aggregator\Plugin\FetcherInterface
* @see \Drupal\aggregator\Plugin\AggregatorPluginSettingsBase
* @see plugin_api
*
* @Annotation
*/
class AggregatorFetcher extends Plugin {
/**
* The plugin ID.
*
* @var string
*/
public $id;
/**
* The title of the plugin.
*
* @var \Drupal\Core\Annotation\Translation
*
* @ingroup plugin_translatable
*/
public $title;
/**
* The description of the plugin.
*
* @var \Drupal\Core\Annotation\Translation
*
* @ingroup plugin_translatable
*/
public $description;
}

View File

@ -1,48 +0,0 @@
<?php
namespace Drupal\aggregator\Annotation;
use Drupal\Component\Annotation\Plugin;
/**
* Defines a Plugin annotation object for aggregator parser plugins.
*
* Plugin Namespace: Plugin\aggregator\parser
*
* For a working example, see \Drupal\aggregator\Plugin\aggregator\parser\DefaultParser
*
* @see \Drupal\aggregator\Plugin\AggregatorPluginManager
* @see \Drupal\aggregator\Plugin\ParserInterface
* @see \Drupal\aggregator\Plugin\AggregatorPluginSettingsBase
* @see plugin_api
*
* @Annotation
*/
class AggregatorParser extends Plugin {
/**
* The plugin ID.
*
* @var string
*/
public $id;
/**
* The title of the plugin.
*
* @var \Drupal\Core\Annotation\Translation
*
* @ingroup plugin_translatable
*/
public $title;
/**
* The description of the plugin.
*
* @var \Drupal\Core\Annotation\Translation
*
* @ingroup plugin_translatable
*/
public $description;
}

View File

@ -1,48 +0,0 @@
<?php
namespace Drupal\aggregator\Annotation;
use Drupal\Component\Annotation\Plugin;
/**
* Defines a Plugin annotation object for aggregator processor plugins.
*
* Plugin Namespace: Plugin\aggregator\processor
*
* For a working example, see \Drupal\aggregator\Plugin\aggregator\processor\DefaultProcessor
*
* @see \Drupal\aggregator\Plugin\AggregatorPluginManager
* @see \Drupal\aggregator\Plugin\ProcessorInterface
* @see \Drupal\aggregator\Plugin\AggregatorPluginSettingsBase
* @see plugin_api
*
* @Annotation
*/
class AggregatorProcessor extends Plugin {
/**
* The plugin ID.
*
* @var string
*/
public $id;
/**
* The title of the plugin.
*
* @var \Drupal\Core\Annotation\Translation
*
* @ingroup plugin_translatable
*/
public $title;
/**
* The description of the plugin.
*
* @var \Drupal\Core\Annotation\Translation
*
* @ingroup plugin_translatable
*/
public $description;
}

View File

@ -1,195 +0,0 @@
<?php
namespace Drupal\aggregator\Controller;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\aggregator\FeedInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Returns responses for aggregator module routes.
*/
class AggregatorController extends ControllerBase {
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* Constructs a \Drupal\aggregator\Controller\AggregatorController object.
*
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
* The date formatter service.
*/
public function __construct(DateFormatterInterface $date_formatter) {
$this->dateFormatter = $date_formatter;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('date.formatter')
);
}
/**
* Presents the aggregator feed creation form.
*
* @return array
* A form array as expected by
* \Drupal\Core\Render\RendererInterface::render().
*/
public function feedAdd() {
$feed = $this->entityTypeManager()->getStorage('aggregator_feed')->create();
return $this->entityFormBuilder()->getForm($feed);
}
/**
* 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 = [
'#type' => 'container',
'#attributes' => ['class' => ['aggregator-wrapper']],
];
$build['feed_source'] = is_array($feed_source) ? $feed_source : ['#markup' => $feed_source];
if ($items) {
$build['items'] = $this->entityTypeManager()->getViewBuilder('aggregator_item')
->viewMultiple($items, 'default');
$build['pager'] = ['#type' => 'pager'];
}
return $build;
}
/**
* Refreshes a feed, then redirects to the overview page.
*
* @param \Drupal\aggregator\FeedInterface $aggregator_feed
* An object describing the feed to be refreshed.
*
* @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) {
$message = $aggregator_feed->refreshItems()
? $this->t('There is new syndicated content from %site.', ['%site' => $aggregator_feed->label()])
: $this->t('There is no new syndicated content from %site.', ['%site' => $aggregator_feed->label()]);
$this->messenger()->addStatus($message);
return $this->redirect('aggregator.admin_overview');
}
/**
* Displays the aggregator administration page.
*
* @return array
* A render array as expected by
* \Drupal\Core\Render\RendererInterface::render().
*/
public function adminOverview() {
$entity_type_manager = $this->entityTypeManager();
$feeds = $entity_type_manager->getStorage('aggregator_feed')
->loadMultiple();
$header = [$this->t('Title'), $this->t('Items'), $this->t('Last update'), $this->t('Next update'), $this->t('Operations')];
$rows = [];
/** @var \Drupal\aggregator\FeedInterface[] $feeds */
foreach ($feeds as $feed) {
$row = [];
$row[] = $feed->toLink()->toString();
$row[] = $this->formatPlural($entity_type_manager->getStorage('aggregator_item')->getItemCount($feed), '1 item', '@count items');
$last_checked = $feed->getLastCheckedTime();
$refresh_rate = $feed->getRefreshRate();
$row[] = ($last_checked ? $this->t('@time ago', ['@time' => $this->dateFormatter->formatInterval(REQUEST_TIME - $last_checked)]) : $this->t('never'));
if (!$last_checked && $refresh_rate) {
$next_update = $this->t('imminently');
}
elseif ($last_checked && $refresh_rate) {
$next_update = $this->t('%time left', ['%time' => $this->dateFormatter->formatInterval($last_checked + $refresh_rate - REQUEST_TIME)]);
}
else {
$next_update = $this->t('never');
}
$row[] = $next_update;
$links['edit'] = [
'title' => $this->t('Edit'),
'url' => Url::fromRoute('entity.aggregator_feed.edit_form', ['aggregator_feed' => $feed->id()]),
];
$links['delete'] = [
'title' => $this->t('Delete'),
'url' => Url::fromRoute('entity.aggregator_feed.delete_form', ['aggregator_feed' => $feed->id()]),
];
$links['delete_items'] = [
'title' => $this->t('Delete items'),
'url' => Url::fromRoute('aggregator.feed_items_delete', ['aggregator_feed' => $feed->id()]),
];
$links['update'] = [
'title' => $this->t('Update items'),
'url' => Url::fromRoute('aggregator.feed_refresh', ['aggregator_feed' => $feed->id()]),
];
$row[] = [
'data' => [
'#type' => 'operations',
'#links' => $links,
],
];
$rows[] = $row;
}
$build['feeds'] = [
'#prefix' => '<h3>' . $this->t('Feed overview') . '</h3>',
'#type' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' => $this->t('No feeds available. <a href=":link">Add feed</a>.', [':link' => Url::fromRoute('aggregator.feed_add')->toString()]),
];
return $build;
}
/**
* Displays the most recent items gathered from any feed.
*
* @return string
* The rendered list of items for the feed.
*/
public function pageLast() {
$items = $this->entityTypeManager()->getStorage('aggregator_item')->loadAll(20);
$build = $this->buildPageList($items);
$build['#attached']['feed'][] = ['aggregator/rss', $this->config('system.site')->get('name') . ' ' . $this->t('aggregator')];
return $build;
}
/**
* Route title callback.
*
* @param \Drupal\aggregator\FeedInterface $aggregator_feed
* The aggregator feed.
*
* @return array
* The feed label as a render array.
*/
public function feedTitle(FeedInterface $aggregator_feed) {
return ['#markup' => $aggregator_feed->label(), '#allowed_tags' => Xss::getHtmlTagList()];
}
}

View File

@ -1,399 +0,0 @@
<?php
namespace Drupal\aggregator\Entity;
use Drupal\aggregator\FeedStorageInterface;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\aggregator\FeedInterface;
/**
* Defines the aggregator feed entity class.
*
* @ContentEntityType(
* id = "aggregator_feed",
* label = @Translation("Aggregator feed"),
* label_collection = @Translation("Aggregator feeds"),
* label_singular = @Translation("aggregator feed"),
* label_plural = @Translation("aggregator feeds"),
* label_count = @PluralTranslation(
* singular = "@count aggregator feed",
* plural = "@count aggregator feeds",
* ),
* handlers = {
* "storage" = "Drupal\aggregator\FeedStorage",
* "storage_schema" = "Drupal\aggregator\FeedStorageSchema",
* "view_builder" = "Drupal\aggregator\FeedViewBuilder",
* "access" = "Drupal\aggregator\FeedAccessControlHandler",
* "views_data" = "Drupal\aggregator\AggregatorFeedViewsData",
* "form" = {
* "default" = "Drupal\aggregator\FeedForm",
* "delete" = "Drupal\aggregator\Form\FeedDeleteForm",
* "delete_items" = "Drupal\aggregator\Form\FeedItemsDeleteForm",
* },
* "route_provider" = {
* "html" = "Drupal\aggregator\FeedHtmlRouteProvider",
* },
* },
* links = {
* "canonical" = "/aggregator/sources/{aggregator_feed}",
* "edit-form" = "/aggregator/sources/{aggregator_feed}/configure",
* "delete-form" = "/aggregator/sources/{aggregator_feed}/delete",
* },
* field_ui_base_route = "aggregator.admin_overview",
* base_table = "aggregator_feed",
* render_cache = FALSE,
* entity_keys = {
* "id" = "fid",
* "label" = "title",
* "langcode" = "langcode",
* "uuid" = "uuid",
* }
* )
*/
class Feed extends ContentEntityBase implements FeedInterface {
/**
* {@inheritdoc}
*/
public function label() {
return $this->get('title')->value;
}
/**
* {@inheritdoc}
*/
public function deleteItems() {
\Drupal::service('aggregator.items.importer')->delete($this);
// Reset feed.
$this->setLastCheckedTime(0);
$this->setHash('');
$this->setEtag('');
$this->setLastModified(0);
$this->save();
return $this;
}
/**
* {@inheritdoc}
*/
public function refreshItems() {
$success = \Drupal::service('aggregator.items.importer')->refresh($this);
// Regardless of successful or not, indicate that it has been checked.
$this->setLastCheckedTime(REQUEST_TIME);
$this->setQueuedTime(0);
$this->save();
return $success;
}
/**
* {@inheritdoc}
*/
public static function preCreate(EntityStorageInterface $storage, array &$values) {
$values += [
'link' => '',
'description' => '',
'image' => '',
];
}
/**
* {@inheritdoc}
*/
public static function preDelete(EntityStorageInterface $storage, array $entities) {
foreach ($entities as $entity) {
// Notify processors to delete stored items.
\Drupal::service('aggregator.items.importer')->delete($entity);
}
}
/**
* {@inheritdoc}
*/
public static function postDelete(EntityStorageInterface $storage, array $entities) {
parent::postDelete($storage, $entities);
if (\Drupal::moduleHandler()->moduleExists('block')) {
// Make sure there are no active blocks for these feeds.
$ids = \Drupal::entityQuery('block')
->accessCheck(FALSE)
->condition('plugin', 'aggregator_feed_block')
->condition('settings.feed', array_keys($entities))
->execute();
if ($ids) {
$block_storage = \Drupal::entityTypeManager()->getStorage('block');
$block_storage->delete($block_storage->loadMultiple($ids));
}
}
}
/**
* {@inheritdoc}
*/
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
/** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
$fields = parent::baseFieldDefinitions($entity_type);
$fields['fid']->setLabel(t('Feed ID'))
->setDescription(t('The ID of the aggregator feed.'));
$fields['uuid']->setDescription(t('The aggregator feed UUID.'));
$fields['langcode']->setLabel(t('Language code'))
->setDescription(t('The feed language code.'));
$fields['title'] = BaseFieldDefinition::create('string')
->setLabel(t('Title'))
->setDescription(t('The name of the feed (or the name of the website providing the feed).'))
->setRequired(TRUE)
->setSetting('max_length', 255)
->setDisplayOptions('form', [
'type' => 'string_textfield',
'weight' => -5,
])
->setDisplayConfigurable('form', TRUE)
->addConstraint('FeedTitle');
$fields['url'] = BaseFieldDefinition::create('uri')
->setLabel(t('URL'))
->setDescription(t('The fully-qualified URL of the feed.'))
->setRequired(TRUE)
->setDisplayOptions('form', [
'type' => 'uri',
'weight' => -3,
])
->setDisplayConfigurable('form', TRUE)
->addConstraint('FeedUrl');
$intervals = [900, 1800, 3600, 7200, 10800, 21600, 32400, 43200, 64800, 86400, 172800, 259200, 604800, 1209600, 2419200];
$period = array_map([\Drupal::service('date.formatter'), 'formatInterval'], array_combine($intervals, $intervals));
$period[FeedStorageInterface::CLEAR_NEVER] = t('Never');
$fields['refresh'] = BaseFieldDefinition::create('list_integer')
->setLabel(t('Update interval'))
->setDescription(t('The length of time between feed updates. Requires a correctly configured cron maintenance task.'))
->setDefaultValue(3600)
->setSetting('unsigned', TRUE)
->setRequired(TRUE)
->setSetting('allowed_values', $period)
->setDisplayOptions('form', [
'type' => 'options_select',
'weight' => -2,
])
->setDisplayConfigurable('form', TRUE);
$fields['checked'] = BaseFieldDefinition::create('timestamp')
->setLabel(t('Checked', [], ['context' => 'Examined']))
->setDescription(t('Last time feed was checked for new items, as Unix timestamp.'))
->setDefaultValue(0)
->setDisplayOptions('view', [
'label' => 'inline',
'type' => 'timestamp_ago',
'weight' => 1,
])
->setDisplayConfigurable('view', TRUE);
$fields['queued'] = BaseFieldDefinition::create('timestamp')
->setLabel(t('Queued'))
->setDescription(t('Time when this feed was queued for refresh, 0 if not queued.'))
->setDefaultValue(0);
$fields['link'] = BaseFieldDefinition::create('uri')
->setLabel(t('URL'))
->setDescription(t('The link of the feed.'))
->setDisplayOptions('view', [
'label' => 'inline',
'weight' => 4,
])
->setDisplayConfigurable('view', TRUE);
$fields['description'] = BaseFieldDefinition::create('string_long')
->setLabel(t('Description'))
->setDescription(t("The parent website's description that comes from the @description element in the feed.", ['@description' => '<description>']));
$fields['image'] = BaseFieldDefinition::create('uri')
->setLabel(t('Image'))
->setDescription(t('An image representing the feed.'));
$fields['hash'] = BaseFieldDefinition::create('string')
->setLabel(t('Hash'))
->setSetting('is_ascii', TRUE)
->setDescription(t('Calculated hash of the feed data, used for validating cache.'));
$fields['etag'] = BaseFieldDefinition::create('string')
->setLabel(t('Etag'))
->setDescription(t('Entity tag HTTP response header, used for validating cache.'));
// This is updated by the fetcher and not when the feed is saved, therefore
// it's a timestamp and not a changed field.
$fields['modified'] = BaseFieldDefinition::create('timestamp')
->setLabel(t('Modified'))
->setDescription(t('When the feed was last modified, as a Unix timestamp.'));
return $fields;
}
/**
* {@inheritdoc}
*/
public function getUrl() {
return $this->get('url')->value;
}
/**
* {@inheritdoc}
*/
public function getRefreshRate() {
return $this->get('refresh')->value;
}
/**
* {@inheritdoc}
*/
public function getLastCheckedTime() {
return $this->get('checked')->value;
}
/**
* {@inheritdoc}
*/
public function getQueuedTime() {
return $this->get('queued')->value;
}
/**
* {@inheritdoc}
*/
public function getWebsiteUrl() {
return $this->get('link')->value;
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return $this->get('description')->value;
}
/**
* {@inheritdoc}
*/
public function getImage() {
return $this->get('image')->value;
}
/**
* {@inheritdoc}
*/
public function getHash() {
return $this->get('hash')->value;
}
/**
* {@inheritdoc}
*/
public function getEtag() {
return $this->get('etag')->value;
}
/**
* {@inheritdoc}
*/
public function getLastModified() {
return $this->get('modified')->value;
}
/**
* {@inheritdoc}
*/
public function setTitle($title) {
$this->set('title', $title);
return $this;
}
/**
* {@inheritdoc}
*/
public function setUrl($url) {
$this->set('url', $url);
return $this;
}
/**
* {@inheritdoc}
*/
public function setRefreshRate($refresh) {
$this->set('refresh', $refresh);
return $this;
}
/**
* {@inheritdoc}
*/
public function setLastCheckedTime($checked) {
$this->set('checked', $checked);
return $this;
}
/**
* {@inheritdoc}
*/
public function setQueuedTime($queued) {
$this->set('queued', $queued);
return $this;
}
/**
* {@inheritdoc}
*/
public function setWebsiteUrl($link) {
$this->set('link', $link);
return $this;
}
/**
* {@inheritdoc}
*/
public function setDescription($description) {
$this->set('description', $description);
return $this;
}
/**
* {@inheritdoc}
*/
public function setImage($image) {
$this->set('image', $image);
return $this;
}
/**
* {@inheritdoc}
*/
public function setHash($hash) {
$this->set('hash', $hash);
return $this;
}
/**
* {@inheritdoc}
*/
public function setEtag($etag) {
$this->set('etag', $etag);
return $this;
}
/**
* {@inheritdoc}
*/
public function setLastModified($modified) {
$this->set('modified', $modified);
return $this;
}
}

View File

@ -1,249 +0,0 @@
<?php
namespace Drupal\aggregator\Entity;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\aggregator\ItemInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Url;
/**
* Defines the aggregator item entity class.
*
* @ContentEntityType(
* id = "aggregator_item",
* label = @Translation("Aggregator feed item"),
* label_collection = @Translation("Aggregator feed items"),
* label_singular = @Translation("aggregator feed item"),
* label_plural = @Translation("aggregator feed items"),
* label_count = @PluralTranslation(
* singular = "@count aggregator feed item",
* plural = "@count aggregator feed items",
* ),
* handlers = {
* "storage" = "Drupal\aggregator\ItemStorage",
* "storage_schema" = "Drupal\aggregator\ItemStorageSchema",
* "view_builder" = "Drupal\aggregator\ItemViewBuilder",
* "access" = "Drupal\aggregator\FeedAccessControlHandler",
* "views_data" = "Drupal\aggregator\AggregatorItemViewsData"
* },
* uri_callback = "Drupal\aggregator\Entity\Item::buildUri",
* base_table = "aggregator_item",
* render_cache = FALSE,
* list_cache_tags = { "aggregator_feed_list" },
* entity_keys = {
* "id" = "iid",
* "label" = "title",
* "langcode" = "langcode",
* }
* )
*/
class Item extends ContentEntityBase implements ItemInterface {
/**
* {@inheritdoc}
*/
public function label() {
return $this->get('title')->value;
}
/**
* {@inheritdoc}
*/
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
/** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
$fields = parent::baseFieldDefinitions($entity_type);
$fields['iid']->setLabel(t('Aggregator item ID'))
->setDescription(t('The ID of the feed item.'));
$fields['langcode']->setLabel(t('Language code'))
->setDescription(t('The feed item language code.'));
$fields['fid'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Source feed'))
->setRequired(TRUE)
->setDescription(t('The aggregator feed entity associated with this item.'))
->setSetting('target_type', 'aggregator_feed')
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'entity_reference_label',
'weight' => 0,
])
->setDisplayConfigurable('form', TRUE);
$fields['title'] = BaseFieldDefinition::create('string')
->setLabel(t('Title'))
->setDescription(t('The title of the feed item.'));
$fields['link'] = BaseFieldDefinition::create('uri')
->setLabel(t('Link'))
->setDescription(t('The link of the feed item.'))
->setDisplayOptions('view', [
'region' => 'hidden',
])
->setDisplayConfigurable('view', TRUE);
$fields['author'] = BaseFieldDefinition::create('string')
->setLabel(t('Author'))
->setDescription(t('The author of the feed item.'))
->setDisplayOptions('view', [
'label' => 'hidden',
'weight' => 3,
])
->setDisplayConfigurable('view', TRUE);
$fields['description'] = BaseFieldDefinition::create('string_long')
->setLabel(t('Description'))
->setDescription(t('The body of the feed item.'));
$fields['timestamp'] = BaseFieldDefinition::create('created')
->setLabel(t('Posted on'))
->setDescription(t('Posted date of the feed item, as a Unix timestamp.'))
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'timestamp_ago',
'weight' => 1,
])
->setDisplayConfigurable('view', TRUE);
// @todo Convert to a real UUID field in
// https://www.drupal.org/node/2149851.
$fields['guid'] = BaseFieldDefinition::create('string_long')
->setLabel(t('GUID'))
->setDescription(t('Unique identifier for the feed item.'));
return $fields;
}
/**
* {@inheritdoc}
*/
public function getFeedId() {
return $this->get('fid')->target_id;
}
/**
* {@inheritdoc}
*/
public function setFeedId($fid) {
return $this->set('fid', $fid);
}
/**
* {@inheritdoc}
*/
public function getTitle() {
return $this->get('title')->value;
}
/**
* {@inheritdoc}
*/
public function setTitle($title) {
return $this->set('title', $title);
}
/**
* {@inheritdoc}
*/
public function getLink() {
return $this->get('link')->value ?? '';
}
/**
* {@inheritdoc}
*/
public function setLink($link) {
return $this->set('link', $link);
}
/**
* {@inheritdoc}
*/
public function getAuthor() {
return $this->get('author')->value;
}
/**
* {@inheritdoc}
*/
public function setAuthor($author) {
return $this->set('author', $author);
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return $this->get('description')->value;
}
/**
* {@inheritdoc}
*/
public function setDescription($description) {
return $this->set('description', $description);
}
/**
* {@inheritdoc}
*/
public function getPostedTime() {
return $this->get('timestamp')->value;
}
/**
* {@inheritdoc}
*/
public function setPostedTime($timestamp) {
return $this->set('timestamp', $timestamp);
}
/**
* {@inheritdoc}
*/
public function getGuid() {
return $this->get('guid')->value;
}
/**
* {@inheritdoc}
*/
public function setGuid($guid) {
return $this->set('guid', $guid);
}
/**
* {@inheritdoc}
*/
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
parent::postSave($storage, $update);
// Entity::postSave() calls Entity::invalidateTagsOnSave(), which only
// handles the regular cases. The Item entity has one special case: a newly
// created Item is *also* associated with a Feed, so we must invalidate the
// associated Feed's cache tag.
if (!$update) {
Cache::invalidateTags($this->getCacheTagsToInvalidate());
}
}
/**
* {@inheritdoc}
*/
public function getCacheTagsToInvalidate() {
return Feed::load($this->getFeedId())->getCacheTags();
}
/**
* Entity URI callback.
*/
public static function buildUri(ItemInterface $item) {
return Url::fromUri($item->getLink());
}
}

View File

@ -1,37 +0,0 @@
<?php
namespace Drupal\aggregator;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
/**
* Defines an access control handler for the feed entity.
*
* @see \Drupal\aggregator\Entity\Feed
*/
class FeedAccessControlHandler extends EntityAccessControlHandler {
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
switch ($operation) {
case 'view':
return AccessResult::allowedIfHasPermission($account, 'access news feeds');
default:
return AccessResult::allowedIfHasPermission($account, 'administer news feeds');
}
}
/**
* {@inheritdoc}
*/
protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
return AccessResult::allowedIfHasPermission($account, 'administer news feeds');
}
}

View File

@ -1,35 +0,0 @@
<?php
namespace Drupal\aggregator;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;
/**
* Form handler for the aggregator feed edit forms.
*
* @internal
*/
class FeedForm extends ContentEntityForm {
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$feed = $this->entity;
$status = $feed->save();
$label = $feed->label();
$view_link = $feed->toLink($label, 'canonical')->toString();
if ($status == SAVED_UPDATED) {
$this->messenger()->addStatus($this->t('The feed %feed has been updated.', ['%feed' => $view_link]));
$form_state->setRedirectUrl($feed->toUrl('canonical'));
}
else {
$this->logger('aggregator')->notice('Feed %feed added.', ['%feed' => $feed->label(), 'link' => Link::fromTextAndUrl($this->t('View'), new Url('aggregator.admin_overview'))->toString()]);
$this->messenger()->addStatus($this->t('The feed %feed has been added.', ['%feed' => $view_link]));
}
}
}

View File

@ -1,34 +0,0 @@
<?php
namespace Drupal\aggregator;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Routing\AdminHtmlRouteProvider;
/**
* Provides HTML routes for the feed entity type.
*/
class FeedHtmlRouteProvider extends AdminHtmlRouteProvider {
/**
* {@inheritdoc}
*/
protected function getCanonicalRoute(EntityTypeInterface $entity_type) {
$route = parent::getCanonicalRoute($entity_type);
$route->setDefault('_title_controller', '\Drupal\aggregator\Controller\AggregatorController::feedTitle');
return $route;
}
/**
* {@inheritdoc}
*/
protected function getEditFormRoute(EntityTypeInterface $entity_type) {
$route = parent::getEditFormRoute($entity_type);
$route->setDefault('_title', 'Configure');
return $route;
}
}

View File

@ -1,239 +0,0 @@
<?php
namespace Drupal\aggregator;
use Drupal\Core\Entity\ContentEntityInterface;
/**
* Provides an interface defining an aggregator feed entity.
*/
interface FeedInterface extends ContentEntityInterface {
/**
* Sets the title of the feed.
*
* @param string $title
* The short title of the feed.
*
* @return $this
* The class instance that this method is called on.
*/
public function setTitle($title);
/**
* Returns the url to the feed.
*
* @return string
* The url to the feed.
*/
public function getUrl();
/**
* Sets the url to the feed.
*
* @param string $url
* A string containing the url of the feed.
*
* @return $this
* The class instance that this method is called on.
*/
public function setUrl($url);
/**
* Returns the refresh rate of the feed in seconds.
*
* @return int
* The refresh rate of the feed in seconds.
*/
public function getRefreshRate();
/**
* Sets the refresh rate of the feed in seconds.
*
* @param int $refresh
* The refresh rate of the feed in seconds.
*
* @return $this
* The class instance that this method is called on.
*/
public function setRefreshRate($refresh);
/**
* Returns the last time where the feed was checked for new items.
*
* @return int
* The timestamp when new items were last checked for.
*/
public function getLastCheckedTime();
/**
* Sets the time when this feed was queued for refresh, 0 if not queued.
*
* @param int $checked
* The timestamp of the last refresh.
*
* @return $this
* The class instance that this method is called on.
*/
public function setLastCheckedTime($checked);
/**
* Returns the time when this feed was queued for refresh, 0 if not queued.
*
* @return int
* The timestamp of the last refresh.
*/
public function getQueuedTime();
/**
* Sets the time when this feed was queued for refresh, 0 if not queued.
*
* @param int $queued
* The timestamp of the last refresh.
*
* @return $this
* The class instance that this method is called on.
*/
public function setQueuedTime($queued);
/**
* Returns the parent website of the feed.
*
* @return string
* The parent website of the feed.
*/
public function getWebsiteUrl();
/**
* Sets the parent website of the feed.
*
* @param string $link
* A string containing the parent website of the feed.
*
* @return $this
* The class instance that this method is called on.
*/
public function setWebsiteUrl($link);
/**
* Returns the description of the feed.
*
* @return string
* The description of the feed.
*/
public function getDescription();
/**
* Sets the description of the feed.
*
* @param string $description
* The description of the feed.
*
* @return $this
* The class instance that this method is called on.
*/
public function setDescription($description);
/**
* Returns the primary image attached to the feed.
*
* @return string
* The URL of the primary image attached to the feed.
*/
public function getImage();
/**
* Sets the primary image attached to the feed.
*
* @param string $image
* An image URL.
*
* @return $this
* The class instance that this method is called on.
*/
public function setImage($image);
/**
* Returns the calculated hash of the feed data, used for validating cache.
*
* @return string
* The calculated hash of the feed data.
*/
public function getHash();
/**
* Sets the calculated hash of the feed data, used for validating cache.
*
* @param string $hash
* A string containing the calculated hash of the feed. Must contain
* US ASCII characters only.
*
* @return $this
* The class instance that this method is called on.
*/
public function setHash($hash);
/**
* Returns the entity tag HTTP response header, used for validating cache.
*
* @return string
* The entity tag HTTP response header.
*/
public function getEtag();
/**
* Sets the entity tag HTTP response header, used for validating cache.
*
* @param string $etag
* A string containing the entity tag HTTP response header.
*
* @return $this
* The class instance that this method is called on.
*/
public function setEtag($etag);
/**
* Return when the feed was modified last time.
*
* @return int
* The timestamp of the last time the feed was modified.
*/
public function getLastModified();
/**
* Sets the last modification of the feed.
*
* @param int $modified
* The timestamp when the feed was modified.
*
* @return $this
* The class instance that this method is called on.
*/
public function setLastModified($modified);
/**
* Deletes all items from a feed.
*
* This will also reset the last checked and modified time of the feed and
* save it.
*
* @return $this
* The class instance that this method is called on.
*
* @see \Drupal\aggregator\ItemsImporterInterface::delete()
*/
public function deleteItems();
/**
* Updates the feed items by triggering the import process.
*
* This will also update the last checked time of the feed and save it.
*
* @return bool
* TRUE if there is new content for the feed FALSE otherwise.
*
* @see \Drupal\aggregator\ItemsImporterInterface::refresh()
*/
public function refreshItems();
}

View File

@ -1,25 +0,0 @@
<?php
namespace Drupal\aggregator;
use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
/**
* Defines the storage handler class for feed entities.
*
* This extends the base storage class, adding required special handling for
* feed entities.
*/
class FeedStorage extends SqlContentEntityStorage implements FeedStorageInterface {
/**
* {@inheritdoc}
*/
public function getFeedIdsToRefresh() {
return $this->database->query('SELECT [fid] FROM {' . $this->getBaseTable() . '} WHERE [queued] = 0 AND [checked] + [refresh] < :time AND [refresh] <> :never', [
':time' => REQUEST_TIME,
':never' => static::CLEAR_NEVER,
])->fetchCol();
}
}

View File

@ -1,25 +0,0 @@
<?php
namespace Drupal\aggregator;
use Drupal\Core\Entity\ContentEntityStorageInterface;
/**
* Defines an interface for aggregator feed entity storage classes.
*/
interface FeedStorageInterface extends ContentEntityStorageInterface {
/**
* Denotes that a feed's items should never expire.
*/
const CLEAR_NEVER = 0;
/**
* Returns the fids of feeds that need to be refreshed.
*
* @return array
* A list of feed ids to be refreshed.
*/
public function getFeedIdsToRefresh();
}

View File

@ -1,36 +0,0 @@
<?php
namespace Drupal\aggregator;
use Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
/**
* Defines the feed schema handler.
*/
class FeedStorageSchema extends SqlContentEntityStorageSchema {
/**
* {@inheritdoc}
*/
protected function getSharedTableFieldSchema(FieldStorageDefinitionInterface $storage_definition, $table_name, array $column_mapping) {
$schema = parent::getSharedTableFieldSchema($storage_definition, $table_name, $column_mapping);
$field_name = $storage_definition->getName();
if ($table_name == $this->storage->getBaseTable()) {
switch ($field_name) {
case 'url':
$this->addSharedTableFieldIndex($storage_definition, $schema, TRUE, 255);
break;
case 'queued':
case 'title':
$this->addSharedTableFieldIndex($storage_definition, $schema, TRUE);
break;
}
}
return $schema;
}
}

View File

@ -1,168 +0,0 @@
<?php
namespace Drupal\aggregator;
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityViewBuilder;
use Drupal\Core\Config\Config;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Theme\Registry;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* View builder handler for aggregator feeds.
*/
class FeedViewBuilder extends EntityViewBuilder {
/**
* The 'aggregator.settings' config.
*
* @var \Drupal\Core\Config\Config
*/
protected $config;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a new FeedViewBuilder.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type definition.
* @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
* The entity repository service.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Drupal\Core\Config\Config $config
* The 'aggregator.settings' config.
* @param \Drupal\Core\Theme\Registry $theme_registry
* The theme registry.
* @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entity_display_repository
* The entity display repository.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(EntityTypeInterface $entity_type, EntityRepositoryInterface $entity_repository, LanguageManagerInterface $language_manager, Config $config, Registry $theme_registry, EntityDisplayRepositoryInterface $entity_display_repository, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($entity_type, $entity_repository, $language_manager, $theme_registry, $entity_display_repository);
$this->config = $config;
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$entity_type,
$container->get('entity.repository'),
$container->get('language_manager'),
$container->get('config.factory')->get('aggregator.settings'),
$container->get('theme.registry'),
$container->get('entity_display.repository'),
$container->get('entity_type.manager')
);
}
/**
* {@inheritdoc}
*/
public function buildComponents(array &$build, array $entities, array $displays, $view_mode) {
parent::buildComponents($build, $entities, $displays, $view_mode);
foreach ($entities as $id => $entity) {
$bundle = $entity->bundle();
$display = $displays[$bundle];
if ($display->getComponent('items')) {
// When in summary view mode, respect the list_max setting.
$limit = $view_mode == 'summary' ? $this->config->get('source.list_max') : 20;
// Retrieve the items attached to this feed.
$items = $this->entityTypeManager
->getStorage('aggregator_item')
->loadByFeed($entity->id(), $limit);
$build[$id]['items'] = $this->entityTypeManager
->getViewBuilder('aggregator_item')
->viewMultiple($items, $view_mode, $entity->language()->getId());
if ($view_mode == 'full') {
// Also add the pager.
$build[$id]['pager'] = ['#type' => 'pager'];
}
}
// By default, the description and image fields are exposed as
// pseudo-fields rendered in this function. However they can optionally
// be rendered directly using a field formatter. Skip rendering here if a
// field formatter type is set.
$component = $display->getComponent('description');
if ($component && !isset($component['type'])) {
$build[$id]['description'] = [
'#markup' => $entity->getDescription(),
'#allowed_tags' => _aggregator_allowed_tags(),
'#prefix' => '<div class="feed-description">',
'#suffix' => '</div>',
];
}
$component = $display->getComponent('image');
if ($component && !isset($component['type'])) {
$image_link = [];
// Render the image as link if it is available.
$image = $entity->getImage();
$label = $entity->label();
$link_href = $entity->getWebsiteUrl();
if ($image && $label && $link_href) {
$link_title = [
'#theme' => 'image',
'#uri' => $image,
'#alt' => $label,
];
$image_link = [
'#type' => 'link',
'#title' => $link_title,
'#url' => Url::fromUri($link_href),
'#options' => [
'attributes' => ['class' => ['feed-image']],
],
];
}
$build[$id]['image'] = $image_link;
}
if ($display->getComponent('feed_icon')) {
$build[$id]['feed_icon'] = [
'#theme' => 'feed_icon',
'#url' => $entity->getUrl(),
'#title' => t('@title feed', ['@title' => $entity->label()]),
];
}
if ($display->getComponent('more_link')) {
$title_stripped = strip_tags($entity->label());
$build[$id]['more_link'] = [
'#type' => 'link',
'#title' => t('More<span class="visually-hidden"> posts about @title</span>', [
'@title' => $title_stripped,
]),
'#url' => Url::fromRoute('entity.aggregator_feed.canonical', ['aggregator_feed' => $entity->id()]),
'#options' => [
'attributes' => [
'title' => $title_stripped,
],
],
];
}
}
}
}

View File

@ -1,38 +0,0 @@
<?php
namespace Drupal\aggregator\Form;
use Drupal\Core\Entity\ContentEntityDeleteForm;
use Drupal\Core\Url;
/**
* Provides a form for deleting a feed.
*
* @internal
*/
class FeedDeleteForm extends ContentEntityDeleteForm {
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('aggregator.admin_overview');
}
/**
* {@inheritdoc}
*/
protected function getRedirectUrl() {
return $this->getCancelUrl();
}
/**
* {@inheritdoc}
*/
protected function getDeletionMessage() {
return $this->t('The feed %label has been deleted.', [
'%label' => $this->entity->label(),
]);
}
}

View File

@ -1,46 +0,0 @@
<?php
namespace Drupal\aggregator\Form;
use Drupal\Core\Entity\ContentEntityConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Provides a deletion confirmation form for items that belong to a feed.
*
* @internal
*/
class FeedItemsDeleteForm extends ContentEntityConfirmFormBase {
/**
* {@inheritdoc}
*/
public function getQuestion() {
return $this->t('Are you sure you want to delete all items from the feed %feed?', ['%feed' => $this->entity->label()]);
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('aggregator.admin_overview');
}
/**
* {@inheritdoc}
*/
public function getConfirmText() {
return $this->t('Delete items');
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->entity->deleteItems();
$form_state->setRedirectUrl($this->getCancelUrl());
}
}

View File

@ -1,213 +0,0 @@
<?php
namespace Drupal\aggregator\Form;
use Drupal\aggregator\FeedStorageInterface;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use GuzzleHttp\Exception\TransferException;
use GuzzleHttp\ClientInterface;
/**
* Imports feeds from OPML.
*
* @internal
*/
class OpmlFeedAdd extends FormBase {
/**
* The feed storage.
*
* @var \Drupal\aggregator\FeedStorageInterface
*/
protected $feedStorage;
/**
* The HTTP client to fetch the feed data with.
*
* @var \GuzzleHttp\ClientInterface
*/
protected $httpClient;
/**
* Constructs a database object.
*
* @param \Drupal\aggregator\FeedStorageInterface $feed_storage
* The feed storage.
* @param \GuzzleHttp\ClientInterface $http_client
* The Guzzle HTTP client.
*/
public function __construct(FeedStorageInterface $feed_storage, ClientInterface $http_client) {
$this->feedStorage = $feed_storage;
$this->httpClient = $http_client;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager')->getStorage('aggregator_feed'),
$container->get('http_client')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'aggregator_opml_add';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$intervals = [900, 1800, 3600, 7200, 10800, 21600, 32400, 43200, 64800, 86400, 172800, 259200, 604800, 1209600, 2419200];
$period = array_map([\Drupal::service('date.formatter'), 'formatInterval'], array_combine($intervals, $intervals));
$form['upload'] = [
'#type' => 'file',
'#title' => $this->t('OPML File'),
'#description' => $this->t('Upload an OPML file containing a list of feeds to be imported.'),
];
$form['remote'] = [
'#type' => 'url',
'#title' => $this->t('OPML Remote URL'),
'#maxlength' => 1024,
'#description' => $this->t('Enter the URL of an OPML file. This file will be downloaded and processed only once on submission of the form.'),
];
$form['refresh'] = [
'#type' => 'select',
'#title' => $this->t('Update interval'),
'#default_value' => 3600,
'#options' => $period,
'#description' => $this->t('The length of time between feed updates. Requires a correctly configured <a href=":cron">cron maintenance task</a>.', [':cron' => Url::fromRoute('system.status')->toString()]),
];
$form['actions'] = ['#type' => 'actions'];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Import'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
// If both fields are empty or filled, cancel.
$all_files = $this->getRequest()->files->get('files', []);
if ($form_state->isValueEmpty('remote') == empty($all_files['upload'])) {
$form_state->setErrorByName('remote', $this->t('<em>Either</em> upload a file or enter a URL.'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$validators = ['file_validate_extensions' => ['opml xml']];
if ($file = file_save_upload('upload', $validators, FALSE, 0)) {
$data = file_get_contents($file->getFileUri());
}
else {
// @todo Move this to a fetcher implementation.
try {
$response = $this->httpClient->get($form_state->getValue('remote'));
$data = (string) $response->getBody();
}
catch (TransferException $e) {
$this->logger('aggregator')->warning('Failed to download OPML file due to "%error".', ['%error' => $e->getMessage()]);
$this->messenger()->addStatus($this->t('Failed to download OPML file due to "%error".', ['%error' => $e->getMessage()]));
return;
}
}
$feeds = $this->parseOpml($data);
if (empty($feeds)) {
$this->messenger()->addStatus($this->t('No new feed has been added.'));
return;
}
// @todo Move this functionality to a processor.
foreach ($feeds as $feed) {
// Ensure URL is valid.
if (!UrlHelper::isValid($feed['url'], TRUE)) {
$this->messenger()->addWarning($this->t('The URL %url is invalid.', ['%url' => $feed['url']]));
continue;
}
// Check for duplicate titles or URLs.
$query = $this->feedStorage->getQuery()->accessCheck(FALSE);
$condition = $query->orConditionGroup()
->condition('title', $feed['title'])
->condition('url', $feed['url']);
$ids = $query
->condition($condition)
->execute();
$result = $this->feedStorage->loadMultiple($ids);
foreach ($result as $old) {
if (strcasecmp($old->label(), $feed['title']) == 0) {
$this->messenger()->addWarning($this->t('A feed named %title already exists.', ['%title' => $old->label()]));
continue 2;
}
if (strcasecmp($old->getUrl(), $feed['url']) == 0) {
$this->messenger()->addWarning($this->t('A feed with the URL %url already exists.', ['%url' => $old->getUrl()]));
continue 2;
}
}
$new_feed = $this->feedStorage->create([
'title' => $feed['title'],
'url' => $feed['url'],
'refresh' => $form_state->getValue('refresh'),
]);
$new_feed->save();
}
$form_state->setRedirect('aggregator.admin_overview');
}
/**
* Parses an OPML file.
*
* Feeds are recognized as <outline> elements with the attributes "text" and
* "xmlurl" set.
*
* @param string $opml
* The complete contents of an OPML document.
*
* @return array
* An array of feeds, each an associative array with a "title" and a "url"
* element, or NULL if the OPML document failed to be parsed. An empty array
* will be returned if the document is valid but contains no feeds, as some
* OPML documents do.
*
* @todo Move this to a parser in https://www.drupal.org/node/1963540.
*/
protected function parseOpml($opml) {
$feeds = [];
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_TARGET_ENCODING, 'utf-8');
if (xml_parse_into_struct($xml_parser, $opml, $values)) {
foreach ($values as $entry) {
if ($entry['tag'] == 'OUTLINE' && isset($entry['attributes'])) {
$item = $entry['attributes'];
if (!empty($item['XMLURL']) && !empty($item['TEXT'])) {
$feeds[] = ['title' => $item['TEXT'], 'url' => $item['XMLURL']];
}
}
}
}
xml_parser_free($xml_parser);
return $feeds;
}
}

View File

@ -1,227 +0,0 @@
<?php
namespace Drupal\aggregator\Form;
use Drupal\aggregator\Plugin\AggregatorPluginManager;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\PluginFormInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\Form\ConfigFormBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Configures aggregator settings for this site.
*
* @internal
*/
class SettingsForm extends ConfigFormBase {
/**
* The aggregator plugin managers.
*
* @var \Drupal\aggregator\Plugin\AggregatorPluginManager[]
*/
protected $managers = [];
/**
* The instantiated plugin instances that have configuration forms.
*
* @var \Drupal\Core\Plugin\PluginFormInterface[]
*/
protected $configurableInstances = [];
/**
* The aggregator plugin definitions.
*
* @var array
*/
protected $definitions = [
'fetcher' => [],
'parser' => [],
'processor' => [],
];
/**
* Constructs a \Drupal\aggregator\SettingsForm object.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
* @param \Drupal\aggregator\Plugin\AggregatorPluginManager $fetcher_manager
* The aggregator fetcher plugin manager.
* @param \Drupal\aggregator\Plugin\AggregatorPluginManager $parser_manager
* The aggregator parser plugin manager.
* @param \Drupal\aggregator\Plugin\AggregatorPluginManager $processor_manager
* The aggregator processor plugin manager.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation manager.
*/
public function __construct(ConfigFactoryInterface $config_factory, AggregatorPluginManager $fetcher_manager, AggregatorPluginManager $parser_manager, AggregatorPluginManager $processor_manager, TranslationInterface $string_translation) {
parent::__construct($config_factory);
$this->stringTranslation = $string_translation;
$this->managers = [
'fetcher' => $fetcher_manager,
'parser' => $parser_manager,
'processor' => $processor_manager,
];
// Get all available fetcher, parser and processor definitions.
foreach (['fetcher', 'parser', 'processor'] as $type) {
foreach ($this->managers[$type]->getDefinitions() as $id => $definition) {
$this->definitions[$type][$id] = new FormattableMarkup('@title <span class="description">@description</span>', ['@title' => $definition['title'], '@description' => $definition['description']]);
}
}
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.factory'),
$container->get('plugin.manager.aggregator.fetcher'),
$container->get('plugin.manager.aggregator.parser'),
$container->get('plugin.manager.aggregator.processor'),
$container->get('string_translation')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'aggregator_admin_form';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return ['aggregator.settings'];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('aggregator.settings');
// Global aggregator settings.
$form['aggregator_allowed_html_tags'] = [
'#type' => 'textfield',
'#title' => $this->t('Allowed HTML tags'),
'#size' => 80,
'#maxlength' => 255,
'#default_value' => $config->get('items.allowed_html'),
'#description' => $this->t('A space-separated list of HTML tags allowed in the content of feed items. Disallowed tags are stripped from the content.'),
];
// Only show basic configuration if there are actually options.
$basic_conf = [];
if (count($this->definitions['fetcher']) > 1) {
$basic_conf['aggregator_fetcher'] = [
'#type' => 'radios',
'#title' => $this->t('Fetcher'),
'#description' => $this->t('Fetchers download data from an external source. Choose a fetcher suitable for the external source you would like to download from.'),
'#options' => $this->definitions['fetcher'],
'#default_value' => $config->get('fetcher'),
];
}
if (count($this->definitions['parser']) > 1) {
$basic_conf['aggregator_parser'] = [
'#type' => 'radios',
'#title' => $this->t('Parser'),
'#description' => $this->t('Parsers transform downloaded data into standard structures. Choose a parser suitable for the type of feeds you would like to aggregate.'),
'#options' => $this->definitions['parser'],
'#default_value' => $config->get('parser'),
];
}
if (count($this->definitions['processor']) > 1) {
$basic_conf['aggregator_processors'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Processors'),
'#description' => $this->t('Processors act on parsed feed data, for example they store feed items. Choose the processors suitable for your task.'),
'#options' => $this->definitions['processor'],
'#default_value' => $config->get('processors'),
];
}
if (count($basic_conf)) {
$form['basic_conf'] = [
'#type' => 'details',
'#title' => $this->t('Basic configuration'),
'#description' => $this->t('For most aggregation tasks, the default settings are fine.'),
'#open' => TRUE,
];
$form['basic_conf'] += $basic_conf;
}
// Call buildConfigurationForm() on the active fetcher and parser.
foreach (['fetcher', 'parser'] as $type) {
$active = $config->get($type);
if (array_key_exists($active, $this->definitions[$type])) {
$instance = $this->managers[$type]->createInstance($active);
if ($instance instanceof PluginFormInterface) {
$form = $instance->buildConfigurationForm($form, $form_state);
// Store the instance for validate and submit handlers.
// Keying by ID would bring conflicts, because two instances of a
// different type could have the same ID.
$this->configurableInstances[] = $instance;
}
}
}
// Implementing processor plugins will expect an array at $form['processors'].
$form['processors'] = [];
// Call buildConfigurationForm() for each active processor.
foreach ($this->definitions['processor'] as $id => $definition) {
if (in_array($id, $config->get('processors'))) {
$instance = $this->managers['processor']->createInstance($id);
if ($instance instanceof PluginFormInterface) {
$form = $instance->buildConfigurationForm($form, $form_state);
// Store the instance for validate and submit handlers.
// Keying by ID would bring conflicts, because two instances of a
// different type could have the same ID.
$this->configurableInstances[] = $instance;
}
}
}
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
// Let active plugins validate their settings.
foreach ($this->configurableInstances as $instance) {
$instance->validateConfigurationForm($form, $form_state);
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
parent::submitForm($form, $form_state);
$config = $this->config('aggregator.settings');
// Let active plugins save their settings.
foreach ($this->configurableInstances as $instance) {
$instance->submitConfigurationForm($form, $form_state);
}
$config->set('items.allowed_html', $form_state->getValue('aggregator_allowed_html_tags'));
if ($form_state->hasValue('aggregator_fetcher')) {
$config->set('fetcher', $form_state->getValue('aggregator_fetcher'));
}
if ($form_state->hasValue('aggregator_parser')) {
$config->set('parser', $form_state->getValue('aggregator_parser'));
}
if ($form_state->hasValue('aggregator_processors')) {
$config->set('processors', array_filter($form_state->getValue('aggregator_processors')));
}
$config->save();
}
}

View File

@ -1,145 +0,0 @@
<?php
namespace Drupal\aggregator;
use Drupal\Core\Entity\ContentEntityInterface;
/**
* Provides an interface defining an aggregator item entity.
*/
interface ItemInterface extends ContentEntityInterface {
/**
* Returns the feed id of aggregator item.
*
* @return int
* The feed id.
*/
public function getFeedId();
/**
* Sets the feed id of aggregator item.
*
* @param int $fid
* The feed id.
*
* @return $this
* The called feed item entity.
*/
public function setFeedId($fid);
/**
* Returns the title of the feed item.
*
* @return string
* The title of the feed item.
*/
public function getTitle();
/**
* Sets the title of the feed item.
*
* @param string $title
* The title of the feed item.
*
* @return $this
* The called feed item entity.
*/
public function setTitle($title);
/**
* Returns the link to the feed item.
*
* @return string
* The link to the feed item.
*/
public function getLink();
/**
* Sets the link to the feed item.
*
* @param string $link
* The link to the feed item.
*
* @return $this
* The called feed item entity.
*/
public function setLink($link);
/**
* Returns the author of the feed item.
*
* @return string
* The author of the feed item.
*/
public function getAuthor();
/**
* Sets the author of the feed item.
*
* @param string $author
* The author name of the feed item.
*
* @return $this
* The called feed item entity.
*/
public function setAuthor($author);
/**
* Returns the body of the feed item.
*
* @return string
* The body of the feed item.
*/
public function getDescription();
/**
* Sets the body of the feed item.
*
* @param string $description
* The body of the feed item.
*
* @return $this
* The called feed item entity.
*/
public function setDescription($description);
/**
* Returns the posted date of the feed item, as a Unix timestamp.
*
* @return int
* The posted date of the feed item, as a Unix timestamp.
*/
public function getPostedTime();
/**
* Sets the posted date of the feed item, as a Unix timestamp.
*
* @param int $timestamp
* The posted date of the feed item, as a Unix timestamp.
*
* @return $this
* The called feed item entity.
*/
public function setPostedTime($timestamp);
/**
* Returns the unique identifier for the feed item.
*
* @return string
* The unique identifier for the feed item.
*/
public function getGuid();
/**
* Sets the unique identifier for the feed item.
*
* @param string $guid
* The unique identifier for the feed item.
*
* @return $this
* The called feed item entity.
*/
public function setGuid($guid);
}

View File

@ -1,67 +0,0 @@
<?php
namespace Drupal\aggregator;
use Drupal\Core\Entity\Query\QueryInterface;
use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
/**
* Defines the storage handler class for feed item entities.
*
* This extends the base storage class, adding required special handling for
* feed item entities.
*/
class ItemStorage extends SqlContentEntityStorage implements ItemStorageInterface {
/**
* {@inheritdoc}
*/
public function getItemCount(FeedInterface $feed) {
$query = \Drupal::entityQuery('aggregator_item')
->accessCheck(FALSE)
->condition('fid', $feed->id())
->count();
return $query->execute();
}
/**
* {@inheritdoc}
*/
public function loadAll($limit = NULL) {
$query = \Drupal::entityQuery('aggregator_item');
return $this->executeFeedItemQuery($query, $limit);
}
/**
* {@inheritdoc}
*/
public function loadByFeed($fid, $limit = NULL) {
$query = \Drupal::entityQuery('aggregator_item')
->condition('fid', $fid);
return $this->executeFeedItemQuery($query, $limit);
}
/**
* Helper method to execute an item query.
*
* @param \Drupal\Core\Entity\Query\QueryInterface $query
* The query to execute.
* @param int $limit
* (optional) The number of items to return.
*
* @return \Drupal\aggregator\ItemInterface[]
* An array of the feed items.
*/
protected function executeFeedItemQuery(QueryInterface $query, $limit) {
$query->accessCheck(FALSE)
->sort('timestamp', 'DESC')
->sort('iid', 'DESC');
if (!empty($limit)) {
$query->pager($limit);
}
return $this->loadMultiple($query->execute());
}
}

View File

@ -1,47 +0,0 @@
<?php
namespace Drupal\aggregator;
use Drupal\Core\Entity\ContentEntityStorageInterface;
/**
* Defines an interface for aggregator item entity storage classes.
*/
interface ItemStorageInterface extends ContentEntityStorageInterface {
/**
* Returns the count of the items in a feed.
*
* @param \Drupal\aggregator\FeedInterface $feed
* The feed entity.
*
* @return int
* The count of items associated with a feed.
*/
public function getItemCount(FeedInterface $feed);
/**
* Loads feed items from all feeds.
*
* @param int $limit
* (optional) The number of items to return. Defaults to unlimited.
*
* @return \Drupal\aggregator\ItemInterface[]
* An array of the feed items.
*/
public function loadAll($limit = NULL);
/**
* Loads feed items filtered by a feed.
*
* @param int $fid
* The feed ID to filter by.
* @param int $limit
* (optional) The number of items to return. Defaults to unlimited.
*
* @return \Drupal\aggregator\ItemInterface[]
* An array of the feed items.
*/
public function loadByFeed($fid, $limit = NULL);
}

View File

@ -1,35 +0,0 @@
<?php
namespace Drupal\aggregator;
use Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
/**
* Defines the item schema handler.
*/
class ItemStorageSchema extends SqlContentEntityStorageSchema {
/**
* {@inheritdoc}
*/
protected function getSharedTableFieldSchema(FieldStorageDefinitionInterface $storage_definition, $table_name, array $column_mapping) {
$schema = parent::getSharedTableFieldSchema($storage_definition, $table_name, $column_mapping);
$field_name = $storage_definition->getName();
if ($table_name == $this->storage->getBaseTable()) {
switch ($field_name) {
case 'timestamp':
$this->addSharedTableFieldIndex($storage_definition, $schema, TRUE);
break;
case 'fid':
$this->addSharedTableFieldForeignKey($storage_definition, $schema, 'aggregator_feed', 'fid');
break;
}
}
return $schema;
}
}

View File

@ -1,38 +0,0 @@
<?php
namespace Drupal\aggregator;
use Drupal\Core\Entity\EntityViewBuilder;
/**
* View builder handler for aggregator feed items.
*/
class ItemViewBuilder extends EntityViewBuilder {
/**
* {@inheritdoc}
*/
public function buildComponents(array &$build, array $entities, array $displays, $view_mode) {
parent::buildComponents($build, $entities, $displays, $view_mode);
foreach ($entities as $id => $entity) {
$bundle = $entity->bundle();
$display = $displays[$bundle];
// By default, the description field is exposed as a pseudo-field
// rendered in this function. However it can optionally be rendered
// directly using a field formatter. Skip rendering here if a field
// formatter type is set.
$component = $display->getComponent('description');
if ($component && !isset($component['type'])) {
$build[$id]['description'] = [
'#markup' => $entity->getDescription(),
'#allowed_tags' => _aggregator_allowed_tags(),
'#prefix' => '<div class="item-description">',
'#suffix' => '</div>',
];
}
}
}
}

View File

@ -1,153 +0,0 @@
<?php
namespace Drupal\aggregator;
use Drupal\aggregator\Plugin\AggregatorPluginManager;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\Config\ConfigFactoryInterface;
use Psr\Log\LoggerInterface;
/**
* Defines an importer of aggregator items.
*/
class ItemsImporter implements ItemsImporterInterface {
/**
* The aggregator fetcher manager.
*
* @var \Drupal\aggregator\Plugin\AggregatorPluginManager
*/
protected $fetcherManager;
/**
* The aggregator processor manager.
*
* @var \Drupal\aggregator\Plugin\AggregatorPluginManager
*/
protected $processorManager;
/**
* The aggregator parser manager.
*
* @var \Drupal\aggregator\Plugin\AggregatorPluginManager
*/
protected $parserManager;
/**
* The aggregator.settings config object.
*
* @var \Drupal\Core\Config\Config
*/
protected $config;
/**
* A logger instance.
*
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* Constructs an Importer object.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
* @param \Drupal\aggregator\Plugin\AggregatorPluginManager $fetcher_manager
* The aggregator fetcher plugin manager.
* @param \Drupal\aggregator\Plugin\AggregatorPluginManager $parser_manager
* The aggregator parser plugin manager.
* @param \Drupal\aggregator\Plugin\AggregatorPluginManager $processor_manager
* The aggregator processor plugin manager.
* @param \Psr\Log\LoggerInterface $logger
* A logger instance.
*/
public function __construct(ConfigFactoryInterface $config_factory, AggregatorPluginManager $fetcher_manager, AggregatorPluginManager $parser_manager, AggregatorPluginManager $processor_manager, LoggerInterface $logger) {
$this->fetcherManager = $fetcher_manager;
$this->processorManager = $processor_manager;
$this->parserManager = $parser_manager;
$this->config = $config_factory->get('aggregator.settings');
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public function delete(FeedInterface $feed) {
foreach ($this->processorManager->getDefinitions() as $id => $definition) {
$this->processorManager->createInstance($id)->delete($feed);
}
}
/**
* {@inheritdoc}
*/
public function refresh(FeedInterface $feed) {
// Store feed URL to track changes.
$feed_url = $feed->getUrl();
// Fetch the feed.
try {
$success = $this->fetcherManager->createInstance($this->config->get('fetcher'))->fetch($feed);
}
catch (PluginException $e) {
$success = FALSE;
watchdog_exception('aggregator', $e);
}
// Store instances in an array so we don't have to instantiate new objects.
$processor_instances = [];
foreach ($this->config->get('processors') as $processor) {
try {
$processor_instances[$processor] = $this->processorManager->createInstance($processor);
}
catch (PluginException $e) {
watchdog_exception('aggregator', $e);
}
}
// We store the hash of feed data in the database. When refreshing a
// feed we compare stored hash and new hash calculated from downloaded
// data. If both are equal we say that feed is not updated.
$hash = $success ? hash('sha256', $feed->source_string) : '';
$has_new_content = $success && ($feed->getHash() != $hash);
if ($has_new_content) {
// Parse the feed.
try {
if ($this->parserManager->createInstance($this->config->get('parser'))->parse($feed)) {
if (!$feed->getWebsiteUrl()) {
$feed->setWebsiteUrl($feed->getUrl());
}
$feed->setHash($hash);
// Update feed with parsed data.
$feed->save();
// Log if feed URL has changed.
if ($feed->getUrl() != $feed_url) {
$this->logger->notice('Updated URL for feed %title to %url.', ['%title' => $feed->label(), '%url' => $feed->getUrl()]);
}
$this->logger->notice('There is new syndicated content from %site.', ['%site' => $feed->label()]);
// If there are items on the feed, let enabled processors process them.
if (!empty($feed->items)) {
foreach ($processor_instances as $instance) {
$instance->process($feed);
}
}
}
}
catch (PluginException $e) {
watchdog_exception('aggregator', $e);
}
}
// Processing is done, call postProcess on enabled processors.
foreach ($processor_instances as $instance) {
$instance->postProcess($feed);
}
return $has_new_content;
}
}

View File

@ -1,32 +0,0 @@
<?php
namespace Drupal\aggregator;
/**
* Provides an interface defining an aggregator items importer.
*/
interface ItemsImporterInterface {
/**
* Updates the feed items by triggering the import process.
*
* This process can be slow and lengthy because it relies on network
* operations. Calling it on performance critical paths should be avoided.
*
* @param \Drupal\aggregator\FeedInterface $feed
* The feed which items should be refreshed.
*
* @return bool
* TRUE if there is new content for the feed FALSE otherwise.
*/
public function refresh(FeedInterface $feed);
/**
* Deletes all imported items from a feed.
*
* @param \Drupal\aggregator\FeedInterface $feed
* The feed that associated items should be deleted from.
*/
public function delete(FeedInterface $feed);
}

View File

@ -1,53 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
/**
* Manages aggregator plugins.
*
* @see \Drupal\aggregator\Annotation\AggregatorParser
* @see \Drupal\aggregator\Annotation\AggregatorFetcher
* @see \Drupal\aggregator\Annotation\AggregatorProcessor
* @see \Drupal\aggregator\Plugin\AggregatorPluginSettingsBase
* @see \Drupal\aggregator\Plugin\FetcherInterface
* @see \Drupal\aggregator\Plugin\ProcessorInterface
* @see \Drupal\aggregator\Plugin\ParserInterface
* @see plugin_api
*/
class AggregatorPluginManager extends DefaultPluginManager {
/**
* Constructs an AggregatorPluginManager object.
*
* @param string $type
* The plugin type, for example fetcher.
* @param \Traversable $namespaces
* An object that implements \Traversable which contains the root paths
* keyed by the corresponding namespace to look for plugin implementations.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
* Cache backend instance to use.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
*/
public function __construct($type, \Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
$type_annotations = [
'fetcher' => 'Drupal\aggregator\Annotation\AggregatorFetcher',
'parser' => 'Drupal\aggregator\Annotation\AggregatorParser',
'processor' => 'Drupal\aggregator\Annotation\AggregatorProcessor',
];
$plugin_interfaces = [
'fetcher' => 'Drupal\aggregator\Plugin\FetcherInterface',
'parser' => 'Drupal\aggregator\Plugin\ParserInterface',
'processor' => 'Drupal\aggregator\Plugin\ProcessorInterface',
];
parent::__construct("Plugin/aggregator/$type", $namespaces, $module_handler, $plugin_interfaces[$type], $type_annotations[$type]);
$this->alterInfo('aggregator_' . $type . '_info');
$this->setCacheBackend($cache_backend, 'aggregator_' . $type . '_plugins');
}
}

View File

@ -1,45 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin;
use Drupal\Component\Plugin\ConfigurableInterface;
use Drupal\Component\Plugin\DependentPluginInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\Core\Plugin\PluginFormInterface;
/**
* Base class for aggregator plugins that implement settings forms.
*
* @see \Drupal\aggregator\Annotation\AggregatorParser
* @see \Drupal\aggregator\Annotation\AggregatorFetcher
* @see \Drupal\aggregator\Annotation\AggregatorProcessor
* @see \Drupal\aggregator\Plugin\AggregatorPluginManager
* @see \Drupal\aggregator\Plugin\FetcherInterface
* @see \Drupal\aggregator\Plugin\ProcessorInterface
* @see \Drupal\aggregator\Plugin\ParserInterface
* @see plugin_api
*/
abstract class AggregatorPluginSettingsBase extends PluginBase implements PluginFormInterface, ConfigurableInterface, DependentPluginInterface {
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [];
}
/**
* {@inheritdoc}
*/
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
return [];
}
}

View File

@ -1,176 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin\Block;
use Drupal\aggregator\FeedStorageInterface;
use Drupal\aggregator\ItemStorageInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides an 'Aggregator feed' block with the latest items from the feed.
*
* @Block(
* id = "aggregator_feed_block",
* admin_label = @Translation("Aggregator feed"),
* category = @Translation("Lists (Views)")
* )
*/
class AggregatorFeedBlock extends BlockBase implements ContainerFactoryPluginInterface {
/**
* The entity storage for feeds.
*
* @var \Drupal\aggregator\FeedStorageInterface
*/
protected $feedStorage;
/**
* The entity storage for items.
*
* @var \Drupal\aggregator\ItemStorageInterface
*/
protected $itemStorage;
/**
* Constructs an AggregatorFeedBlock object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\aggregator\FeedStorageInterface $feed_storage
* The entity storage for feeds.
* @param \Drupal\aggregator\ItemStorageInterface $item_storage
* The entity storage for feed items.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, FeedStorageInterface $feed_storage, ItemStorageInterface $item_storage) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->feedStorage = $feed_storage;
$this->itemStorage = $item_storage;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager')->getStorage('aggregator_feed'),
$container->get('entity_type.manager')->getStorage('aggregator_item')
);
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
// By default, the block will contain 10 feed items.
return [
'block_count' => 10,
'feed' => NULL,
];
}
/**
* {@inheritdoc}
*/
protected function blockAccess(AccountInterface $account) {
// Only grant access to users with the 'access news feeds' permission.
return AccessResult::allowedIfHasPermission($account, 'access news feeds');
}
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
$feeds = $this->feedStorage->loadMultiple();
$options = [];
foreach ($feeds as $feed) {
$options[$feed->id()] = $feed->label();
}
$form['feed'] = [
'#type' => 'select',
'#title' => $this->t('Select the feed that should be displayed'),
'#default_value' => $this->configuration['feed'],
'#options' => $options,
];
$range = range(2, 20);
$form['block_count'] = [
'#type' => 'select',
'#title' => $this->t('Number of news items in block'),
'#default_value' => $this->configuration['block_count'],
'#options' => array_combine($range, $range),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['block_count'] = $form_state->getValue('block_count');
$this->configuration['feed'] = $form_state->getValue('feed');
}
/**
* {@inheritdoc}
*/
public function build() {
// Load the selected feed.
if (!$feed = $this->feedStorage->load($this->configuration['feed'])) {
return [];
}
$result = $this->itemStorage->getQuery()
->accessCheck(TRUE)
->condition('fid', $feed->id())
->range(0, $this->configuration['block_count'])
->sort('timestamp', 'DESC')
->sort('iid', 'DESC')
->execute();
if ($result) {
// Only display the block if there are items to show.
$items = $this->itemStorage->loadMultiple($result);
$build['list'] = [
'#theme' => 'item_list',
'#items' => [],
];
foreach ($items as $item) {
$build['list']['#items'][$item->id()] = [
'#type' => 'link',
'#url' => $item->toUrl(),
'#title' => $item->label(),
];
}
$build['more_link'] = [
'#type' => 'more_link',
'#url' => $feed->toUrl(),
'#attributes' => ['title' => $this->t("View this feed's recent news.")],
];
return $build;
}
}
/**
* {@inheritdoc}
*/
public function getCacheTags() {
$cache_tags = parent::getCacheTags();
if ($feed = $this->feedStorage->load($this->configuration['feed'])) {
$cache_tags = Cache::mergeTags($cache_tags, $feed->getCacheTags());
}
return $cache_tags;
}
}

View File

@ -1,37 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin;
use Drupal\aggregator\FeedInterface;
/**
* Defines an interface for aggregator fetcher implementations.
*
* A fetcher downloads feed data to a Drupal site. The fetcher is called at the
* first of the three aggregation stages: first, data is downloaded by the
* active fetcher; second, it is converted to a common format by the active
* parser; and finally, it is passed to all active processors, which manipulate
* or store the data.
*
* @see \Drupal\aggregator\Annotation\AggregatorFetcher
* @see \Drupal\aggregator\Plugin\AggregatorPluginSettingsBase
* @see \Drupal\aggregator\Plugin\AggregatorPluginManager
* @see plugin_api
*/
interface FetcherInterface {
/**
* Downloads feed data.
*
* @param \Drupal\aggregator\FeedInterface $feed
* A feed object representing the resource to be downloaded.
* $feed->getUrl() contains the link to the feed.
* Download the data at the URL and expose it
* to other modules by attaching it to $feed->source_string.
*
* @return bool
* TRUE if fetching was successful, FALSE otherwise.
*/
public function fetch(FeedInterface $feed);
}

View File

@ -1,86 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Plugin implementation of the 'aggregator_title' formatter.
*
* @FieldFormatter(
* id = "aggregator_title",
* label = @Translation("Aggregator title"),
* description = @Translation("Formats an aggregator item or feed title with an optional link."),
* field_types = {
* "string"
* }
* )
*/
class AggregatorTitleFormatter extends FormatterBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
$options = parent::defaultSettings();
$options['display_as_link'] = TRUE;
return $options;
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$form = parent::settingsForm($form, $form_state);
$form['display_as_link'] = [
'#type' => 'checkbox',
'#title' => $this->t('Link to URL'),
'#default_value' => $this->getSetting('display_as_link'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
if ($items->getEntity()->getEntityTypeId() == 'aggregator_feed') {
$url_string = $items->getEntity()->getUrl();
}
else {
$url_string = $items->getEntity()->getLink();
}
foreach ($items as $delta => $item) {
if ($this->getSetting('display_as_link') && $url_string) {
$elements[$delta] = [
'#type' => 'link',
'#title' => $item->value,
'#url' => Url::fromUri($url_string),
];
}
else {
$elements[$delta] = ['#markup' => $item->value];
}
}
return $elements;
}
/**
* {@inheritdoc}
*/
public static function isApplicable(FieldDefinitionInterface $field_definition) {
return (($field_definition->getTargetEntityTypeId() === 'aggregator_item' || $field_definition->getTargetEntityTypeId() === 'aggregator_feed') && $field_definition->getName() === 'title');
}
}

View File

@ -1,39 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
/**
* Plugin implementation of the 'aggregator_xss' formatter.
*
* @FieldFormatter(
* id = "aggregator_xss",
* label = @Translation("Aggregator XSS"),
* description = @Translation("Filter output for aggregator items"),
* field_types = {
* "string",
* "string_long",
* }
* )
*/
class AggregatorXSSFormatter extends FormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
$elements[$delta] = [
'#type' => 'markup',
'#markup' => $item->value,
'#allowed_tags' => _aggregator_allowed_tags(),
];
}
return $elements;
}
}

View File

@ -1,52 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin;
use Drupal\aggregator\FeedInterface;
/**
* Defines an interface for aggregator parser implementations.
*
* A parser converts feed item data to a common format. The parser is called
* at the second of the three aggregation stages: first, data is downloaded
* by the active fetcher; second, it is converted to a common format by the
* active parser; and finally, it is passed to all active processors which
* manipulate or store the data.
*
* @see \Drupal\aggregator\Annotation\AggregatorParser
* @see \Drupal\aggregator\Plugin\AggregatorPluginSettingsBase
* @see \Drupal\aggregator\Plugin\AggregatorPluginManager
* @see plugin_api
*/
interface ParserInterface {
/**
* Parses feed data.
*
* @param \Drupal\aggregator\FeedInterface $feed
* An object describing the resource to be parsed.
* $feed->source_string->value contains the raw feed data. Parse the data
* and add the following properties to the $feed object:
* - description: The human-readable description of the feed.
* - link: A full URL that directly relates to the feed.
* - image: An image URL used to display an image of the feed.
* - etag: An entity tag from the HTTP header used for cache validation to
* determine if the content has been changed.
* - modified: The UNIX timestamp when the feed was last modified.
* - items: An array of feed items. The common format for a single feed item
* is an associative array containing:
* - title: The human-readable title of the feed item.
* - description: The full body text of the item or a summary.
* - timestamp: The UNIX timestamp when the feed item was last published.
* - author: The author of the feed item.
* - guid: The global unique identifier (GUID) string that uniquely
* identifies the item. If not available, the link is used to identify
* the item.
* - link: A full URL to the individual feed item.
*
* @return bool
* TRUE if parsing was successful, FALSE otherwise.
*/
public function parse(FeedInterface $feed);
}

View File

@ -1,59 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin;
use Drupal\aggregator\FeedInterface;
/**
* Defines an interface for aggregator processor implementations.
*
* A processor acts on parsed feed data. Active processors are called at the
* third and last of the aggregation stages: first, data is downloaded by the
* active fetcher; second, it is converted to a common format by the active
* parser; and finally, it is passed to all active processors that manipulate or
* store the data.
*
* @see \Drupal\aggregator\Annotation\AggregatorProcessor
* @see \Drupal\aggregator\Plugin\AggregatorPluginSettingsBase
* @see \Drupal\aggregator\Plugin\AggregatorPluginManager
* @see plugin_api
*/
interface ProcessorInterface {
/**
* Processes feed data.
*
* @param \Drupal\aggregator\FeedInterface $feed
* A feed object representing the resource to be processed.
* $feed->items contains an array of feed items downloaded and parsed at the
* parsing stage. See \Drupal\aggregator\Plugin\FetcherInterface::parse()
* for the basic format of a single item in the $feed->items array.
* For the exact format refer to the particular parser in use.
*/
public function process(FeedInterface $feed);
/**
* Refreshes feed information.
*
* Called after the processing of the feed is completed by all selected
* processors.
*
* @param \Drupal\aggregator\FeedInterface $feed
* Object describing feed.
*
* @see aggregator_refresh()
*/
public function postProcess(FeedInterface $feed);
/**
* Deletes stored feed data.
*
* Called by aggregator if either a feed is deleted or a user clicks on
* "delete items".
*
* @param \Drupal\aggregator\FeedInterface $feed
* The $feed object whose items are being deleted.
*/
public function delete(FeedInterface $feed);
}

View File

@ -1,28 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin\QueueWorker;
use Drupal\aggregator\FeedInterface;
use Drupal\Core\Queue\QueueWorkerBase;
/**
* Updates a feed's items.
*
* @QueueWorker(
* id = "aggregator_feeds",
* title = @Translation("Aggregator refresh"),
* cron = {"time" = 60}
* )
*/
class AggregatorRefresh extends QueueWorkerBase {
/**
* {@inheritdoc}
*/
public function processItem($data) {
if ($data instanceof FeedInterface) {
$data->refreshItems();
}
}
}

View File

@ -1,19 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin\Validation\Constraint;
use Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldConstraint;
/**
* Supports validating feed titles.
*
* @Constraint(
* id = "FeedTitle",
* label = @Translation("Feed title", context = "Validation")
* )
*/
class FeedTitleConstraint extends UniqueFieldConstraint {
public $message = 'A feed named %value already exists. Enter a unique title.';
}

View File

@ -1,19 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin\Validation\Constraint;
use Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldConstraint;
/**
* Supports validating feed URLs.
*
* @Constraint(
* id = "FeedUrl",
* label = @Translation("Feed URL", context = "Validation")
* )
*/
class FeedUrlConstraint extends UniqueFieldConstraint {
public $message = 'A feed with this URL %value already exists. Enter a unique URL.';
}

View File

@ -1,135 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin\aggregator\fetcher;
use Drupal\aggregator\Plugin\FetcherInterface;
use Drupal\aggregator\FeedInterface;
use Drupal\Component\Datetime\DateTimePlus;
use Drupal\Core\Http\ClientFactory;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use GuzzleHttp\Exception\TransferException;
use GuzzleHttp\Psr7\Request;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines a default fetcher implementation.
*
* Uses the http_client service to download the feed.
*
* @AggregatorFetcher(
* id = "aggregator",
* title = @Translation("Default fetcher"),
* description = @Translation("Downloads data from a URL using Drupal's HTTP request handler.")
* )
*/
class DefaultFetcher implements FetcherInterface, ContainerFactoryPluginInterface {
/**
* The HTTP client to fetch the feed data with.
*
* @var \Drupal\Core\Http\ClientFactory
*/
protected $httpClientFactory;
/**
* A logger instance.
*
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* The messenger.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* Constructs a DefaultFetcher object.
*
* @param \Drupal\Core\Http\ClientFactory $http_client_factory
* A Guzzle client object.
* @param \Psr\Log\LoggerInterface $logger
* A logger instance.
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger.
*/
public function __construct(ClientFactory $http_client_factory, LoggerInterface $logger, MessengerInterface $messenger) {
$this->httpClientFactory = $http_client_factory;
$this->logger = $logger;
$this->messenger = $messenger;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$container->get('http_client_factory'),
$container->get('logger.factory')->get('aggregator'),
$container->get('messenger')
);
}
/**
* {@inheritdoc}
*/
public function fetch(FeedInterface $feed) {
$request = new Request('GET', $feed->getUrl());
$feed->source_string = FALSE;
// Generate conditional GET headers.
if ($feed->getEtag()) {
$request = $request->withAddedHeader('If-None-Match', $feed->getEtag());
}
if ($feed->getLastModified()) {
$request = $request->withAddedHeader('If-Modified-Since', gmdate(DateTimePlus::RFC7231, $feed->getLastModified()));
}
try {
/** @var \Psr\Http\Message\UriInterface $actual_uri */
$actual_uri = NULL;
$response = $this->httpClientFactory->fromOptions([
'allow_redirects' => [
'on_redirect' => function (RequestInterface $request, ResponseInterface $response, UriInterface $uri) use (&$actual_uri) {
$actual_uri = (string) $uri;
},
],
])->send($request);
// In case of a 304 Not Modified, there is no new content, so return
// FALSE.
if ($response->getStatusCode() == 304) {
return FALSE;
}
$feed->source_string = (string) $response->getBody();
if ($response->hasHeader('ETag')) {
$feed->setEtag($response->getHeaderLine('ETag'));
}
if ($response->hasHeader('Last-Modified')) {
$feed->setLastModified(strtotime($response->getHeaderLine('Last-Modified')));
}
$feed->http_headers = $response->getHeaders();
// Update the feed URL in case of a 301 redirect.
if ($actual_uri && $actual_uri !== $feed->getUrl()) {
$feed->setUrl($actual_uri);
}
return TRUE;
}
catch (TransferException $e) {
$this->logger->warning('The feed from %site seems to be broken because of error "%error".', ['%site' => $feed->label(), '%error' => $e->getMessage()]);
$this->messenger->addWarning(t('The feed from %site seems to be broken because of error "%error".', ['%site' => $feed->label(), '%error' => $e->getMessage()]));
return FALSE;
}
}
}

View File

@ -1,72 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin\aggregator\parser;
use Drupal\aggregator\Plugin\ParserInterface;
use Drupal\aggregator\FeedInterface;
use Drupal\Core\Messenger\MessengerTrait;
use Laminas\Feed\Reader\Reader;
use Laminas\Feed\Reader\Exception\ExceptionInterface;
/**
* Defines a default parser implementation.
*
* Parses RSS, Atom and RDF feeds.
*
* @AggregatorParser(
* id = "aggregator",
* title = @Translation("Default parser"),
* description = @Translation("Default parser for RSS, Atom and RDF feeds.")
* )
*/
class DefaultParser implements ParserInterface {
use MessengerTrait;
/**
* {@inheritdoc}
*/
public function parse(FeedInterface $feed) {
// Set our bridge extension manager to Laminas Feed.
Reader::setExtensionManager(\Drupal::service('feed.bridge.reader'));
try {
$channel = Reader::importString($feed->source_string);
}
catch (ExceptionInterface $e) {
watchdog_exception('aggregator', $e);
$this->messenger()->addError(t('The feed from %site seems to be broken because of error "%error".', ['%site' => $feed->label(), '%error' => $e->getMessage()]));
return FALSE;
}
$feed->setWebsiteUrl($channel->getLink());
$feed->setDescription($channel->getDescription());
if ($image = $channel->getImage()) {
$feed->setImage($image['uri']);
}
// Initialize items array.
$feed->items = [];
foreach ($channel as $item) {
// Reset the parsed item.
$parsed_item = [];
// Move the values to an array as expected by processors.
$parsed_item['title'] = $item->getTitle();
$parsed_item['guid'] = $item->getId();
$parsed_item['link'] = $item->getLink();
$parsed_item['description'] = $item->getDescription();
$parsed_item['author'] = '';
if ($author = $item->getAuthor()) {
$parsed_item['author'] = $author['name'];
}
$parsed_item['timestamp'] = '';
if ($date = $item->getDateModified()) {
$parsed_item['timestamp'] = $date->getTimestamp();
}
// Store on $feed object. This is where processors will look for parsed items.
$feed->items[] = $parsed_item;
}
return TRUE;
}
}

View File

@ -1,291 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin\aggregator\processor;
use Drupal\aggregator\Entity\Item;
use Drupal\aggregator\FeedInterface;
use Drupal\aggregator\FeedStorageInterface;
use Drupal\aggregator\ItemStorageInterface;
use Drupal\aggregator\Plugin\AggregatorPluginSettingsBase;
use Drupal\aggregator\Plugin\ProcessorInterface;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Form\ConfigFormBaseTrait;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines a default processor implementation.
*
* Creates lightweight records from feed items.
*
* @AggregatorProcessor(
* id = "aggregator",
* title = @Translation("Default processor"),
* description = @Translation("Creates lightweight records from feed items.")
* )
*/
class DefaultProcessor extends AggregatorPluginSettingsBase implements ProcessorInterface, ContainerFactoryPluginInterface {
use ConfigFormBaseTrait;
/**
* Contains the configuration object factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* The entity storage for items.
*
* @var \Drupal\aggregator\ItemStorageInterface
*/
protected $itemStorage;
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* The messenger.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* 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.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config
* The configuration factory object.
* @param \Drupal\aggregator\ItemStorageInterface $item_storage
* The entity storage for feed items.
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
* The date formatter service.
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigFactoryInterface $config, ItemStorageInterface $item_storage, DateFormatterInterface $date_formatter, MessengerInterface $messenger) {
$this->configFactory = $config;
$this->itemStorage = $item_storage;
$this->dateFormatter = $date_formatter;
$this->messenger = $messenger;
// @todo Refactor aggregator plugins to ConfigEntity so merging
// the configuration here is not needed.
parent::__construct($configuration + $this->getConfiguration(), $plugin_id, $plugin_definition);
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('config.factory'),
$container->get('entity_type.manager')->getStorage('aggregator_item'),
$container->get('date.formatter'),
$container->get('messenger')
);
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return ['aggregator.settings'];
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$config = $this->config('aggregator.settings');
$processors = $config->get('processors');
$info = $this->getPluginDefinition();
$counts = [3, 5, 10, 15, 20, 25];
$items = array_map(function ($count) {
return $this->formatPlural($count, '1 item', '@count items');
}, array_combine($counts, $counts));
$intervals = [3600, 10800, 21600, 32400, 43200, 86400, 172800, 259200, 604800, 1209600, 2419200, 4838400, 9676800];
$period = array_map([$this->dateFormatter, 'formatInterval'], array_combine($intervals, $intervals));
$period[FeedStorageInterface::CLEAR_NEVER] = t('Never');
$form['processors'][$info['id']] = [];
// Only wrap into details if there is a basic configuration.
if (isset($form['basic_conf'])) {
$form['processors'][$info['id']] = [
'#type' => 'details',
'#title' => t('Default processor settings'),
'#description' => $info['description'],
'#open' => in_array($info['id'], $processors),
];
}
$form['processors'][$info['id']]['aggregator_summary_items'] = [
'#type' => 'select',
'#title' => t('Number of items shown in listing pages'),
'#default_value' => $config->get('source.list_max'),
'#empty_value' => 0,
'#options' => $items,
];
$form['processors'][$info['id']]['aggregator_clear'] = [
'#type' => 'select',
'#title' => t('Discard items older than'),
'#default_value' => $config->get('items.expire'),
'#options' => $period,
'#description' => t('Requires a correctly configured <a href=":cron">cron maintenance task</a>.', [':cron' => Url::fromRoute('system.status')->toString()]),
];
$lengths = [0, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000];
$options = array_map(function ($length) {
return ($length == 0) ? t('Unlimited') : $this->formatPlural($length, '1 character', '@count characters');
}, array_combine($lengths, $lengths));
$form['processors'][$info['id']]['aggregator_teaser_length'] = [
'#type' => 'select',
'#title' => t('Length of trimmed description'),
'#default_value' => $config->get('items.teaser_length'),
'#options' => $options,
'#description' => t('The maximum number of characters used in the trimmed version of content.'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$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');
// @todo Refactor aggregator plugins to ConfigEntity so this is not needed.
$this->setConfiguration($this->configuration);
}
/**
* {@inheritdoc}
*/
public function process(FeedInterface $feed) {
if (!is_array($feed->items)) {
return;
}
foreach ($feed->items as $item) {
// @todo The default entity view builder always returns an empty
// 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 = ['fid' => $feed->id(), 'guid' => $item['guid']];
}
elseif ($item['link'] && $item['link'] != $feed->link && $item['link'] != $feed->url) {
$values = ['fid' => $feed->id(), 'link' => $item['link']];
}
else {
$values = ['fid' => $feed->id(), 'title' => $item['title']];
}
// Try to load an existing entry.
if ($entry = $this->itemStorage->loadByProperties($values)) {
$entry = reset($entry);
}
else {
$entry = Item::create(['langcode' => $feed->language()->getId()]);
}
if ($item['timestamp']) {
$entry->setPostedTime($item['timestamp']);
}
// Make sure the item title and author fit in the 255 varchar column.
$entry->setTitle(Unicode::truncate($item['title'], 255, TRUE, TRUE));
$entry->setAuthor(Unicode::truncate($item['author'], 255, TRUE, TRUE));
$entry->setFeedId($feed->id());
$entry->setLink($item['link']);
$entry->setGuid($item['guid']);
$description = '';
if (!empty($item['description'])) {
$description = $item['description'];
}
$entry->setDescription($description);
$entry->save();
}
}
/**
* {@inheritdoc}
*/
public function delete(FeedInterface $feed) {
if ($items = $this->itemStorage->loadByFeed($feed->id())) {
$this->itemStorage->delete($items);
}
// @todo This should be moved out to caller with a different message maybe.
$this->messenger->addStatus(t('The news items from %site have been deleted.', ['%site' => $feed->label()]));
}
/**
* Implements \Drupal\aggregator\Plugin\ProcessorInterface::postProcess().
*
* Expires items from a feed depending on expiration settings.
*/
public function postProcess(FeedInterface $feed) {
$aggregator_clear = $this->configuration['items']['expire'];
if ($aggregator_clear != FeedStorageInterface::CLEAR_NEVER) {
// Delete all items that are older than flush item timer.
$age = REQUEST_TIME - $aggregator_clear;
$result = $this->itemStorage->getQuery()
->accessCheck(FALSE)
->condition('fid', $feed->id())
->condition('timestamp', $age, '<')
->execute();
if ($result) {
$entities = $this->itemStorage->loadMultiple($result);
$this->itemStorage->delete($entities);
}
}
}
/**
* {@inheritdoc}
*/
public function getConfiguration() {
return $this->configFactory->get('aggregator.settings')->get();
}
/**
* {@inheritdoc}
*/
public function setConfiguration(array $configuration) {
$config = $this->config('aggregator.settings');
foreach ($configuration as $key => $value) {
$config->set($key, $value);
}
$config->save();
}
}

View File

@ -1,61 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin\migrate\source;
use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase;
/**
* Drupal 6/7 feed source from database.
*
* For available configuration keys, refer to the parent classes.
*
* @see \Drupal\migrate\Plugin\migrate\source\SqlBase
* @see \Drupal\migrate\Plugin\migrate\source\SourcePluginBase
*
* @MigrateSource(
* id = "aggregator_feed",
* source_module = "aggregator"
* )
*/
class AggregatorFeed extends DrupalSqlBase {
/**
* {@inheritdoc}
*/
public function query() {
return $this->select('aggregator_feed', 'af')
->fields('af');
}
/**
* {@inheritdoc}
*/
public function fields() {
$fields = [
'fid' => $this->t('The feed ID.'),
'title' => $this->t('Title of the feed.'),
'url' => $this->t('URL to the feed.'),
'refresh' => $this->t('Refresh frequency in seconds.'),
'checked' => $this->t('Last-checked unix timestamp.'),
'link' => $this->t('Parent website of the feed.'),
'description' => $this->t("Parent website's description of the feed."),
'image' => $this->t('An image representing the feed.'),
'etag' => $this->t('Entity tag HTTP response header.'),
'modified' => $this->t('When the feed was last modified.'),
'block' => $this->t("Number of items to display in the feed's block."),
];
if ($this->getModuleSchemaVersion('system') >= 7000) {
$fields['queued'] = $this->t('Time when this feed was queued for refresh, 0 if not queued.');
}
return $fields;
}
/**
* {@inheritdoc}
*/
public function getIds() {
$ids['fid']['type'] = 'integer';
return $ids;
}
}

View File

@ -1,55 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin\migrate\source;
use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase;
/**
* Drupal 6/7 aggregator item source from database.
*
* For available configuration keys, refer to the parent classes.
*
* @see \Drupal\migrate\Plugin\migrate\source\SqlBase
* @see \Drupal\migrate\Plugin\migrate\source\SourcePluginBase
*
* @MigrateSource(
* id = "aggregator_item",
* source_module = "aggregator"
* )
*/
class AggregatorItem extends DrupalSqlBase {
/**
* {@inheritdoc}
*/
public function query() {
return $this->select('aggregator_item', 'ai')
->fields('ai')
->orderBy('ai.iid');
}
/**
* {@inheritdoc}
*/
public function fields() {
return [
'iid' => $this->t('Primary Key: Unique ID for feed item.'),
'fid' => $this->t('The {aggregator_feed}.fid to which this item belongs.'),
'title' => $this->t('Title of the feed item.'),
'link' => $this->t('Link to the feed item.'),
'author' => $this->t('Author of the feed item.'),
'description' => $this->t('Body of the feed item.'),
'timestamp' => $this->t('Post date of feed item, as a Unix timestamp.'),
'guid' => $this->t('Unique identifier for the feed item.'),
];
}
/**
* {@inheritdoc}
*/
public function getIds() {
$ids['iid']['type'] = 'integer';
return $ids;
}
}

View File

@ -1,62 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin\views\argument;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\views\Plugin\views\argument\NumericArgument;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Argument handler to accept an aggregator feed id.
*
* @ingroup views_argument_handlers
*
* @ViewsArgument("aggregator_fid")
*/
class Fid extends NumericArgument {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a \Drupal\aggregator\Plugin\views\argument\Fid object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container->get('entity_type.manager'));
}
/**
* {@inheritdoc}
*/
public function titleQuery() {
$titles = [];
$feeds = $this->entityTypeManager->getStorage('aggregator_feed')->loadMultiple($this->value);
foreach ($feeds as $feed) {
$titles[] = $feed->label();
}
return $titles;
}
}

View File

@ -1,67 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin\views\argument;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\views\Plugin\views\argument\NumericArgument;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Argument handler to accept an aggregator item id.
*
* @ingroup views_argument_handlers
*
* @ViewsArgument("aggregator_iid")
*/
class Iid extends NumericArgument {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a \Drupal\aggregator\Plugin\views\argument\Iid object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager')
);
}
/**
* {@inheritdoc}
*/
public function titleQuery() {
$titles = [];
$items = $this->entityTypeManager->getStorage('aggregator_item')->loadMultiple($this->value);
foreach ($items as $feed) {
$titles[] = $feed->label();
}
return $titles;
}
}

View File

@ -1,79 +0,0 @@
<?php
namespace Drupal\aggregator\Plugin\views\row;
use Drupal\views\Plugin\views\row\RssPluginBase;
/**
* Defines a row plugin which loads an aggregator item and renders as RSS.
*
* @ViewsRow(
* id = "aggregator_rss",
* theme = "views_view_row_rss",
* title = @Translation("Aggregator item"),
* help = @Translation("Display the aggregator item using the data from the original source."),
* base = {"aggregator_item"},
* display_types = {"feed"}
* )
*/
class Rss extends RssPluginBase {
/**
* The table the aggregator item is using for storage.
*
* @var string
*/
public $base_table = 'aggregator_item';
/**
* The actual field which is used to identify an aggregator item.
*
* @var string
*/
public $base_field = 'iid';
/**
* {@inheritdoc}
*/
protected $entityTypeId = 'aggregator_item';
/**
* {@inheritdoc}
*/
public function render($row) {
$entity = $row->_entity;
$item = new \stdClass();
foreach ($entity as $name => $field) {
$item->{$name} = $field->value;
}
$item->elements = [
[
'key' => 'pubDate',
// views_view_row_rss takes care about the escaping.
'value' => gmdate('r', $entity->timestamp->value),
],
[
'key' => 'dc:creator',
// views_view_row_rss takes care about the escaping.
'value' => $entity->author->value,
],
[
'key' => 'guid',
// views_view_row_rss takes care about the escaping.
'value' => $entity->guid->value,
'attributes' => ['isPermaLink' => 'false'],
],
];
$build = [
'#theme' => $this->themeFunctions(),
'#view' => $this->view,
'#options' => $this->options,
'#row' => $item,
];
return $build;
}
}

View File

@ -1,130 +0,0 @@
<?php
namespace Drupal\aggregator;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Laminas\Feed\Reader\ExtensionManagerInterface as ReaderManagerInterface;
use Laminas\Feed\Writer\ExtensionManagerInterface as WriterManagerInterface;
/**
* Defines a bridge between the Laminas service manager to Symfony container.
*/
class ZfExtensionManagerSfContainer implements ReaderManagerInterface, WriterManagerInterface, ContainerAwareInterface {
/**
* A map of characters to be replaced through strtr.
*
* This property is based on Laminas service manager.
*
* @link https://github.com/laminas/laminas-servicemanager for the canonical source repository
* @copyright Copyright (c) 2019, Laminas Foundation. (https://getlaminas.org/)
* @license https://github.com/laminas/laminas-servicemanager/blob/master/LICENSE.md
*
* @var array
*
* @see \Drupal\aggregator\ZfExtensionManagerSfContainer::canonicalizeName().
* @see https://github.com/laminas/laminas-servicemanager/blob/2.7.11/src/ServiceManager.php#L114
*/
protected $canonicalNamesReplacements = ['-' => '', '_' => '', ' ' => '', '\\' => '', '/' => ''];
/**
* The prefix to be used when retrieving plugins from the container.
*
* @var string
*/
protected $prefix = '';
/**
* The service container.
*
* @var \Symfony\Component\DependencyInjection\ContainerInterface
*/
protected $container;
/**
* A local cache of computed canonical names.
*
* @var string[]
*/
protected $canonicalNames;
/**
* @var \Laminas\Feed\Reader\ExtensionManagerInterface|\Laminas\Feed\Writer\ExtensionManagerInterface
*/
protected $standalone;
/**
* Constructs a ZfExtensionManagerSfContainer object.
*
* @param string $prefix
* The prefix to be used when retrieving plugins from the container.
*/
public function __construct($prefix = '') {
$this->prefix = $prefix;
}
/**
* {@inheritdoc}
*/
public function get($extension) {
if ($this->standalone && $this->standalone->has($extension)) {
return $this->standalone->get($extension);
}
return $this->container->get($this->prefix . $this->canonicalizeName($extension));
}
/**
* {@inheritdoc}
*/
public function has($extension) {
if ($this->standalone && $this->standalone->has($extension)) {
return TRUE;
}
return $this->container->has($this->prefix . $this->canonicalizeName($extension));
}
/**
* Canonicalize the extension name to a service name.
*
* This method is based on Laminas service manager.
*
* @link https://github.com/laminas/laminas-servicemanager for the canonical source repository
* @copyright Copyright (c) 2019, Laminas Foundation. (https://getlaminas.org/)
* @license https://github.com/laminas/laminas-servicemanager/blob/master/LICENSE.md
*
* @param string $name
* The extension name.
*
* @return string
* The service name, without the prefix.
*
* @see https://github.com/laminas/laminas-servicemanager/blob/2.7.11/src/ServiceManager.php#L900
*/
protected function canonicalizeName($name) {
if (isset($this->canonicalNames[$name])) {
return $this->canonicalNames[$name];
}
// This is just for performance instead of using str_replace().
return $this->canonicalNames[$name] = strtolower(strtr($name, $this->canonicalNamesReplacements));
}
/**
* {@inheritdoc}
*/
public function setContainer(ContainerInterface $container = NULL) {
$this->container = $container;
}
/**
* @param $class
* The class to set as standalone.
*/
public function setStandalone($class) {
if (!is_subclass_of($class, ReaderManagerInterface::class) && !is_subclass_of($class, WriterManagerInterface::class)) {
throw new \RuntimeException("$class must implement Laminas\Feed\Reader\ExtensionManagerInterface or Laminas\Feed\Writer\ExtensionManagerInterface");
}
$this->standalone = new $class();
}
}

View File

@ -1,33 +0,0 @@
{#
/**
* @file
* Default theme implementation to present an aggregator feed.
*
* The contents are rendered above feed listings when browsing source feeds.
* For example, "example.com/aggregator/sources/1".
*
* Available variables:
* - title: (optional) Title of the feed item.
* - content: All field items. Use {{ content }} to print them all,
* or print a subset such as {{ content.field_example }}. Use
* {{ content|without('field_example') }} to temporarily suppress the printing
* of a given element.
* - title_attributes: Same as attributes, except applied to the main title
* tag that appears in the template.
* - title_prefix: Additional output populated by modules, intended to be
* displayed in front of the main title tag that appears in the template.
* - title_suffix: Additional output populated by modules, intended to be
* displayed after the main title tag that appears in the template.
*
* @see template_preprocess_aggregator_feed()
*
* @ingroup themeable
*/
#}
{{ title_prefix }}
{% if title and not full %}
<h2{{ title_attributes }}>{{ title }}</h2>
{% endif %}
{{ title_suffix }}
{{ content }}

View File

@ -1,33 +0,0 @@
{#
/**
* @file
* Default theme implementation to present a feed item in an aggregator page.
*
* Available variables:
* - url: URL to the originating feed item.
* - title: (optional) Title of the feed item.
* - content: All field items. Use {{ content }} to print them all,
* or print a subset such as {{ content.field_example }}. Use
* {{ content|without('field_example') }} to temporarily suppress the printing
* of a given element.
* - attributes: HTML attributes for the wrapper.
* - title_prefix: Additional output populated by modules, intended to be
* displayed in front of the main title tag that appears in the template.
* - title_suffix: Additional output populated by modules, intended to be
* displayed after the main title tag that appears in the template.
*
* @see template_preprocess_aggregator_item()
*
* @ingroup themeable
*/
#}
<article{{ attributes }}>
{{ title_prefix }}
{% if title %}
<h3>
<a href="{{ url }}">{{ title }}</a>
</h3>
{% endif %}
{{ title_suffix }}
{{ content }}
</article>

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -1,5 +0,0 @@
name: 'Aggregator configurable display module tests'
type: module
description: 'Support module for aggregator \Drupal\Core\Field\BaseFieldDefinition::setDisplayConfigurable() testing.'
package: Testing
version: VERSION

View File

@ -1,40 +0,0 @@
<?php
/**
* @file
* A module for testing making aggregator_feed base fields' displays
* configurable.
*/
use Drupal\Core\Entity\EntityTypeInterface;
/**
* Implements hook_entity_base_field_info_alter().
*/
function aggregator_display_configurable_test_entity_base_field_info_alter(&$base_field_definitions, EntityTypeInterface $entity_type) {
/** @var \Drupal\Core\Field\BaseFieldDefinition[] $base_field_definitions */
if ($entity_type->id() === 'aggregator_feed') {
$base_field_definitions['title']->setDisplayConfigurable('view', TRUE);
$base_field_definitions['description']->setDisplayConfigurable('view', TRUE);
$base_field_definitions['image']->setDisplayConfigurable('view', TRUE);
}
if ($entity_type->id() === 'aggregator_item') {
$base_field_definitions['title']->setDisplayConfigurable('view', TRUE);
$options = [
'type' => 'text_default',
'label' => 'above',
];
$base_field_definitions['title']->setDisplayOptions('view', $options);
}
}
/**
* Implements hook_entity_type_build().
*/
function aggregator_display_configurable_test_entity_type_build(array &$entity_types) {
// Allow skipping of extra preprocessing for configurable display.
$entity_types['aggregator_feed']->set('enable_base_field_custom_preprocess_skipping', TRUE);
$entity_types['aggregator_item']->set('enable_base_field_custom_preprocess_skipping', TRUE);
}

View File

@ -1,5 +0,0 @@
name: 'Aggregator module tests'
type: module
description: 'Support module for aggregator related testing.'
package: Testing
version: VERSION

View File

@ -1,27 +0,0 @@
<?php
/**
* @file
* Helper module for the Aggregator tests.
*/
/**
* Implements hook_aggregator_fetcher_info_alter().
*/
function aggregator_test_aggregator_fetcher_info_alter(array &$info) {
$info['aggregator_test_fetcher']['definition_altered'] = TRUE;
}
/**
* Implements hook_aggregator_parser_info_alter().
*/
function aggregator_test_aggregator_parser_info_alter(array &$info) {
$info['aggregator_test_parser']['definition_altered'] = TRUE;
}
/**
* Implements hook_aggregator_processor_info_alter().
*/
function aggregator_test_aggregator_processor_info_alter(array &$info) {
$info['aggregator_test_processor']['definition_altered'] = TRUE;
}

View File

@ -1,17 +0,0 @@
aggregator_test.feed:
path: '/aggregator/test-feed/{use_last_modified}/{use_etag}'
defaults:
_controller: '\Drupal\aggregator_test\Controller\AggregatorTestRssController::testFeed'
_title: 'Test feed static last modified date'
use_last_modified: FALSE
use_etag: FALSE
requirements:
_access: 'TRUE'
aggregator_test.redirect:
path: '/aggregator/redirect'
defaults:
_controller: '\Drupal\aggregator_test\Controller\AggregatorTestRssController::testRedirect'
_title: 'Test feed with a redirect'
requirements:
_access: 'TRUE'

View File

@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Example Feed</title>
<link href="http://example.org/" />
<updated>2003-12-13T18:30:02Z</updated>
<author>
<name>John Doe</name>
</author>
<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
<entry>
<title>Atom-Powered Robots Run Amok</title>
<link href="http://example.org/2003/12/13/atom03" />
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
</entry>
<entry>
<title>We tried to stop them, but we failed.</title>
<link href="http://example.org/2003/12/14/atom03" />
<id>urn:uuid:1225c695-cfb8-4ebb-bbbb-80da344efa6a</id>
<updated>2003-12-14T16:30:02Z</updated>
<summary>Some other text.</summary>
</entry>
</feed>

View File

@ -1,62 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<rss version="0.91">
<channel>
<title>Example</title>
<link>http://example.com</link>
<description>Example updates</description>
<language>en-us</language>
<copyright>Copyright 2000, Example team.</copyright>
<managingEditor>editor@example.com</managingEditor>
<webMaster>webmaster@example.com</webMaster>
<image>
<title>Example</title>
<url>http://example.com/images/druplicon.png</url>
<link>http://example.com</link>
<width>88</width>
<height>100</height>
<description>Example updates</description>
</image>
<item>
<title>First example feed item title</title>
<link>http://example.com/example-turns-one</link>
<description>First example feed item description.</description>
</item>
<item>
<title>Second example feed item title. This title is extremely long so that it exceeds the 255 character limit for titles in feed item storage. In fact it's so long that this sentence isn't long enough so I'm rambling a bit to make it longer, nearly there now. Ah now it's long enough so I'll shut up.</title>
<link>http://example.com/example-turns-two</link>
<description>Second example feed item description.</description>
</item>
<item>
<title>Long link feed item title.</title>
<link>http://example.com/tomorrow/and/tomorrow/and/tomorrow/creeps/in/this/petty/pace/from/day/to/day/to/the/last/syllable/of/recorded/time/and/all/our/yesterdays/have/lighted/fools/the/way/to/dusty/death/out/out/brief/candle/life/is/but/a/walking/shadow/a/poor/player/that/struts/and/frets/his/hour/upon/the/stage/and/is/heard/no/more/it/is/a/tale/told/by/an/idiot/full/of/sound/and/fury/signifying/nothing</link>
<description>Long link feed item description.</description>
</item>
<item>
<title>Long author feed item title.</title>
<link>http://example.com/long/author</link>
<author>I wanted to get out and walk eastward toward the park through the soft twilight, but each time I tried to go I became entangled in some wild, strident argument which pulled me back, as if with ropes, into my chair. Yet high over the city our line of yellow windows must have contributed their share of human secrecy to the casual watcher in the darkening streets, and I was him too, looking up and wondering. I was within and without, simultaneously enchanted and repelled by the inexhaustible variety of life.</author>
<description>Long author feed item description.</description>
</item>
<item>
<title></title>
<link>http://example.com/empty/title</link>
<description>This is an item with an empty title.</description>
</item>
<item>
<title>Empty description feed item title.</title>
<link>http://example.com/empty/description</link>
<description></description>
</item>
<item>
<title>Empty link feed item title.</title>
<link></link>
<description>This is an item with an empty link.</description>
</item>
<item>
<title>Empty author feed item title.</title>
<link>http://example.com/empty/author</link>
<author></author>
<description>We've tested items with no author, but what about an empty author tag?</description>
</item>
</channel>
</rss>

View File

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<rss version="0.91">
<channel>
<title>Example with Entities</title>
<link>http://example.com</link>
<description>Example RSS Feed With HTML Entities in Title</description>
<language>en-us</language>
<item>
<title>Quote&quot; Amp&amp;</title>
<link>http://example.com/example-turns-one</link>
<description>Some text.</description>
</item>
</channel>
</rss>

View File

@ -1,13 +0,0 @@
# Schema for the configuration files of the Aggregator Test module.
aggregator_test.settings:
type: config_object
label: 'Aggregator test settings'
mapping:
items:
type: mapping
label: 'Items'
mapping:
dummy_length:
type: integer
label: 'Dummy length'

Some files were not shown because too many files have changed in this diff Show More