ThemeHandler.php 21.6 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\Asset\AssetCollectionOptimizerInterface;
12
use Drupal\Core\Cache\Cache;
13
use Drupal\Core\Config\ConfigFactoryInterface;
14
use Drupal\Core\Config\ConfigInstallerInterface;
15
use Drupal\Core\Config\ConfigManagerInterface;
16
use Drupal\Core\Config\PreExistingConfigException;
17
use Drupal\Core\Routing\RouteBuilderInterface;
18
use Drupal\Core\State\StateInterface;
19
use Psr\Log\LoggerInterface;
20 21

/**
22
 * Default theme handler using the config system to store installation statuses.
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
 */
class ThemeHandler implements ThemeHandlerInterface {

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

  /**
   * A list of all currently available themes.
   *
   * @var array
   */
46
  protected $list;
47 48

  /**
49
   * The config factory to get the installed themes.
50
   *
51
   * @var \Drupal\Core\Config\ConfigFactoryInterface
52 53 54 55
   */
  protected $configFactory;

  /**
56
   * The module handler to fire themes_installed/themes_uninstalled hooks.
57 58 59 60 61 62
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
63
   * The state backend.
64
   *
65
   * @var \Drupal\Core\State\StateInterface
66
   */
67
  protected $state;
68

69 70 71 72 73 74 75
  /**
   *  The config installer to install configuration.
   *
   * @var \Drupal\Core\Config\ConfigInstallerInterface
   */
  protected $configInstaller;

76 77 78 79 80 81 82
  /**
   * The info parser to parse the theme.info.yml files.
   *
   * @var \Drupal\Core\Extension\InfoParserInterface
   */
  protected $infoParser;

83 84 85 86 87 88 89
  /**
   * A logger instance.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

90
  /**
91
   * The route builder to rebuild the routes if a theme is installed.
92
   *
93
   * @var \Drupal\Core\Routing\RouteBuilderInterface
94
   */
95
  protected $routeBuilder;
96 97

  /**
98
   * An extension discovery instance.
99
   *
100
   * @var \Drupal\Core\Extension\ExtensionDiscovery
101
   */
102
  protected $extensionDiscovery;
103

104 105 106 107 108 109 110
  /**
   * The CSS asset collection optimizer service.
   *
   * @var \Drupal\Core\Asset\AssetCollectionOptimizerInterface
   */
  protected $cssCollectionOptimizer;

111 112 113 114 115 116 117
  /**
   * The config manager used to uninstall a theme.
   *
   * @var \Drupal\Core\Config\ConfigManagerInterface
   */
  protected $configManager;

118 119 120 121 122 123 124
  /**
   * The app root.
   *
   * @var string
   */
  protected $root;

125 126 127
  /**
   * Constructs a new ThemeHandler.
   *
128 129
   * @param string $root
   *   The app root.
130
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
131
   *   The config factory to get the installed themes.
132
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
133
   *   The module handler to fire themes_installed/themes_uninstalled hooks.
134 135
   * @param \Drupal\Core\State\StateInterface $state
   *   The state store.
136 137
   * @param \Drupal\Core\Extension\InfoParserInterface $info_parser
   *   The info parser to parse the theme.info.yml files.
138 139
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
140 141
   * @param \Drupal\Core\Asset\AssetCollectionOptimizerInterface $css_collection_optimizer
   *   The CSS asset collection optimizer service.
142 143 144 145
   * @param \Drupal\Core\Config\ConfigInstallerInterface $config_installer
   *   (optional) The config installer to install configuration. This optional
   *   to allow the theme handler to work before Drupal is installed and has a
   *   database.
146 147
   * @param \Drupal\Core\Config\ConfigManagerInterface $config_manager
   *   The config manager used to uninstall a theme.
148 149 150
   * @param \Drupal\Core\Routing\RouteBuilderInterface $route_builder
   *   (optional) The route builder service to rebuild the routes if a theme is
   *   installed.
151 152
   * @param \Drupal\Core\Extension\ExtensionDiscovery $extension_discovery
   *   (optional) A extension discovery instance (for unit tests).
153
   */
154
  public function __construct($root, ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, StateInterface $state, InfoParserInterface $info_parser,LoggerInterface $logger, AssetCollectionOptimizerInterface $css_collection_optimizer = NULL, ConfigInstallerInterface $config_installer = NULL, ConfigManagerInterface $config_manager = NULL, RouteBuilderInterface $route_builder = NULL, ExtensionDiscovery $extension_discovery = NULL) {
155
    $this->root = $root;
156 157
    $this->configFactory = $config_factory;
    $this->moduleHandler = $module_handler;
158
    $this->state = $state;
159
    $this->infoParser = $info_parser;
160
    $this->logger = $logger;
161
    $this->cssCollectionOptimizer = $css_collection_optimizer;
162
    $this->configInstaller = $config_installer;
163
    $this->configManager = $config_manager;
164
    $this->routeBuilder = $route_builder;
165
    $this->extensionDiscovery = $extension_discovery;
166 167 168 169 170
  }

  /**
   * {@inheritdoc}
   */
171 172 173 174 175 176 177 178
  public function getDefault() {
    return $this->configFactory->get('system.theme')->get('default');
  }

  /**
   * {@inheritdoc}
   */
  public function setDefault($name) {
179 180
    $list = $this->listInfo();
    if (!isset($list[$name])) {
181
      throw new \InvalidArgumentException("$name theme is not installed.");
182
    }
183
    $this->configFactory->getEditable('system.theme')
184 185 186 187 188 189 190 191
      ->set('default', $name)
      ->save();
    return $this;
  }

  /**
   * {@inheritdoc}
   */
192
  public function install(array $theme_list, $install_dependencies = TRUE) {
193
    $extension_config = $this->configFactory->getEditable('core.extension');
194 195 196

    $theme_data = $this->rebuildThemeData();

197
    if ($install_dependencies) {
198 199 200 201
      $theme_list = array_combine($theme_list, $theme_list);

      if ($missing = array_diff_key($theme_list, $theme_data)) {
        // One or more of the given themes doesn't exist.
202
        throw new \InvalidArgumentException(SafeMarkup::format('Unknown themes: !themes.', array(
203 204 205 206
          '!themes' => implode(', ', $missing),
        )));
      }

207
      // Only process themes that are not installed currently.
208 209
      $installed_themes = $extension_config->get('theme') ?: array();
      if (!$theme_list = array_diff_key($theme_list, $installed_themes)) {
210
        // Nothing to do. All themes already installed.
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
        return TRUE;
      }

      while (list($theme) = each($theme_list)) {
        // Add dependencies to the list. The new themes will be processed as
        // the while loop continues.
        foreach (array_keys($theme_data[$theme]->requires) as $dependency) {
          if (!isset($theme_data[$dependency])) {
            // The dependency does not exist.
            return FALSE;
          }

          // Skip already installed themes.
          if (!isset($theme_list[$dependency]) && !isset($installed_themes[$dependency])) {
            $theme_list[$dependency] = $dependency;
          }
        }
      }

      // Set the actual theme weights.
      $theme_list = array_map(function ($theme) use ($theme_data) {
        return $theme_data[$theme]->sort;
      }, $theme_list);

      // Sort the theme list by their weights (reverse).
      arsort($theme_list);
      $theme_list = array_keys($theme_list);
    }
    else {
      $installed_themes = $extension_config->get('theme') ?: array();
    }

243
    $themes_installed = array();
244
    foreach ($theme_list as $key) {
245 246 247
      // Only process themes that are not already installed.
      $installed = $extension_config->get("theme.$key") !== NULL;
      if ($installed) {
248 249 250
        continue;
      }

251 252
      // Throw an exception if the theme name is too long.
      if (strlen($key) > DRUPAL_EXTENSION_NAME_MAX_LENGTH) {
253
        throw new ExtensionNameLengthException(SafeMarkup::format('Theme name %name is over the maximum allowed length of @max characters.', array(
254 255 256 257 258
          '%name' => $key,
          '@max' => DRUPAL_EXTENSION_NAME_MAX_LENGTH,
        )));
      }

259 260
      // Validate default configuration of the theme. If there is existing
      // configuration then stop installing.
261
      $this->configInstaller->checkConfigurationToInstall('theme', $key);
262

263 264
      // The value is not used; the weight is ignored for themes currently. Do
      // not check schema when saving the configuration.
265 266
      $extension_config
        ->set("theme.$key", 0)
267
        ->save(TRUE);
268

269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
      // Add the theme to the current list.
      // @todo Remove all code that relies on $status property.
      $theme_data[$key]->status = 1;
      $this->addTheme($theme_data[$key]);

      // Update the current theme data accordingly.
      $current_theme_data = $this->state->get('system.theme.data', array());
      $current_theme_data[$key] = $theme_data[$key];
      $this->state->set('system.theme.data', $current_theme_data);

      // Reset theme settings.
      $theme_settings = &drupal_static('theme_get_setting');
      unset($theme_settings[$key]);

      // @todo Remove system_list().
      $this->systemListReset();

      // Only install default configuration if this theme has not been installed
      // already.
      if (!isset($installed_themes[$key])) {
        // Install default configuration of the theme.
        $this->configInstaller->installDefaultConfig('theme', $key);
291
      }
292

293
      $themes_installed[] = $key;
294

295 296
      // Record the fact that it was installed.
      $this->logger->info('%theme theme installed.', array('%theme' => $key));
297 298
    }

299
    $this->cssCollectionOptimizer->deleteAll();
300 301
    $this->resetSystem();

302 303
    // Invoke hook_themes_installed() after the themes have been installed.
    $this->moduleHandler->invokeAll('themes_installed', array($themes_installed));
304

305
    return !empty($themes_installed);
306 307 308 309 310
  }

  /**
   * {@inheritdoc}
   */
311
  public function uninstall(array $theme_list) {
312 313
    $extension_config = $this->configFactory->getEditable('core.extension');
    $theme_config = $this->configFactory->getEditable('system.theme');
314
    $list = $this->listInfo();
315
    foreach ($theme_list as $key) {
316
      if (!isset($list[$key])) {
317 318 319
        throw new \InvalidArgumentException("Unknown theme: $key.");
      }
      if ($key === $theme_config->get('default')) {
320
        throw new \InvalidArgumentException("The current default theme $key cannot be uninstalled.");
321 322
      }
      if ($key === $theme_config->get('admin')) {
323
        throw new \InvalidArgumentException("The current admin theme $key cannot be uninstalled.");
324
      }
325 326 327 328 329
      // Base themes cannot be uninstalled if sub themes are installed, and if
      // they are not uninstalled at the same time.
      // @todo https://www.drupal.org/node/474684 and
      //   https://www.drupal.org/node/1297856 themes should leverage the module
      //   dependency system.
330 331 332
      if (!empty($list[$key]->sub_themes)) {
        foreach ($list[$key]->sub_themes as $sub_key => $sub_label) {
          if (isset($list[$sub_key]) && !in_array($sub_key, $theme_list, TRUE)) {
333
            throw new \InvalidArgumentException("The base theme $key cannot be uninstalled, because theme $sub_key depends on it.");
334 335 336
          }
        }
      }
337 338
    }

339
    $this->cssCollectionOptimizer->deleteAll();
340
    $current_theme_data = $this->state->get('system.theme.data', array());
341 342
    foreach ($theme_list as $key) {
      // The value is not used; the weight is ignored for themes currently.
343
      $extension_config->clear("theme.$key");
344 345 346 347 348 349 350 351 352 353 354 355 356

      // Remove the theme from the current list.
      unset($this->list[$key]);

      // Update the current theme data accordingly.
      unset($current_theme_data[$key]);

      // Reset theme settings.
      $theme_settings = &drupal_static('theme_get_setting');
      unset($theme_settings[$key]);

      // @todo Remove system_list().
      $this->systemListReset();
357 358 359 360

      // Remove all configuration belonging to the theme.
      $this->configManager->uninstall('theme', $key);

361
    }
362 363 364
    // Don't check schema when uninstalling a theme since we are only clearing
    // keys.
    $extension_config->save(TRUE);
365
    $this->state->set('system.theme.data', $current_theme_data);
366 367 368

    $this->resetSystem();

369
    $this->moduleHandler->invokeAll('themes_uninstalled', [$theme_list]);
370 371 372 373 374 375
  }

  /**
   * {@inheritdoc}
   */
  public function listInfo() {
376
    if (!isset($this->list)) {
377
      $this->list = array();
378
      $themes = $this->systemThemeList();
379 380 381 382 383 384 385
      // @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());
      }
386 387
      foreach ($themes as $theme) {
        $this->addTheme($theme);
388
      }
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    }
    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;
  }
408

409 410 411 412 413 414
  /**
   * {@inheritdoc}
   */
  public function refreshInfo() {
    $this->reset();
    $extension_config = $this->configFactory->get('core.extension');
415
    $installed = $extension_config->get('theme');
416 417 418 419 420

    // @todo Avoid re-scanning all themes by retaining the original (unaltered)
    //   theme info somewhere.
    $list = $this->rebuildThemeData();
    foreach ($list as $name => $theme) {
421
      if (isset($installed[$name])) {
422
        $this->addTheme($theme);
423 424
      }
    }
425
    $this->state->set('system.theme.data', $this->list);
426 427 428 429 430 431 432
  }

  /**
   * {@inheritdoc}
   */
  public function reset() {
    $this->systemListReset();
433
    $this->list = NULL;
434 435 436 437 438 439
  }

  /**
   * {@inheritdoc}
   */
  public function rebuildThemeData() {
440 441 442
    $listing = $this->getExtensionDiscovery();
    $themes = $listing->scan('theme');
    $engines = $listing->scan('theme_engine');
443
    $extension_config = $this->configFactory->get('core.extension');
444
    $installed = $extension_config->get('theme') ?: array();
445 446 447 448 449 450 451 452 453

    // Set defaults for theme info.
    $defaults = array(
      'engine' => 'twig',
      'regions' => array(
        'sidebar_first' => 'Left sidebar',
        'sidebar_second' => 'Right sidebar',
        'content' => 'Content',
        'header' => 'Header',
454 455
        'primary_menu' => 'Primary menu',
        'secondary_menu' => 'Secondary menu',
456 457
        'footer' => 'Footer',
        'highlighted' => 'Highlighted',
458
        'messages' => 'Messages',
459 460 461
        'help' => 'Help',
        'page_top' => 'Page top',
        'page_bottom' => 'Page bottom',
462
        'breadcrumb' => 'Breadcrumb',
463 464 465 466 467
      ),
      'description' => '',
      'features' => $this->defaultFeatures,
      'screenshot' => 'screenshot.png',
      'php' => DRUPAL_MINIMUM_PHP,
468
      'libraries' => array(),
469 470 471
    );

    $sub_themes = array();
472
    $files = array();
473 474
    // Read info files for each theme.
    foreach ($themes as $key => $theme) {
475
      // @todo Remove all code that relies on the $status property.
476
      $theme->status = (int) isset($installed[$key]);
477

478
      $theme->info = $this->infoParser->parse($theme->getPathname()) + $defaults;
479 480 481

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

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

490
      if (!empty($theme->info['base theme'])) {
491
        $sub_themes[] = $key;
492 493
        // Add the base theme as a proper dependency.
        $themes[$key]->info['dependencies'][] = $themes[$key]->info['base theme'];
494 495
      }

496 497
      // Defaults to 'twig' (see $defaults above).
      $engine = $theme->info['engine'];
498
      if (isset($engines[$engine])) {
499
        $theme->owner = $engines[$engine]->getExtensionPathname();
500
        $theme->prefix = $engines[$engine]->getName();
501 502
      }

503
      // Prefix screenshot with theme path.
504
      if (!empty($theme->info['screenshot'])) {
505
        $theme->info['screenshot'] = $theme->getPath() . '/' . $theme->info['screenshot'];
506
      }
507 508

      $files[$key] = $theme->getPathname();
509
    }
510 511 512 513 514 515 516 517
    // Build dependencies.
    // @todo Move into a generic ExtensionHandler base class.
    // @see https://drupal.org/node/2208429
    $themes = $this->moduleHandler->buildModuleDependencies($themes);

    // Store filenames to allow system_list() and drupal_get_filename() to
    // retrieve them without having to scan the filesystem.
    $this->state->set('system.theme.files', $files);
518

519 520
    // After establishing the full list of available themes, fill in data for
    // sub-themes.
521
    foreach ($sub_themes as $key) {
522 523 524 525 526 527 528 529
      $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)) {
530 531
        continue;
      }
532 533 534 535 536
      // 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'];
537
      }
538 539 540 541 542
      // 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;
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
      }
    }

    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;
594
      return $this->doGetBaseThemes($themes, $base_key, $used_themes) + $current_base_theme;
595 596 597 598 599 600
    }
    // If we get here, then this is our parent theme.
    return $current_base_theme;
  }

  /**
601
   * Returns an extension discovery object.
602
   *
603 604
   * @return \Drupal\Core\Extension\ExtensionDiscovery
   *   The extension discovery object.
605
   */
606 607
  protected function getExtensionDiscovery() {
    if (!isset($this->extensionDiscovery)) {
608
      $this->extensionDiscovery = new ExtensionDiscovery($this->root);
609
    }
610
    return $this->extensionDiscovery;
611 612 613 614 615 616
  }

  /**
   * Resets some other systems like rebuilding the route information or caches.
   */
  protected function resetSystem() {
617 618
    if ($this->routeBuilder) {
      $this->routeBuilder->setRebuildNeeded();
619 620 621 622 623
    }
    $this->systemListReset();

    // @todo It feels wrong to have the requirement to clear the local tasks
    //   cache here.
624
    Cache::invalidateTags(array('local_task'));
625 626 627
    $this->themeRegistryRebuild();
  }

628 629 630 631 632 633
  /**
   * {@inheritdoc}
   */
  public function getName($theme) {
    $themes = $this->listInfo();
    if (!isset($themes[$theme])) {
634
      throw new \InvalidArgumentException(SafeMarkup::format('Requested the name of a non-existing theme @theme', array('@theme' => $theme)));
635
    }
636
    return SafeMarkup::checkPlain($themes[$theme]->info['name']);
637 638
  }

639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
  /**
   * Wraps system_list_reset().
   */
  protected function systemListReset() {
    system_list_reset();
  }

  /**
   * Wraps drupal_theme_rebuild().
   */
  protected function themeRegistryRebuild() {
    drupal_theme_rebuild();
  }

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

663 664 665 666 667 668
  /**
   * {@inheritdoc}
   */
  public function getThemeDirectories() {
    $dirs = array();
    foreach ($this->listInfo() as $name => $theme) {
669
      $dirs[$name] = $this->root . '/' . $theme->getPath();
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
    }
    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));
  }

693
}