ThemeHandler.php 13.8 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 36 37 38
 */
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
   */
39
  protected $list;
40 41

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

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

  /**
56
   * The state backend.
57
   *
58
   * @var \Drupal\Core\State\StateInterface
59
   */
60
  protected $state;
61

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

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

76 77 78 79 80 81 82
  /**
   * A logger instance.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

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

  /**
91
   * An extension discovery instance.
92
   *
93
   * @var \Drupal\Core\Extension\ExtensionDiscovery
94
   */
95
  protected $extensionDiscovery;
96

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

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

111 112 113 114 115 116 117
  /**
   * The app root.
   *
   * @var string
   */
  protected $root;

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

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

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

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

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

  /**
   * {@inheritdoc}
   */
  public function listInfo() {
186
    if (!isset($this->list)) {
187
      $this->list = array();
188
      $themes = $this->systemThemeList();
189 190 191 192 193 194 195
      // @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());
      }
196 197
      foreach ($themes as $theme) {
        $this->addTheme($theme);
198
      }
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    }
    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;
  }
218

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

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

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

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

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

    $sub_themes = array();
281 282
    $files_theme = array();
    $files_theme_engine = array();
283 284
    // Read info files for each theme.
    foreach ($themes as $key => $theme) {
285
      // @todo Remove all code that relies on the $status property.
286
      $theme->status = (int) isset($installed[$key]);
287

288
      $theme->info = $this->infoParser->parse($theme->getPathname()) + $defaults;
289 290 291

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

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

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

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

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

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

    // Store filenames to allow system_list() and drupal_get_filename() to
327 328 329 330
    // 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);
331

332 333
    // After establishing the full list of available themes, fill in data for
    // sub-themes.
334
    foreach ($sub_themes as $key) {
335 336 337 338 339 340 341 342
      $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)) {
343 344
        continue;
      }
345 346 347 348 349
      // 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'];
350
      }
351 352 353 354 355
      // 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;
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 404 405 406
      }
    }

    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;
407
      return $this->doGetBaseThemes($themes, $base_key, $used_themes) + $current_base_theme;
408 409 410 411 412 413
    }
    // If we get here, then this is our parent theme.
    return $current_base_theme;
  }

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

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

437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
  /**
   * 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');
  }

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

484
}