60a189936240703f61db2ac55e96f5e39b4dc70e
[yaffs-website] / web / core / modules / aggregator / src / Form / OpmlFeedAdd.php
1 <?php
2
3 namespace Drupal\aggregator\Form;
4
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;
12
13 /**
14  * Imports feeds from OPML.
15  *
16  * @internal
17  */
18 class OpmlFeedAdd extends FormBase {
19
20   /**
21    * The feed storage.
22    *
23    * @var \Drupal\aggregator\FeedStorageInterface
24    */
25   protected $feedStorage;
26
27   /**
28    * The HTTP client to fetch the feed data with.
29    *
30    * @var \GuzzleHttp\ClientInterface
31    */
32   protected $httpClient;
33
34   /**
35    * Constructs a database object.
36    *
37    * @param \Drupal\aggregator\FeedStorageInterface $feed_storage
38    *   The feed storage.
39    * @param \GuzzleHttp\ClientInterface $http_client
40    *   The Guzzle HTTP client.
41    */
42   public function __construct(FeedStorageInterface $feed_storage, ClientInterface $http_client) {
43     $this->feedStorage = $feed_storage;
44     $this->httpClient = $http_client;
45   }
46
47   /**
48    * {@inheritdoc}
49    */
50   public static function create(ContainerInterface $container) {
51     return new static(
52       $container->get('entity.manager')->getStorage('aggregator_feed'),
53       $container->get('http_client')
54     );
55   }
56
57   /**
58    * {@inheritdoc}
59    */
60   public function getFormId() {
61     return 'aggregator_opml_add';
62   }
63
64   /**
65    * {@inheritdoc}
66    */
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));
70
71     $form['upload'] = [
72       '#type' => 'file',
73       '#title' => $this->t('OPML File'),
74       '#description' => $this->t('Upload an OPML file containing a list of feeds to be imported.'),
75     ];
76     $form['remote'] = [
77       '#type' => 'url',
78       '#title' => $this->t('OPML Remote URL'),
79       '#maxlength' => 1024,
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.'),
81     ];
82     $form['refresh'] = [
83       '#type' => 'select',
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')]),
88     ];
89
90     $form['actions'] = ['#type' => 'actions'];
91     $form['actions']['submit'] = [
92       '#type' => 'submit',
93       '#value' => $this->t('Import'),
94     ];
95
96     return $form;
97   }
98
99   /**
100    * {@inheritdoc}
101    */
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.'));
107     }
108   }
109
110   /**
111    * {@inheritdoc}
112    */
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());
117     }
118     else {
119       // @todo Move this to a fetcher implementation.
120       try {
121         $response = $this->httpClient->get($form_state->getValue('remote'));
122         $data = (string) $response->getBody();
123       }
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()]));
127         return;
128       }
129     }
130
131     $feeds = $this->parseOpml($data);
132     if (empty($feeds)) {
133       drupal_set_message($this->t('No new feed has been added.'));
134       return;
135     }
136
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');
142         continue;
143       }
144
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']);
150       $ids = $query
151         ->condition($condition)
152         ->execute();
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');
157           continue 2;
158         }
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');
161           continue 2;
162         }
163       }
164
165       $new_feed = $this->feedStorage->create([
166         'title' => $feed['title'],
167         'url' => $feed['url'],
168         'refresh' => $form_state->getValue('refresh'),
169       ]);
170       $new_feed->save();
171     }
172
173     $form_state->setRedirect('aggregator.admin_overview');
174   }
175
176   /**
177    * Parses an OPML file.
178    *
179    * Feeds are recognized as <outline> elements with the attributes "text" and
180    * "xmlurl" set.
181    *
182    * @param string $opml
183    *   The complete contents of an OPML document.
184    *
185    * @return array
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
189    *   OPML documents do.
190    *
191    * @todo Move this to a parser in https://www.drupal.org/node/1963540.
192    */
193   protected function parseOpml($opml) {
194     $feeds = [];
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']];
203           }
204         }
205       }
206     }
207     xml_parser_free($xml_parser);
208
209     return $feeds;
210   }
211
212 }