2fd75e190cabdf6259aa169841da84332e9c71a8
[yaffs-website] / web / core / lib / Drupal / Core / Extension / ThemeHandler.php
1 <?php
2
3 namespace Drupal\Core\Extension;
4
5 use Drupal\Core\Config\ConfigFactoryInterface;
6 use Drupal\Core\State\StateInterface;
7
8 /**
9  * Default theme handler using the config system to store installation statuses.
10  */
11 class ThemeHandler implements ThemeHandlerInterface {
12
13   /**
14    * Contains the features enabled for themes by default.
15    *
16    * @var array
17    *
18    * @see _system_default_theme_features()
19    */
20   protected $defaultFeatures = [
21     'favicon',
22     'logo',
23     'node_user_picture',
24     'comment_user_picture',
25     'comment_user_verification',
26   ];
27
28   /**
29    * A list of all currently available themes.
30    *
31    * @var array
32    */
33   protected $list;
34
35   /**
36    * The config factory to get the installed themes.
37    *
38    * @var \Drupal\Core\Config\ConfigFactoryInterface
39    */
40   protected $configFactory;
41
42   /**
43    * The module handler to fire themes_installed/themes_uninstalled hooks.
44    *
45    * @var \Drupal\Core\Extension\ModuleHandlerInterface
46    */
47   protected $moduleHandler;
48
49   /**
50    * The state backend.
51    *
52    * @var \Drupal\Core\State\StateInterface
53    */
54   protected $state;
55
56   /**
57    * The config installer to install configuration.
58    *
59    * @var \Drupal\Core\Config\ConfigInstallerInterface
60    */
61   protected $configInstaller;
62
63   /**
64    * The info parser to parse the theme.info.yml files.
65    *
66    * @var \Drupal\Core\Extension\InfoParserInterface
67    */
68   protected $infoParser;
69
70   /**
71    * A logger instance.
72    *
73    * @var \Psr\Log\LoggerInterface
74    */
75   protected $logger;
76
77   /**
78    * The route builder to rebuild the routes if a theme is installed.
79    *
80    * @var \Drupal\Core\Routing\RouteBuilderInterface
81    */
82   protected $routeBuilder;
83
84   /**
85    * An extension discovery instance.
86    *
87    * @var \Drupal\Core\Extension\ExtensionDiscovery
88    */
89   protected $extensionDiscovery;
90
91   /**
92    * The CSS asset collection optimizer service.
93    *
94    * @var \Drupal\Core\Asset\AssetCollectionOptimizerInterface
95    */
96   protected $cssCollectionOptimizer;
97
98   /**
99    * The config manager used to uninstall a theme.
100    *
101    * @var \Drupal\Core\Config\ConfigManagerInterface
102    */
103   protected $configManager;
104
105   /**
106    * The app root.
107    *
108    * @var string
109    */
110   protected $root;
111
112   /**
113    * Constructs a new ThemeHandler.
114    *
115    * @param string $root
116    *   The app root.
117    * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
118    *   The config factory to get the installed themes.
119    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
120    *   The module handler to fire themes_installed/themes_uninstalled hooks.
121    * @param \Drupal\Core\State\StateInterface $state
122    *   The state store.
123    * @param \Drupal\Core\Extension\InfoParserInterface $info_parser
124    *   The info parser to parse the theme.info.yml files.
125    * @param \Drupal\Core\Extension\ExtensionDiscovery $extension_discovery
126    *   (optional) A extension discovery instance (for unit tests).
127    */
128   public function __construct($root, ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, StateInterface $state, InfoParserInterface $info_parser, ExtensionDiscovery $extension_discovery = NULL) {
129     $this->root = $root;
130     $this->configFactory = $config_factory;
131     $this->moduleHandler = $module_handler;
132     $this->state = $state;
133     $this->infoParser = $info_parser;
134     $this->extensionDiscovery = $extension_discovery;
135   }
136
137   /**
138    * {@inheritdoc}
139    */
140   public function getDefault() {
141     return $this->configFactory->get('system.theme')->get('default');
142   }
143
144   /**
145    * {@inheritdoc}
146    */
147   public function setDefault($name) {
148     $list = $this->listInfo();
149     if (!isset($list[$name])) {
150       throw new \InvalidArgumentException("$name theme is not installed.");
151     }
152     $this->configFactory->getEditable('system.theme')
153       ->set('default', $name)
154       ->save();
155     return $this;
156   }
157
158   /**
159    * {@inheritdoc}
160    */
161   public function install(array $theme_list, $install_dependencies = TRUE) {
162     // We keep the old install() method as BC layer but redirect directly to the
163     // theme installer.
164     return \Drupal::service('theme_installer')->install($theme_list, $install_dependencies);
165   }
166
167   /**
168    * {@inheritdoc}
169    */
170   public function uninstall(array $theme_list) {
171     // We keep the old uninstall() method as BC layer but redirect directly to
172     // the theme installer.
173     \Drupal::service('theme_installer')->uninstall($theme_list);
174   }
175
176   /**
177    * {@inheritdoc}
178    */
179   public function listInfo() {
180     if (!isset($this->list)) {
181       $this->list = [];
182       $themes = $this->systemThemeList();
183       // @todo Ensure that systemThemeList() does not contain an empty list
184       //   during the batch installer, see https://www.drupal.org/node/2322619.
185       if (empty($themes)) {
186         $this->refreshInfo();
187         $this->list = $this->list ?: [];
188         $themes = \Drupal::state()->get('system.theme.data', []);
189       }
190       foreach ($themes as $theme) {
191         $this->addTheme($theme);
192       }
193     }
194     return $this->list;
195   }
196
197   /**
198    * {@inheritdoc}
199    */
200   public function addTheme(Extension $theme) {
201     if (!empty($theme->info['libraries'])) {
202       foreach ($theme->info['libraries'] as $library => $name) {
203         $theme->libraries[$library] = $name;
204       }
205     }
206     if (isset($theme->info['engine'])) {
207       $theme->engine = $theme->info['engine'];
208     }
209     if (isset($theme->info['base theme'])) {
210       $theme->base_theme = $theme->info['base theme'];
211     }
212     $this->list[$theme->getName()] = $theme;
213   }
214
215   /**
216    * {@inheritdoc}
217    */
218   public function refreshInfo() {
219     $this->reset();
220     $extension_config = $this->configFactory->get('core.extension');
221     $installed = $extension_config->get('theme');
222
223     // @todo Avoid re-scanning all themes by retaining the original (unaltered)
224     //   theme info somewhere.
225     $list = $this->rebuildThemeData();
226     foreach ($list as $name => $theme) {
227       if (isset($installed[$name])) {
228         $this->addTheme($theme);
229       }
230     }
231     $this->state->set('system.theme.data', $this->list);
232   }
233
234   /**
235    * {@inheritdoc}
236    */
237   public function reset() {
238     $this->systemListReset();
239     $this->list = NULL;
240   }
241
242   /**
243    * {@inheritdoc}
244    */
245   public function rebuildThemeData() {
246     $listing = $this->getExtensionDiscovery();
247     $themes = $listing->scan('theme');
248     $engines = $listing->scan('theme_engine');
249     $extension_config = $this->configFactory->get('core.extension');
250     $installed = $extension_config->get('theme') ?: [];
251
252     // Set defaults for theme info.
253     $defaults = [
254       'engine' => 'twig',
255       'base theme' => 'stable',
256       'regions' => [
257         'sidebar_first' => 'Left sidebar',
258         'sidebar_second' => 'Right sidebar',
259         'content' => 'Content',
260         'header' => 'Header',
261         'primary_menu' => 'Primary menu',
262         'secondary_menu' => 'Secondary menu',
263         'footer' => 'Footer',
264         'highlighted' => 'Highlighted',
265         'help' => 'Help',
266         'page_top' => 'Page top',
267         'page_bottom' => 'Page bottom',
268         'breadcrumb' => 'Breadcrumb',
269       ],
270       'description' => '',
271       'features' => $this->defaultFeatures,
272       'screenshot' => 'screenshot.png',
273       'php' => DRUPAL_MINIMUM_PHP,
274       'libraries' => [],
275     ];
276
277     $sub_themes = [];
278     $files_theme = [];
279     $files_theme_engine = [];
280     // Read info files for each theme.
281     foreach ($themes as $key => $theme) {
282       // @todo Remove all code that relies on the $status property.
283       $theme->status = (int) isset($installed[$key]);
284
285       $theme->info = $this->infoParser->parse($theme->getPathname()) + $defaults;
286       // Remove the default Stable base theme when 'base theme: false' is set in
287       // a theme .info.yml file.
288       if ($theme->info['base theme'] === FALSE) {
289         unset($theme->info['base theme']);
290       }
291
292       // Add the info file modification time, so it becomes available for
293       // contributed modules to use for ordering theme lists.
294       $theme->info['mtime'] = $theme->getMTime();
295
296       // Invoke hook_system_info_alter() to give installed modules a chance to
297       // modify the data in the .info.yml files if necessary.
298       // @todo Remove $type argument, obsolete with $theme->getType().
299       $type = 'theme';
300       $this->moduleHandler->alter('system_info', $theme->info, $theme, $type);
301
302       if (!empty($theme->info['base theme'])) {
303         $sub_themes[] = $key;
304         // Add the base theme as a proper dependency.
305         $themes[$key]->info['dependencies'][] = $themes[$key]->info['base theme'];
306       }
307
308       // Defaults to 'twig' (see $defaults above).
309       $engine = $theme->info['engine'];
310       if (isset($engines[$engine])) {
311         $theme->owner = $engines[$engine]->getExtensionPathname();
312         $theme->prefix = $engines[$engine]->getName();
313         $files_theme_engine[$engine] = $engines[$engine]->getPathname();
314       }
315
316       // Prefix screenshot with theme path.
317       if (!empty($theme->info['screenshot'])) {
318         $theme->info['screenshot'] = $theme->getPath() . '/' . $theme->info['screenshot'];
319       }
320
321       $files_theme[$key] = $theme->getPathname();
322     }
323     // Build dependencies.
324     // @todo Move into a generic ExtensionHandler base class.
325     // @see https://www.drupal.org/node/2208429
326     $themes = $this->moduleHandler->buildModuleDependencies($themes);
327
328     // Store filenames to allow system_list() and drupal_get_filename() to
329     // retrieve them for themes and theme engines without having to scan the
330     // filesystem.
331     $this->state->set('system.theme.files', $files_theme);
332     $this->state->set('system.theme_engine.files', $files_theme_engine);
333
334     // After establishing the full list of available themes, fill in data for
335     // sub-themes.
336     foreach ($sub_themes as $key) {
337       $sub_theme = $themes[$key];
338       // The $base_themes property is optional; only set for sub themes.
339       // @see ThemeHandlerInterface::listInfo()
340       $sub_theme->base_themes = $this->getBaseThemes($themes, $key);
341       // empty() cannot be used here, since ThemeHandler::doGetBaseThemes() adds
342       // the key of a base theme with a value of NULL in case it is not found,
343       // in order to prevent needless iterations.
344       if (!current($sub_theme->base_themes)) {
345         continue;
346       }
347       // Determine the root base theme.
348       $root_key = key($sub_theme->base_themes);
349       // Build the list of sub-themes for each of the theme's base themes.
350       foreach (array_keys($sub_theme->base_themes) as $base_theme) {
351         $themes[$base_theme]->sub_themes[$key] = $sub_theme->info['name'];
352       }
353       // Add the theme engine info from the root base theme.
354       if (isset($themes[$root_key]->owner)) {
355         $sub_theme->info['engine'] = $themes[$root_key]->info['engine'];
356         $sub_theme->owner = $themes[$root_key]->owner;
357         $sub_theme->prefix = $themes[$root_key]->prefix;
358       }
359     }
360
361     return $themes;
362   }
363
364   /**
365    * {@inheritdoc}
366    */
367   public function getBaseThemes(array $themes, $theme) {
368     return $this->doGetBaseThemes($themes, $theme);
369   }
370
371   /**
372    * Finds the base themes for the specific theme.
373    *
374    * @param array $themes
375    *   An array of available themes.
376    * @param string $theme
377    *   The name of the theme whose base we are looking for.
378    * @param array $used_themes
379    *   (optional) A recursion parameter preventing endless loops. Defaults to
380    *   an empty array.
381    *
382    * @return array
383    *   An array of base themes.
384    */
385   protected function doGetBaseThemes(array $themes, $theme, $used_themes = []) {
386     if (!isset($themes[$theme]->info['base theme'])) {
387       return [];
388     }
389
390     $base_key = $themes[$theme]->info['base theme'];
391     // Does the base theme exist?
392     if (!isset($themes[$base_key])) {
393       return [$base_key => NULL];
394     }
395
396     $current_base_theme = [$base_key => $themes[$base_key]->info['name']];
397
398     // Is the base theme itself a child of another theme?
399     if (isset($themes[$base_key]->info['base theme'])) {
400       // Do we already know the base themes of this theme?
401       if (isset($themes[$base_key]->base_themes)) {
402         return $themes[$base_key]->base_themes + $current_base_theme;
403       }
404       // Prevent loops.
405       if (!empty($used_themes[$base_key])) {
406         return [$base_key => NULL];
407       }
408       $used_themes[$base_key] = TRUE;
409       return $this->doGetBaseThemes($themes, $base_key, $used_themes) + $current_base_theme;
410     }
411     // If we get here, then this is our parent theme.
412     return $current_base_theme;
413   }
414
415   /**
416    * Returns an extension discovery object.
417    *
418    * @return \Drupal\Core\Extension\ExtensionDiscovery
419    *   The extension discovery object.
420    */
421   protected function getExtensionDiscovery() {
422     if (!isset($this->extensionDiscovery)) {
423       $this->extensionDiscovery = new ExtensionDiscovery($this->root);
424     }
425     return $this->extensionDiscovery;
426   }
427
428   /**
429    * {@inheritdoc}
430    */
431   public function getName($theme) {
432     $themes = $this->listInfo();
433     if (!isset($themes[$theme])) {
434       throw new \InvalidArgumentException("Requested the name of a non-existing theme $theme");
435     }
436     return $themes[$theme]->info['name'];
437   }
438
439   /**
440    * Wraps system_list_reset().
441    */
442   protected function systemListReset() {
443     system_list_reset();
444   }
445
446   /**
447    * Wraps system_list().
448    *
449    * @return array
450    *   A list of themes keyed by name.
451    */
452   protected function systemThemeList() {
453     return system_list('theme');
454   }
455
456   /**
457    * {@inheritdoc}
458    */
459   public function getThemeDirectories() {
460     $dirs = [];
461     foreach ($this->listInfo() as $name => $theme) {
462       $dirs[$name] = $this->root . '/' . $theme->getPath();
463     }
464     return $dirs;
465   }
466
467   /**
468    * {@inheritdoc}
469    */
470   public function themeExists($theme) {
471     $themes = $this->listInfo();
472     return isset($themes[$theme]);
473   }
474
475   /**
476    * {@inheritdoc}
477    */
478   public function getTheme($name) {
479     $themes = $this->listInfo();
480     if (isset($themes[$name])) {
481       return $themes[$name];
482     }
483     throw new \InvalidArgumentException(sprintf('The theme %s does not exist.', $name));
484   }
485
486   /**
487    * {@inheritdoc}
488    */
489   public function hasUi($name) {
490     $themes = $this->listInfo();
491     if (isset($themes[$name])) {
492       if (!empty($themes[$name]->info['hidden'])) {
493         $theme_config = $this->configFactory->get('system.theme');
494         return $name == $theme_config->get('default') || $name == $theme_config->get('admin');
495       }
496       return TRUE;
497     }
498     return FALSE;
499   }
500
501 }