Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / web / core / modules / views / src / Plugin / views / display / Feed.php
1 <?php
2
3 namespace Drupal\views\Plugin\views\display;
4
5 use Drupal\Core\Cache\CacheableMetadata;
6 use Drupal\Core\Cache\CacheableResponse;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\views\ViewExecutable;
9 use Drupal\views\Views;
10 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
11
12 /**
13  * The plugin that handles a feed, such as RSS or atom.
14  *
15  * @ingroup views_display_plugins
16  *
17  * @ViewsDisplay(
18  *   id = "feed",
19  *   title = @Translation("Feed"),
20  *   help = @Translation("Display the view as a feed, such as an RSS feed."),
21  *   uses_route = TRUE,
22  *   admin = @Translation("Feed"),
23  *   returns_response = TRUE
24  * )
25  */
26 class Feed extends PathPluginBase implements ResponseDisplayPluginInterface {
27
28   /**
29    * Whether the display allows the use of AJAX or not.
30    *
31    * @var bool
32    */
33   protected $ajaxEnabled = FALSE;
34
35   /**
36    * Whether the display allows the use of a pager or not.
37    *
38    * @var bool
39    */
40   protected $usesPager = FALSE;
41
42   /**
43    * {@inheritdoc}
44    */
45   public function getType() {
46     return 'feed';
47   }
48
49   /**
50    * {@inheritdoc}
51    */
52   public static function buildResponse($view_id, $display_id, array $args = []) {
53     $build = static::buildBasicRenderable($view_id, $display_id, $args);
54
55     // Set up an empty response, so for example RSS can set the proper
56     // Content-Type header.
57     $response = new CacheableResponse('', 200);
58     $build['#response'] = $response;
59
60     /** @var \Drupal\Core\Render\RendererInterface $renderer */
61     $renderer = \Drupal::service('renderer');
62
63     $output = (string) $renderer->renderRoot($build);
64
65     if (empty($output)) {
66       throw new NotFoundHttpException();
67     }
68
69     $response->setContent($output);
70     $cache_metadata = CacheableMetadata::createFromRenderArray($build);
71     $response->addCacheableDependency($cache_metadata);
72
73     return $response;
74   }
75
76
77   /**
78    * {@inheritdoc}
79    */
80   public function execute() {
81     parent::execute();
82
83     return $this->view->render();
84   }
85
86   /**
87    * {@inheritdoc}
88    */
89   public function preview() {
90     $output = $this->view->render();
91
92     if (!empty($this->view->live_preview)) {
93       $output = [
94         '#prefix' => '<pre>',
95         '#plain_text' => drupal_render_root($output),
96         '#suffix' => '</pre>',
97       ];
98     }
99
100     return $output;
101   }
102
103   /**
104    * {@inheritdoc}
105    */
106   public function render() {
107     $build = $this->view->style_plugin->render($this->view->result);
108
109     $this->applyDisplayCacheabilityMetadata($build);
110
111     return $build;
112   }
113
114   /**
115    * {@inheritdoc}
116    */
117   public function defaultableSections($section = NULL) {
118     $sections = parent::defaultableSections($section);
119
120     if (in_array($section, ['style', 'row'])) {
121       return FALSE;
122     }
123
124     // Tell views our sitename_title option belongs in the title section.
125     if ($section == 'title') {
126       $sections[] = 'sitename_title';
127     }
128     elseif (!$section) {
129       $sections['title'][] = 'sitename_title';
130     }
131     return $sections;
132   }
133
134   /**
135    * {@inheritdoc}
136    */
137   protected function defineOptions() {
138     $options = parent::defineOptions();
139
140     $options['displays'] = ['default' => []];
141
142     // Overrides for standard stuff.
143     $options['style']['contains']['type']['default'] = 'rss';
144     $options['style']['contains']['options']['default']  = ['description' => ''];
145     $options['sitename_title']['default'] = FALSE;
146     $options['row']['contains']['type']['default'] = 'rss_fields';
147     $options['defaults']['default']['style'] = FALSE;
148     $options['defaults']['default']['row'] = FALSE;
149
150     return $options;
151   }
152
153   /**
154    * {@inheritdoc}
155    */
156   public function newDisplay() {
157     parent::newDisplay();
158
159     // Set the default row style. Ideally this would be part of the option
160     // definition, but in this case it's dependent on the view's base table,
161     // which we don't know until init().
162     if (empty($this->options['row']['type']) || $this->options['row']['type'] === 'rss_fields') {
163       $row_plugins = Views::fetchPluginNames('row', $this->getType(), [$this->view->storage->get('base_table')]);
164       $default_row_plugin = key($row_plugins);
165
166       $options = $this->getOption('row');
167       $options['type'] = $default_row_plugin;
168       $this->setOption('row', $options);
169     }
170   }
171
172   /**
173    * {@inheritdoc}
174    */
175   public function optionsSummary(&$categories, &$options) {
176     parent::optionsSummary($categories, $options);
177
178     // Since we're childing off the 'path' type, we'll still *call* our
179     // category 'page' but let's override it so it says feed settings.
180     $categories['page'] = [
181       'title' => $this->t('Feed settings'),
182       'column' => 'second',
183       'build' => [
184         '#weight' => -10,
185       ],
186     ];
187
188     if ($this->getOption('sitename_title')) {
189       $options['title']['value'] = $this->t('Using the site name');
190     }
191
192     $displays = array_filter($this->getOption('displays'));
193     if (count($displays) > 1) {
194       $attach_to = $this->t('Multiple displays');
195     }
196     elseif (count($displays) == 1) {
197       $display = array_shift($displays);
198       $displays = $this->view->storage->get('display');
199       if (!empty($displays[$display])) {
200         $attach_to = $displays[$display]['display_title'];
201       }
202     }
203
204     if (!isset($attach_to)) {
205       $attach_to = $this->t('None');
206     }
207
208     $options['displays'] = [
209       'category' => 'page',
210       'title' => $this->t('Attach to'),
211       'value' => $attach_to,
212     ];
213   }
214
215   /**
216    * {@inheritdoc}
217    */
218   public function buildOptionsForm(&$form, FormStateInterface $form_state) {
219     // It is very important to call the parent function here.
220     parent::buildOptionsForm($form, $form_state);
221
222     switch ($form_state->get('section')) {
223       case 'title':
224         $title = $form['title'];
225         // A little juggling to move the 'title' field beyond our checkbox.
226         unset($form['title']);
227         $form['sitename_title'] = [
228           '#type' => 'checkbox',
229           '#title' => $this->t('Use the site name for the title'),
230           '#default_value' => $this->getOption('sitename_title'),
231         ];
232         $form['title'] = $title;
233         $form['title']['#states'] = [
234           'visible' => [
235             ':input[name="sitename_title"]' => ['checked' => FALSE],
236           ],
237         ];
238         break;
239       case 'displays':
240         $form['#title'] .= $this->t('Attach to');
241         $displays = [];
242         foreach ($this->view->storage->get('display') as $display_id => $display) {
243           // @todo The display plugin should have display_title and id as well.
244           if ($this->view->displayHandlers->has($display_id) && $this->view->displayHandlers->get($display_id)->acceptAttachments()) {
245             $displays[$display_id] = $display['display_title'];
246           }
247         }
248         $form['displays'] = [
249           '#title' => $this->t('Displays'),
250           '#type' => 'checkboxes',
251           '#description' => $this->t('The feed icon will be available only to the selected displays.'),
252           '#options' => array_map('\Drupal\Component\Utility\Html::escape', $displays),
253           '#default_value' => $this->getOption('displays'),
254         ];
255         break;
256       case 'path':
257         $form['path']['#description'] = $this->t('This view will be displayed by visiting this path on your site. It is recommended that the path be something like "path/%/%/feed" or "path/%/%/rss.xml", putting one % in the path for each contextual filter you have defined in the view.');
258     }
259   }
260
261   /**
262    * {@inheritdoc}
263    */
264   public function submitOptionsForm(&$form, FormStateInterface $form_state) {
265     parent::submitOptionsForm($form, $form_state);
266     $section = $form_state->get('section');
267     switch ($section) {
268       case 'title':
269         $this->setOption('sitename_title', $form_state->getValue('sitename_title'));
270         break;
271       case 'displays':
272         $this->setOption($section, $form_state->getValue($section));
273         break;
274     }
275   }
276
277   /**
278    * {@inheritdoc}
279    */
280   public function attachTo(ViewExecutable $clone, $display_id, array &$build) {
281     $displays = $this->getOption('displays');
282     if (empty($displays[$display_id])) {
283       return;
284     }
285
286     // Defer to the feed style; it may put in meta information, and/or
287     // attach a feed icon.
288     $clone->setArguments($this->view->args);
289     $clone->setDisplay($this->display['id']);
290     $clone->buildTitle();
291     if ($plugin = $clone->display_handler->getPlugin('style')) {
292       $plugin->attachTo($build, $display_id, $clone->getUrl(), $clone->getTitle());
293       foreach ($clone->feedIcons as $feed_icon) {
294         $this->view->feedIcons[] = $feed_icon;
295       }
296     }
297
298     // Clean up.
299     $clone->destroy();
300     unset($clone);
301   }
302
303   /**
304    * {@inheritdoc}
305    */
306   public function usesLinkDisplay() {
307     return TRUE;
308   }
309
310 }