ThemeHandler.php 13.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\Core\Config\ConfigFactoryInterface;
11
use Drupal\Core\State\StateInterface;
12 13

/**
14
 * Default theme handler using the config system to store installation statuses.
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
 */
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
   */
35
  protected $list;
36 37

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // @todo Avoid re-scanning all themes by retaining the original (unaltered)
    //   theme info somewhere.
    $list = $this->rebuildThemeData();
    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 236 237 238
  }

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

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

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

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

284
      $theme->info = $this->infoParser->parse($theme->getPathname()) + $defaults;
285 286 287

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

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

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

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

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

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

    // Store filenames to allow system_list() and drupal_get_filename() to
323 324 325 326
    // 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);
327

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

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

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

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

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
  /**
   * 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');
  }

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

480
}