Security update for Core, with self-updated composer
[yaffs-website] / web / core / lib / Drupal / Core / EventSubscriber / ActiveLinkResponseFilter.php
1 <?php
2
3 namespace Drupal\Core\EventSubscriber;
4
5 use Drupal\Component\Serialization\Json;
6 use Drupal\Core\Language\LanguageInterface;
7 use Drupal\Core\Language\LanguageManagerInterface;
8 use Drupal\Core\Path\CurrentPathStack;
9 use Drupal\Core\Path\PathMatcherInterface;
10 use Drupal\Core\Session\AccountInterface;
11 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
12 use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
13 use Symfony\Component\HttpKernel\KernelEvents;
14
15 /**
16  * Subscribes to filter HTML responses, to set the 'is-active' class on links.
17  *
18  * Only for anonymous users; for authenticated users, the active-link asset
19  * library is loaded.
20  *
21  * @see system_page_attachments()
22  */
23 class ActiveLinkResponseFilter implements EventSubscriberInterface {
24
25   /**
26    * The current user.
27    *
28    * @var \Drupal\Core\Session\AccountInterface
29    */
30   protected $currentUser;
31
32   /**
33    * The current path.
34    *
35    * @var \Drupal\Core\Path\CurrentPathStack
36    */
37   protected $currentPath;
38
39   /**
40    * The path matcher.
41    *
42    * @var \Drupal\Core\Path\PathMatcherInterface
43    */
44   protected $pathMatcher;
45
46   /**
47    * The language manager.
48    *
49    * @var \Drupal\Core\Language\LanguageManagerInterface
50    */
51   protected $languageManager;
52
53   /**
54    * Constructs a new ActiveLinkResponseFilter instance.
55    *
56    * @param \Drupal\Core\Session\AccountInterface $current_user
57    *   The current user.
58    * @param \Drupal\Core\Path\CurrentPathStack $current_path
59    *   The current path.
60    * @param \Drupal\Core\Path\PathMatcherInterface $path_matcher
61    *   The path matcher.
62    * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
63    *   The language manager.
64    */
65   public function __construct(AccountInterface $current_user, CurrentPathStack $current_path, PathMatcherInterface $path_matcher, LanguageManagerInterface $language_manager) {
66     $this->currentUser = $current_user;
67     $this->currentPath = $current_path;
68     $this->pathMatcher = $path_matcher;
69     $this->languageManager = $language_manager;
70   }
71
72   /**
73    * Sets the 'is-active' class on links.
74    *
75    * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
76    *   The response event.
77    */
78   public function onResponse(FilterResponseEvent $event) {
79     // Only care about HTML responses.
80     if (stripos($event->getResponse()->headers->get('Content-Type'), 'text/html') === FALSE) {
81       return;
82     }
83
84     // For authenticated users, the 'is-active' class is set in JavaScript.
85     // @see system_page_attachments()
86     if ($this->currentUser->isAuthenticated()) {
87       return;
88     }
89
90     $response = $event->getResponse();
91     $response->setContent(static::setLinkActiveClass(
92       $response->getContent(),
93       ltrim($this->currentPath->getPath(), '/'),
94       $this->pathMatcher->isFrontPage(),
95       $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_URL)->getId(),
96       $event->getRequest()->query->all()
97     ));
98   }
99
100
101   /**
102    * Sets the "is-active" class on relevant links.
103    *
104    * This is a PHP implementation of the drupal.active-link JavaScript library.
105    *
106    * @param string $html_markup
107    *   The HTML markup to update.
108    * @param string $current_path
109    *   The system path of the currently active page.
110    * @param bool $is_front
111    *   Whether the current page is the front page (which implies the current
112    *   path might also be <front>).
113    * @param string $url_language
114    *   The language code of the current URL.
115    * @param array $query
116    *   The query string for the current URL.
117    *
118    * @return string
119    *   The updated HTML markup.
120    *
121    * @todo Once a future version of PHP supports parsing HTML5 properly
122    *   (i.e. doesn't fail on
123    *   https://www.drupal.org/comment/7938201#comment-7938201) then we can get
124    *   rid of this manual parsing and use DOMDocument instead.
125    */
126   public static function setLinkActiveClass($html_markup, $current_path, $is_front, $url_language, array $query) {
127     $search_key_current_path = 'data-drupal-link-system-path="' . $current_path . '"';
128     $search_key_front = 'data-drupal-link-system-path="&lt;front&gt;"';
129
130     $offset = 0;
131     // There are two distinct conditions that can make a link be marked active:
132     // 1. A link has the current path in its 'data-drupal-link-system-path'
133     //    attribute.
134     // 2. We are on the front page and a link has the special '<front>' value in
135     //    its 'data-drupal-link-system-path' attribute.
136     while (strpos($html_markup, $search_key_current_path, $offset) !== FALSE || ($is_front && strpos($html_markup, $search_key_front, $offset) !== FALSE)) {
137       $pos_current_path = strpos($html_markup, $search_key_current_path, $offset);
138       // Only look for links with the special '<front>' system path if we are
139       // actually on the front page.
140       $pos_front = $is_front ? strpos($html_markup, $search_key_front, $offset) : FALSE;
141
142       // Determine which of the two values is the next match: the exact path, or
143       // the <front> special case.
144       $pos_match = NULL;
145       if ($pos_front === FALSE) {
146         $pos_match = $pos_current_path;
147       }
148       elseif ($pos_current_path === FALSE) {
149         $pos_match = $pos_front;
150       }
151       elseif ($pos_current_path < $pos_front) {
152         $pos_match = $pos_current_path;
153       }
154       else {
155         $pos_match = $pos_front;
156       }
157
158       // Find beginning and ending of opening tag.
159       $pos_tag_start = NULL;
160       for ($i = $pos_match; $pos_tag_start === NULL && $i > 0; $i--) {
161         if ($html_markup[$i] === '<') {
162           $pos_tag_start = $i;
163         }
164       }
165       $pos_tag_end = NULL;
166       for ($i = $pos_match; $pos_tag_end === NULL && $i < strlen($html_markup); $i++) {
167         if ($html_markup[$i] === '>') {
168           $pos_tag_end = $i;
169         }
170       }
171
172       // Get the HTML: this will be the opening part of a single tag, e.g.:
173       //   <a href="/" data-drupal-link-system-path="&lt;front&gt;">
174       $tag = substr($html_markup, $pos_tag_start, $pos_tag_end - $pos_tag_start + 1);
175
176       // Parse it into a DOMDocument so we can reliably read and modify
177       // attributes.
178       $dom = new \DOMDocument();
179       @$dom->loadHTML('<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body>' . $tag . '</body></html>');
180       $node = $dom->getElementsByTagName('body')->item(0)->firstChild;
181
182       // Ensure we don't set the "active" class twice on the same element.
183       $class = $node->getAttribute('class');
184       $add_active = !in_array('is-active', explode(' ', $class));
185
186       // The language of an active link is equal to the current language.
187       if ($add_active && $url_language) {
188         if ($node->hasAttribute('hreflang') && $node->getAttribute('hreflang') !== $url_language) {
189           $add_active = FALSE;
190         }
191       }
192       // The query parameters of an active link are equal to the current
193       // parameters.
194       if ($add_active) {
195         if ($query) {
196           if (!$node->hasAttribute('data-drupal-link-query') || $node->getAttribute('data-drupal-link-query') !== Json::encode($query)) {
197             $add_active = FALSE;
198           }
199         }
200         else {
201           if ($node->hasAttribute('data-drupal-link-query')) {
202             $add_active = FALSE;
203           }
204         }
205       }
206
207       // Only if the path, the language and the query match, we set the
208       // "is-active" class.
209       if ($add_active) {
210         if (strlen($class) > 0) {
211           $class .= ' ';
212         }
213         $class .= 'is-active';
214         $node->setAttribute('class', $class);
215
216         // Get the updated tag.
217         $updated_tag = $dom->saveXML($node, LIBXML_NOEMPTYTAG);
218         // saveXML() added a closing tag, remove it.
219         $updated_tag = substr($updated_tag, 0, strrpos($updated_tag, '<'));
220
221         $html_markup = str_replace($tag, $updated_tag, $html_markup);
222
223         // Ensure we only search the remaining HTML.
224         $offset = $pos_tag_end - strlen($tag) + strlen($updated_tag);
225       }
226       else {
227         // Ensure we only search the remaining HTML.
228         $offset = $pos_tag_end + 1;
229       }
230     }
231
232     return $html_markup;
233   }
234
235   /**
236    * {@inheritdoc}
237    */
238   public static function getSubscribedEvents() {
239     // Should run after any other response subscriber that modifies the markup.
240     $events[KernelEvents::RESPONSE][] = ['onResponse', -512];
241
242     return $events;
243   }
244
245 }