Updated Drupal to 8.6. This goes with the following updates because it's possible...
[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    * {@inheritdoc}
78    */
79   public function execute() {
80     parent::execute();
81
82     return $this->view->render();
83   }
84
85   /**
86    * {@inheritdoc}
87    */
88   public function preview() {
89     $output = $this->view->render();
90
91     if (!empty($this->view->live_preview)) {
92       $output = [
93         '#prefix' => '<pre>',
94         '#plain_text' => drupal_render_root($output),
95         '#suffix' => '</pre>',
96       ];
97     }
98
99     return $output;
100   }
101
102   /**
103    * {@inheritdoc}
104    */
105   public function render() {
106     $build = $this->view->style_plugin->render($this->view->result);
107
108     $this->applyDisplayCacheabilityMetadata($build);
109
110     return $build;
111   }
112
113   /**
114    * {@inheritdoc}
115    */
116   public function defaultableSections($section = NULL) {
117     $sections = parent::defaultableSections($section);
118
119     if (in_array($section, ['style', 'row'])) {
120       return FALSE;
121     }
122
123     // Tell views our sitename_title option belongs in the title section.
124     if ($section == 'title') {
125       $sections[] = 'sitename_title';
126     }
127     elseif (!$section) {
128       $sections['title'][] = 'sitename_title';
129     }
130     return $sections;
131   }
132
133   /**
134    * {@inheritdoc}
135    */
136   protected function defineOptions() {
137     $options = parent::defineOptions();
138
139     $options['displays'] = ['default' => []];
140
141     // Overrides for standard stuff.
142     $options['style']['contains']['type']['default'] = 'rss';
143     $options['style']['contains']['options']['default'] = ['description' => ''];
144     $options['sitename_title']['default'] = FALSE;
145     $options['row']['contains']['type']['default'] = 'rss_fields';
146     $options['defaults']['default']['style'] = FALSE;
147     $options['defaults']['default']['row'] = FALSE;
148
149     return $options;
150   }
151
152   /**
153    * {@inheritdoc}
154    */
155   public function newDisplay() {
156     parent::newDisplay();
157
158     // Set the default row style. Ideally this would be part of the option
159     // definition, but in this case it's dependent on the view's base table,
160     // which we don't know until init().
161     if (empty($this->options['row']['type']) || $this->options['row']['type'] === 'rss_fields') {
162       $row_plugins = Views::fetchPluginNames('row', $this->getType(), [$this->view->storage->get('base_table')]);
163       $default_row_plugin = key($row_plugins);
164
165       $options = $this->getOption('row');
166       $options['type'] = $default_row_plugin;
167       $this->setOption('row', $options);
168     }
169   }
170
171   /**
172    * {@inheritdoc}
173    */
174   public function optionsSummary(&$categories, &$options) {
175     parent::optionsSummary($categories, $options);
176
177     // Since we're childing off the 'path' type, we'll still *call* our
178     // category 'page' but let's override it so it says feed settings.
179     $categories['page'] = [
180       'title' => $this->t('Feed settings'),
181       'column' => 'second',
182       'build' => [
183         '#weight' => -10,
184       ],
185     ];
186
187     if ($this->getOption('sitename_title')) {
188       $options['title']['value'] = $this->t('Using the site name');
189     }
190
191     $displays = array_filter($this->getOption('displays'));
192     if (count($displays) > 1) {
193       $attach_to = $this->t('Multiple displays');
194     }
195     elseif (count($displays) == 1) {
196       $display = array_shift($displays);
197       $displays = $this->view->storage->get('display');
198       if (!empty($displays[$display])) {
199         $attach_to = $displays[$display]['display_title'];
200       }
201     }
202
203     if (!isset($attach_to)) {
204       $attach_to = $this->t('None');
205     }
206
207     $options['displays'] = [
208       'category' => 'page',
209       'title' => $this->t('Attach to'),
210       'value' => $attach_to,
211     ];
212   }
213
214   /**
215    * {@inheritdoc}
216    */
217   public function buildOptionsForm(&$form, FormStateInterface $form_state) {
218     // It is very important to call the parent function here.
219     parent::buildOptionsForm($form, $form_state);
220
221     switch ($form_state->get('section')) {
222       case 'title':
223         $title = $form['title'];
224         // A little juggling to move the 'title' field beyond our checkbox.
225         unset($form['title']);
226         $form['sitename_title'] = [
227           '#type' => 'checkbox',
228           '#title' => $this->t('Use the site name for the title'),
229           '#default_value' => $this->getOption('sitename_title'),
230         ];
231         $form['title'] = $title;
232         $form['title']['#states'] = [
233           'visible' => [
234             ':input[name="sitename_title"]' => ['checked' => FALSE],
235           ],
236         ];
237         break;
238       case 'displays':
239         $form['#title'] .= $this->t('Attach to');
240         $displays = [];
241         foreach ($this->view->storage->get('display') as $display_id => $display) {
242           // @todo The display plugin should have display_title and id as well.
243           if ($this->view->displayHandlers->has($display_id) && $this->view->displayHandlers->get($display_id)->acceptAttachments()) {
244             $displays[$display_id] = $display['display_title'];
245           }
246         }
247         $form['displays'] = [
248           '#title' => $this->t('Displays'),
249           '#type' => 'checkboxes',
250           '#description' => $this->t('The feed icon will be available only to the selected displays.'),
251           '#options' => array_map('\Drupal\Component\Utility\Html::escape', $displays),
252           '#default_value' => $this->getOption('displays'),
253         ];
254         break;
255       case 'path':
256         $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.');
257     }
258   }
259
260   /**
261    * {@inheritdoc}
262    */
263   public function submitOptionsForm(&$form, FormStateInterface $form_state) {
264     parent::submitOptionsForm($form, $form_state);
265     $section = $form_state->get('section');
266     switch ($section) {
267       case 'title':
268         $this->setOption('sitename_title', $form_state->getValue('sitename_title'));
269         break;
270       case 'displays':
271         $this->setOption($section, $form_state->getValue($section));
272         break;
273     }
274   }
275
276   /**
277    * {@inheritdoc}
278    */
279   public function attachTo(ViewExecutable $clone, $display_id, array &$build) {
280     $displays = $this->getOption('displays');
281     if (empty($displays[$display_id])) {
282       return;
283     }
284
285     // Defer to the feed style; it may put in meta information, and/or
286     // attach a feed icon.
287     $clone->setArguments($this->view->args);
288     $clone->setDisplay($this->display['id']);
289     $clone->buildTitle();
290     if ($plugin = $clone->display_handler->getPlugin('style')) {
291       $plugin->attachTo($build, $display_id, $clone->getUrl(), $clone->getTitle());
292       foreach ($clone->feedIcons as $feed_icon) {
293         $this->view->feedIcons[] = $feed_icon;
294       }
295     }
296
297     // Clean up.
298     $clone->destroy();
299     unset($clone);
300   }
301
302   /**
303    * {@inheritdoc}
304    */
305   public function usesLinkDisplay() {
306     return TRUE;
307   }
308
309 }