3 namespace Drupal\aggregator\Form;
5 use Drupal\aggregator\FeedStorageInterface;
6 use Drupal\Component\Utility\UrlHelper;
7 use Drupal\Core\Form\FormBase;
8 use Drupal\Core\Form\FormStateInterface;
9 use Symfony\Component\DependencyInjection\ContainerInterface;
10 use GuzzleHttp\Exception\RequestException;
11 use GuzzleHttp\ClientInterface;
14 * Imports feeds from OPML.
18 class OpmlFeedAdd extends FormBase {
23 * @var \Drupal\aggregator\FeedStorageInterface
25 protected $feedStorage;
28 * The HTTP client to fetch the feed data with.
30 * @var \GuzzleHttp\ClientInterface
32 protected $httpClient;
35 * Constructs a database object.
37 * @param \Drupal\aggregator\FeedStorageInterface $feed_storage
39 * @param \GuzzleHttp\ClientInterface $http_client
40 * The Guzzle HTTP client.
42 public function __construct(FeedStorageInterface $feed_storage, ClientInterface $http_client) {
43 $this->feedStorage = $feed_storage;
44 $this->httpClient = $http_client;
50 public static function create(ContainerInterface $container) {
52 $container->get('entity.manager')->getStorage('aggregator_feed'),
53 $container->get('http_client')
60 public function getFormId() {
61 return 'aggregator_opml_add';
67 public function buildForm(array $form, FormStateInterface $form_state) {
68 $intervals = [900, 1800, 3600, 7200, 10800, 21600, 32400, 43200, 64800, 86400, 172800, 259200, 604800, 1209600, 2419200];
69 $period = array_map([\Drupal::service('date.formatter'), 'formatInterval'], array_combine($intervals, $intervals));
73 '#title' => $this->t('OPML File'),
74 '#description' => $this->t('Upload an OPML file containing a list of feeds to be imported.'),
78 '#title' => $this->t('OPML Remote URL'),
80 '#description' => $this->t('Enter the URL of an OPML file. This file will be downloaded and processed only once on submission of the form.'),
84 '#title' => $this->t('Update interval'),
85 '#default_value' => 3600,
86 '#options' => $period,
87 '#description' => $this->t('The length of time between feed updates. Requires a correctly configured <a href=":cron">cron maintenance task</a>.', [':cron' => $this->url('system.status')]),
90 $form['actions'] = ['#type' => 'actions'];
91 $form['actions']['submit'] = [
93 '#value' => $this->t('Import'),
102 public function validateForm(array &$form, FormStateInterface $form_state) {
103 // If both fields are empty or filled, cancel.
104 $all_files = $this->getRequest()->files->get('files', []);
105 if ($form_state->isValueEmpty('remote') == empty($all_files['upload'])) {
106 $form_state->setErrorByName('remote', $this->t('<em>Either</em> upload a file or enter a URL.'));
113 public function submitForm(array &$form, FormStateInterface $form_state) {
114 $validators = ['file_validate_extensions' => ['opml xml']];
115 if ($file = file_save_upload('upload', $validators, FALSE, 0)) {
116 $data = file_get_contents($file->getFileUri());
119 // @todo Move this to a fetcher implementation.
121 $response = $this->httpClient->get($form_state->getValue('remote'));
122 $data = (string) $response->getBody();
124 catch (RequestException $e) {
125 $this->logger('aggregator')->warning('Failed to download OPML file due to "%error".', ['%error' => $e->getMessage()]);
126 drupal_set_message($this->t('Failed to download OPML file due to "%error".', ['%error' => $e->getMessage()]));
131 $feeds = $this->parseOpml($data);
133 drupal_set_message($this->t('No new feed has been added.'));
137 // @todo Move this functionality to a processor.
138 foreach ($feeds as $feed) {
139 // Ensure URL is valid.
140 if (!UrlHelper::isValid($feed['url'], TRUE)) {
141 drupal_set_message($this->t('The URL %url is invalid.', ['%url' => $feed['url']]), 'warning');
145 // Check for duplicate titles or URLs.
146 $query = $this->feedStorage->getQuery();
147 $condition = $query->orConditionGroup()
148 ->condition('title', $feed['title'])
149 ->condition('url', $feed['url']);
151 ->condition($condition)
153 $result = $this->feedStorage->loadMultiple($ids);
154 foreach ($result as $old) {
155 if (strcasecmp($old->label(), $feed['title']) == 0) {
156 drupal_set_message($this->t('A feed named %title already exists.', ['%title' => $old->label()]), 'warning');
159 if (strcasecmp($old->getUrl(), $feed['url']) == 0) {
160 drupal_set_message($this->t('A feed with the URL %url already exists.', ['%url' => $old->getUrl()]), 'warning');
165 $new_feed = $this->feedStorage->create([
166 'title' => $feed['title'],
167 'url' => $feed['url'],
168 'refresh' => $form_state->getValue('refresh'),
173 $form_state->setRedirect('aggregator.admin_overview');
177 * Parses an OPML file.
179 * Feeds are recognized as <outline> elements with the attributes "text" and
182 * @param string $opml
183 * The complete contents of an OPML document.
186 * An array of feeds, each an associative array with a "title" and a "url"
187 * element, or NULL if the OPML document failed to be parsed. An empty array
188 * will be returned if the document is valid but contains no feeds, as some
191 * @todo Move this to a parser in https://www.drupal.org/node/1963540.
193 protected function parseOpml($opml) {
195 $xml_parser = xml_parser_create();
196 xml_parser_set_option($xml_parser, XML_OPTION_TARGET_ENCODING, 'utf-8');
197 if (xml_parse_into_struct($xml_parser, $opml, $values)) {
198 foreach ($values as $entry) {
199 if ($entry['tag'] == 'OUTLINE' && isset($entry['attributes'])) {
200 $item = $entry['attributes'];
201 if (!empty($item['XMLURL']) && !empty($item['TEXT'])) {
202 $feeds[] = ['title' => $item['TEXT'], 'url' => $item['XMLURL']];
207 xml_parser_free($xml_parser);