ThemeHandler.php 13.7 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\Core\Extension\ThemeHandler.
 */

namespace Drupal\Core\Extension;

10
use Drupal\Component\Utility\SafeMarkup;
11
use Drupal\Core\Config\ConfigFactoryInterface;
12
use Drupal\Core\State\StateInterface;
13 14

/**
15
 * Default theme handler using the config system to store installation statuses.
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
 */
class ThemeHandler implements ThemeHandlerInterface {

  /**
   * Contains the features enabled for themes by default.
   *
   * @var array
   */
  protected $defaultFeatures = array(
    'favicon',
    'node_user_picture',
    'comment_user_picture',
    'comment_user_verification',
  );

  /**
   * A list of all currently available themes.
   *
   * @var array
   */
36
  protected $list;
37 38

  /**
39
   * The config factory to get the installed themes.
40
   *
41
   * @var \Drupal\Core\Config\ConfigFactoryInterface
42 43 44 45
   */
  protected $configFactory;

  /**
46
   * The module handler to fire themes_installed/themes_uninstalled hooks.
47 48 49 50 51 52
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
53
   * The state backend.
54
   *
55
   * @var \Drupal\Core\State\StateInterface
56
   */
57
  protected $state;
58

59 60 61 62 63 64 65
  /**
   *  The config installer to install configuration.
   *
   * @var \Drupal\Core\Config\ConfigInstallerInterface
   */
  protected $configInstaller;

66 67 68 69 70 71 72
  /**
   * The info parser to parse the theme.info.yml files.
   *
   * @var \Drupal\Core\Extension\InfoParserInterface
   */
  protected $infoParser;

73 74 75 76 77 78 79
  /**
   * A logger instance.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

80
  /**
81
   * The route builder to rebuild the routes if a theme is installed.
82
   *
83
   * @var \Drupal\Core\Routing\RouteBuilderInterface
84
   */
85
  protected $routeBuilder;
86 87

  /**
88
   * An extension discovery instance.
89
   *
90
   * @var \Drupal\Core\Extension\ExtensionDiscovery
91
   */
92
  protected $extensionDiscovery;
93

94 95 96 97 98 99 100
  /**
   * The CSS asset collection optimizer service.
   *
   * @var \Drupal\Core\Asset\AssetCollectionOptimizerInterface
   */
  protected $cssCollectionOptimizer;

101 102 103 104 105 106 107
  /**
   * The config manager used to uninstall a theme.
   *
   * @var \Drupal\Core\Config\ConfigManagerInterface
   */
  protected $configManager;

108 109 110 111 112 113 114
  /**
   * The app root.
   *
   * @var string
   */
  protected $root;

115 116 117
  /**
   * Constructs a new ThemeHandler.
   *
118 119
   * @param string $root
   *   The app root.
120
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
121
   *   The config factory to get the installed themes.
122
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
123
   *   The module handler to fire themes_installed/themes_uninstalled hooks.
124 125
   * @param \Drupal\Core\State\StateInterface $state
   *   The state store.
126 127
   * @param \Drupal\Core\Extension\InfoParserInterface $info_parser
   *   The info parser to parse the theme.info.yml files.
128 129
   * @param \Drupal\Core\Extension\ExtensionDiscovery $extension_discovery
   *   (optional) A extension discovery instance (for unit tests).
130
   */
131
  public function __construct($root, ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, StateInterface $state, InfoParserInterface $info_parser, ExtensionDiscovery $extension_discovery = NULL) {
132
    $this->root = $root;
133 134
    $this->configFactory = $config_factory;
    $this->moduleHandler = $module_handler;
135
    $this->state = $state;
136
    $this->infoParser = $info_parser;
137
    $this->extensionDiscovery = $extension_discovery;
138 139 140 141 142
  }

  /**
   * {@inheritdoc}
   */
143 144 145 146 147 148 149 150
  public function getDefault() {
    return $this->configFactory->get('system.theme')->get('default');
  }

  /**
   * {@inheritdoc}
   */
  public function setDefault($name) {
151 152
    $list = $this->listInfo();
    if (!isset($list[$name])) {
153
      throw new \InvalidArgumentException("$name theme is not installed.");
154
    }
155
    $this->configFactory->getEditable('system.theme')
156 157 158 159 160 161 162 163
      ->set('default', $name)
      ->save();
    return $this;
  }

  /**
   * {@inheritdoc}
   */
164
  public function install(array $theme_list, $install_dependencies = TRUE) {
165 166
    // We keep the old install() method as BC layer but redirect directly to the
    // theme installer.
167
    return \Drupal::service('theme_installer')->install($theme_list, $install_dependencies);
168 169 170 171 172
  }

  /**
   * {@inheritdoc}
   */
173
  public function uninstall(array $theme_list) {
174 175 176
    // We keep the old uninstall() method as BC layer but redirect directly to
    // the theme installer.
    \Drupal::service('theme_installer')->uninstall($theme_list);
177 178 179 180 181 182
  }

  /**
   * {@inheritdoc}
   */
  public function listInfo() {
183
    if (!isset($this->list)) {
184
      $this->list = array();
185
      $themes = $this->systemThemeList();
186 187 188 189 190 191 192
      // @todo Ensure that systemThemeList() does not contain an empty list
      //   during the batch installer, see https://www.drupal.org/node/2322619.
      if (empty($themes)) {
        $this->refreshInfo();
        $this->list = $this->list ?: array();
        $themes = \Drupal::state()->get('system.theme.data', array());
      }
193 194
      foreach ($themes as $theme) {
        $this->addTheme($theme);
195
      }
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    }
    return $this->list;
  }

  /**
   * {@inheritdoc}
   */
  public function addTheme(Extension $theme) {
    foreach ($theme->info['libraries'] as $library => $name) {
      $theme->libraries[$library] = $name;
    }
    if (isset($theme->info['engine'])) {
      $theme->engine = $theme->info['engine'];
    }
    if (isset($theme->info['base theme'])) {
      $theme->base_theme = $theme->info['base theme'];
    }
    $this->list[$theme->getName()] = $theme;
  }
215

216 217 218 219 220 221
  /**
   * {@inheritdoc}
   */
  public function refreshInfo() {
    $this->reset();
    $extension_config = $this->configFactory->get('core.extension');
222
    $installed = $extension_config->get('theme');
223 224 225 226 227

    // @todo Avoid re-scanning all themes by retaining the original (unaltered)
    //   theme info somewhere.
    $list = $this->rebuildThemeData();
    foreach ($list as $name => $theme) {
228
      if (isset($installed[$name])) {
229
        $this->addTheme($theme);
230 231
      }
    }
232
    $this->state->set('system.theme.data', $this->list);
233 234 235 236 237 238 239
  }

  /**
   * {@inheritdoc}
   */
  public function reset() {
    $this->systemListReset();
240
    $this->list = NULL;
241 242 243 244 245 246
  }

  /**
   * {@inheritdoc}
   */
  public function rebuildThemeData() {
247 248 249
    $listing = $this->getExtensionDiscovery();
    $themes = $listing->scan('theme');
    $engines = $listing->scan('theme_engine');
250
    $extension_config = $this->configFactory->get('core.extension');
251
    $installed = $extension_config->get('theme') ?: array();
252 253 254 255 256 257 258 259 260

    // Set defaults for theme info.
    $defaults = array(
      'engine' => 'twig',
      'regions' => array(
        'sidebar_first' => 'Left sidebar',
        'sidebar_second' => 'Right sidebar',
        'content' => 'Content',
        'header' => 'Header',
261 262
        'primary_menu' => 'Primary menu',
        'secondary_menu' => 'Secondary menu',
263 264 265 266 267
        'footer' => 'Footer',
        'highlighted' => 'Highlighted',
        'help' => 'Help',
        'page_top' => 'Page top',
        'page_bottom' => 'Page bottom',
268
        'breadcrumb' => 'Breadcrumb',
269 270 271 272 273
      ),
      'description' => '',
      'features' => $this->defaultFeatures,
      'screenshot' => 'screenshot.png',
      'php' => DRUPAL_MINIMUM_PHP,
274
      'libraries' => array(),
275 276 277
    );

    $sub_themes = array();
278 279
    $files_theme = array();
    $files_theme_engine = array();
280 281
    // Read info files for each theme.
    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 287 288

      // Add the info file modification time, so it becomes available for
      // contributed modules to use for ordering theme lists.
289
      $theme->info['mtime'] = $theme->getMTime();
290 291 292

      // Invoke hook_system_info_alter() to give installed modules a chance to
      // modify the data in the .info.yml files if necessary.
293
      // @todo Remove $type argument, obsolete with $theme->getType().
294
      $type = 'theme';
295
      $this->moduleHandler->alter('system_info', $theme->info, $theme, $type);
296

297
      if (!empty($theme->info['base theme'])) {
298
        $sub_themes[] = $key;
299 300
        // Add the base theme as a proper dependency.
        $themes[$key]->info['dependencies'][] = $themes[$key]->info['base theme'];
301 302
      }

303 304
      // Defaults to 'twig' (see $defaults above).
      $engine = $theme->info['engine'];
305
      if (isset($engines[$engine])) {
306
        $theme->owner = $engines[$engine]->getExtensionPathname();
307
        $theme->prefix = $engines[$engine]->getName();
308
        $files_theme_engine[$engine] = $engines[$engine]->getPathname();
309 310
      }

311
      // Prefix screenshot with theme path.
312
      if (!empty($theme->info['screenshot'])) {
313
        $theme->info['screenshot'] = $theme->getPath() . '/' . $theme->info['screenshot'];
314
      }
315

316
      $files_theme[$key] = $theme->getPathname();
317
    }
318 319
    // Build dependencies.
    // @todo Move into a generic ExtensionHandler base class.
320
    // @see https://www.drupal.org/node/2208429
321 322 323
    $themes = $this->moduleHandler->buildModuleDependencies($themes);

    // Store filenames to allow system_list() and drupal_get_filename() to
324 325 326 327
    // retrieve them for themes and theme engines without having to scan the
    // filesystem.
    $this->state->set('system.theme.files', $files_theme);
    $this->state->set('system.theme_engine.files', $files_theme_engine);
328

329 330
    // After establishing the full list of available themes, fill in data for
    // sub-themes.
331
    foreach ($sub_themes as $key) {
332 333 334 335 336 337 338 339
      $sub_theme = $themes[$key];
      // The $base_themes property is optional; only set for sub themes.
      // @see ThemeHandlerInterface::listInfo()
      $sub_theme->base_themes = $this->getBaseThemes($themes, $key);
      // empty() cannot be used here, since ThemeHandler::doGetBaseThemes() adds
      // the key of a base theme with a value of NULL in case it is not found,
      // in order to prevent needless iterations.
      if (!current($sub_theme->base_themes)) {
340 341
        continue;
      }
342 343 344 345 346
      // Determine the root base theme.
      $root_key = key($sub_theme->base_themes);
      // Build the list of sub-themes for each of the theme's base themes.
      foreach (array_keys($sub_theme->base_themes) as $base_theme) {
        $themes[$base_theme]->sub_themes[$key] = $sub_theme->info['name'];
347
      }
348 349 350 351 352
      // Add the theme engine info from the root base theme.
      if (isset($themes[$root_key]->owner)) {
        $sub_theme->info['engine'] = $themes[$root_key]->info['engine'];
        $sub_theme->owner = $themes[$root_key]->owner;
        $sub_theme->prefix = $themes[$root_key]->prefix;
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
      }
    }

    return $themes;
  }

  /**
   * {@inheritdoc}
   */
  public function getBaseThemes(array $themes, $theme) {
    return $this->doGetBaseThemes($themes, $theme);
  }

  /**
   * Finds the base themes for the specific theme.
   *
   * @param array $themes
   *   An array of available themes.
   * @param string $theme
   *   The name of the theme whose base we are looking for.
   * @param array $used_themes
   *   (optional) A recursion parameter preventing endless loops. Defaults to
   *   an empty array.
   *
   * @return array
   *   An array of base themes.
   */
  protected function doGetBaseThemes(array $themes, $theme, $used_themes = array()) {
    if (!isset($themes[$theme]->info['base theme'])) {
      return array();
    }

    $base_key = $themes[$theme]->info['base theme'];
    // Does the base theme exist?
    if (!isset($themes[$base_key])) {
      return array($base_key => NULL);
    }

    $current_base_theme = array($base_key => $themes[$base_key]->info['name']);

    // Is the base theme itself a child of another theme?
    if (isset($themes[$base_key]->info['base theme'])) {
      // Do we already know the base themes of this theme?
      if (isset($themes[$base_key]->base_themes)) {
        return $themes[$base_key]->base_themes + $current_base_theme;
      }
      // Prevent loops.
      if (!empty($used_themes[$base_key])) {
        return array($base_key => NULL);
      }
      $used_themes[$base_key] = TRUE;
404
      return $this->doGetBaseThemes($themes, $base_key, $used_themes) + $current_base_theme;
405 406 407 408 409 410
    }
    // If we get here, then this is our parent theme.
    return $current_base_theme;
  }

  /**
411
   * Returns an extension discovery object.
412
   *
413 414
   * @return \Drupal\Core\Extension\ExtensionDiscovery
   *   The extension discovery object.
415
   */
416 417
  protected function getExtensionDiscovery() {
    if (!isset($this->extensionDiscovery)) {
418
      $this->extensionDiscovery = new ExtensionDiscovery($this->root);
419
    }
420
    return $this->extensionDiscovery;
421 422
  }

423 424 425 426 427 428
  /**
   * {@inheritdoc}
   */
  public function getName($theme) {
    $themes = $this->listInfo();
    if (!isset($themes[$theme])) {
429
      throw new \InvalidArgumentException("Requested the name of a non-existing theme $theme");
430
    }
431
    return SafeMarkup::checkPlain($themes[$theme]->info['name']);
432 433
  }

434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
  /**
   * Wraps system_list_reset().
   */
  protected function systemListReset() {
    system_list_reset();
  }

  /**
   * Wraps system_list().
   *
   * @return array
   *   A list of themes keyed by name.
   */
  protected function systemThemeList() {
    return system_list('theme');
  }

451 452 453 454 455 456
  /**
   * {@inheritdoc}
   */
  public function getThemeDirectories() {
    $dirs = array();
    foreach ($this->listInfo() as $name => $theme) {
457
      $dirs[$name] = $this->root . '/' . $theme->getPath();
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
    }
    return $dirs;
  }

  /**
   * {@inheritdoc}
   */
  public function themeExists($theme) {
    $themes = $this->listInfo();
    return isset($themes[$theme]);
  }

  /**
   * {@inheritdoc}
   */
  public function getTheme($name) {
    $themes = $this->listInfo();
    if (isset($themes[$name])) {
      return $themes[$name];
    }
    throw new \InvalidArgumentException(sprintf('The theme %s does not exist.', $name));
  }

481
}