ModuleHandler.php 36.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php

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

namespace Drupal\Core\Extension;

use Drupal\Component\Graph\Graph;
11
use Drupal\Component\Serialization\Yaml;
12 13
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Cache\CacheBackendInterface;
14
use Drupal\Core\Entity\Schema\EntitySchemaProviderInterface;
15
use Symfony\Component\DependencyInjection\ContainerInterface;
16 17

/**
18
 * Class that manages modules in a Drupal installation.
19 20 21 22 23 24 25 26 27 28 29 30 31
 */
class ModuleHandler implements ModuleHandlerInterface {

  /**
   * List of loaded files.
   *
   * @var array
   *   An associative array whose keys are file paths of loaded files, relative
   *   to the application's root directory.
   */
  protected $loadedFiles;

  /**
32
   * List of installed modules.
33
   *
34
   * @var \Drupal\Core\Extension\Extension[]
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
   */
  protected $moduleList;

  /**
   * Boolean indicating whether modules have been loaded.
   *
   * @var bool
   */
  protected $loaded = FALSE;

  /**
   * List of hook implementations keyed by hook name.
   *
   * @var array
   */
  protected $implementations;

  /**
   * Information returned by hook_hook_info() implementations.
   *
   * @var array
   */
  protected $hookInfo;

59 60 61 62 63 64 65 66 67 68 69 70 71 72
  /**
   * Cache backend for storing module hook implementation information.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cacheBackend;

  /**
   * Whether the cache needs to be written.
   *
   * @var bool
   */
  protected $cacheNeedsWriting = FALSE;

73 74 75 76 77 78 79 80 81 82 83
  /**
   * List of alter hook implementations keyed by hook name(s).
   *
   * @var array
   */
  protected $alterFunctions;

  /**
   * Constructs a ModuleHandler object.
   *
   * @param array $module_list
84
   *   An associative array whose keys are the names of installed modules and
85
   *   whose values are Extension class parameters. This is normally the
86
   *   %container.modules% parameter being set up by DrupalKernel.
87 88
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   Cache backend for storing module hook implementation information.
89 90
   *
   * @see \Drupal\Core\DrupalKernel
91
   * @see \Drupal\Core\CoreServiceProvider
92
   */
93
  public function __construct(array $module_list = array(), CacheBackendInterface $cache_backend) {
94 95 96 97
    $this->moduleList = array();
    foreach ($module_list as $name => $module) {
      $this->moduleList[$name] = new Extension($module['type'], $module['pathname'], $module['filename']);
    }
98
    $this->cacheBackend = $cache_backend;
99 100 101
  }

  /**
102
   * {@inheritdoc}
103 104 105 106 107 108 109
   */
  public function load($name) {
    if (isset($this->loadedFiles[$name])) {
      return TRUE;
    }

    if (isset($this->moduleList[$name])) {
110
      $this->moduleList[$name]->load();
111 112 113 114 115 116 117
      $this->loadedFiles[$name] = TRUE;
      return TRUE;
    }
    return FALSE;
  }

  /**
118
   * {@inheritdoc}
119 120 121
   */
  public function loadAll() {
    if (!$this->loaded) {
122 123
      foreach ($this->moduleList as $name => $module) {
        $this->load($name);
124 125 126 127 128 129
      }
      $this->loaded = TRUE;
    }
  }

  /**
130
   * {@inheritdoc}
131 132 133 134 135 136 137
   */
  public function reload() {
    $this->loaded = FALSE;
    $this->loadAll();
  }

  /**
138
   * {@inheritdoc}
139 140 141 142 143 144
   */
  public function isLoaded() {
    return $this->loaded;
  }

  /**
145
   * {@inheritdoc}
146 147 148 149 150
   */
  public function getModuleList() {
    return $this->moduleList;
  }

151 152 153 154 155 156 157 158 159 160
  /**
   * {@inheritdoc}
   */
  public function getModule($name) {
    if (isset($this->moduleList[$name])) {
      return $this->moduleList[$name];
    }
    throw new \InvalidArgumentException(sprintf('The module %s does not exist.', $name));
  }

161
  /**
162
   * {@inheritdoc}
163 164 165
   */
  public function setModuleList(array $module_list = array()) {
    $this->moduleList = $module_list;
166 167 168
    // Reset the implementations, so a new call triggers a reloading of the
    // available hooks.
    $this->resetImplementations();
169 170
  }

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
  /**
   * {@inheritdoc}
   */
  public function addModule($name, $path) {
    $this->add('module', $name, $path);
  }

  /**
   * {@inheritdoc}
   */
  public function addProfile($name, $path) {
    $this->add('profile', $name, $path);
  }

  /**
   * Adds a module or profile to the list of currently active modules.
   *
   * @param string $type
   *   The extension type; either 'module' or 'profile'.
   * @param string $name
   *   The module name; e.g., 'node'.
   * @param string $path
   *   The module path; e.g., 'core/modules/node'.
   */
  protected function add($type, $name, $path) {
    $pathname = "$path/$name.info.yml";
197
    $filename = file_exists(DRUPAL_ROOT . "/$path/$name.$type") ? "$name.$type" : NULL;
198 199 200 201
    $this->moduleList[$name] = new Extension($type, $pathname, $filename);
    $this->resetImplementations();
  }

202
  /**
203
   * {@inheritdoc}
204 205
   */
  public function buildModuleDependencies(array $modules) {
206
    foreach ($modules as $module) {
207
      $graph[$module->getName()]['edges'] = array();
208 209
      if (isset($module->info['dependencies']) && is_array($module->info['dependencies'])) {
        foreach ($module->info['dependencies'] as $dependency) {
210
          $dependency_data = static::parseDependency($dependency);
211
          $graph[$module->getName()]['edges'][$dependency_data['name']] = $dependency_data;
212 213 214 215 216 217 218 219 220 221 222 223 224 225
        }
      }
    }
    $graph_object = new Graph($graph);
    $graph = $graph_object->searchAndSort();
    foreach ($graph as $module_name => $data) {
      $modules[$module_name]->required_by = isset($data['reverse_paths']) ? $data['reverse_paths'] : array();
      $modules[$module_name]->requires = isset($data['paths']) ? $data['paths'] : array();
      $modules[$module_name]->sort = $data['weight'];
    }
    return $modules;
  }

  /**
226
   * {@inheritdoc}
227 228 229 230 231 232
   */
  public function moduleExists($module) {
    return isset($this->moduleList[$module]);
  }

  /**
233
   * {@inheritdoc}
234 235 236 237 238 239 240 241
   */
  public function loadAllIncludes($type, $name = NULL) {
    foreach ($this->moduleList as $module => $filename) {
      $this->loadInclude($module, $type, $name);
    }
  }

  /**
242
   * {@inheritdoc}
243 244 245 246 247 248 249 250
   */
  public function loadInclude($module, $type, $name = NULL) {
    if ($type == 'install') {
      // Make sure the installation API is available
      include_once DRUPAL_ROOT . '/core/includes/install.inc';
    }

    $name = $name ?: $module;
251
    if (isset($this->moduleList[$module])) {
252
      $file = DRUPAL_ROOT . '/' . $this->moduleList[$module]->getPath() . "/$name.$type";
253 254 255 256
      if (is_file($file)) {
        require_once $file;
        return $file;
      }
257 258 259 260 261
    }

    return FALSE;
  }

262
  /**
263
   * {@inheritdoc}
264 265
   */
  public function getHookInfo() {
266 267 268 269 270 271 272 273
    if (!isset($this->hookInfo)) {
      if ($cache = $this->cacheBackend->get('hook_info')) {
        $this->hookInfo = $cache->data;
      }
      else {
        $this->buildHookInfo();
        $this->cacheBackend->set('hook_info', $this->hookInfo);
      }
274
    }
275 276 277 278 279 280 281 282 283
    return $this->hookInfo;
  }

  /**
   * Builds hook_hook_info() information.
   *
   * @see \Drupal\Core\Extension\ModuleHandler::getHookInfo()
   */
  protected function buildHookInfo() {
284
    $this->hookInfo = array();
285 286
    // Make sure that the modules are loaded before checking.
    $this->reload();
287
    // $this->invokeAll() would cause an infinite recursion.
288 289 290 291 292 293 294 295 296 297 298
    foreach ($this->moduleList as $module => $filename) {
      $function = $module . '_hook_info';
      if (function_exists($function)) {
        $result = $function();
        if (isset($result) && is_array($result)) {
          $this->hookInfo = NestedArray::mergeDeep($this->hookInfo, $result);
        }
      }
    }
  }

299
  /**
300
   * {@inheritdoc}
301 302 303 304 305 306 307
   */
  public function getImplementations($hook) {
    $implementations = $this->getImplementationInfo($hook);
    return array_keys($implementations);
  }

  /**
308 309 310 311 312 313 314 315 316 317 318
   * {@inheritdoc}
   */
  public function writeCache() {
    if ($this->cacheNeedsWriting) {
      $this->cacheBackend->set('module_implements', $this->implementations);
      $this->cacheNeedsWriting = FALSE;
    }
  }

  /**
   * {@inheritdoc}
319 320 321 322 323
   */
  public function resetImplementations() {
    $this->implementations = NULL;
    $this->hookInfo = NULL;
    $this->alterFunctions = NULL;
324 325 326 327 328 329 330 331 332 333 334 335 336
    // We maintain a persistent cache of hook implementations in addition to the
    // static cache to avoid looping through every module and every hook on each
    // request. Benchmarks show that the benefit of this caching outweighs the
    // additional database hit even when using the default database caching
    // backend and only a small number of modules are enabled. The cost of the
    // $this->cacheBackend->get() is more or less constant and reduced further
    // when non-database caching backends are used, so there will be more
    // significant gains when a large number of modules are installed or hooks
    // invoked, since this can quickly lead to
    // \Drupal::moduleHandler()->implementsHook() being called several thousand
    // times per request.
    $this->cacheBackend->set('module_implements', array());
    $this->cacheBackend->delete('hook_info');
337 338 339
  }

  /**
340
   * {@inheritdoc}
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
   */
  public function implementsHook($module, $hook) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      return TRUE;
    }
    // If the hook implementation does not exist, check whether it lives in an
    // optional include file registered via hook_hook_info().
    $hook_info = $this->getHookInfo();
    if (isset($hook_info[$hook]['group'])) {
      $this->loadInclude($module, 'inc', $module . '.' . $hook_info[$hook]['group']);
      if (function_exists($function)) {
        return TRUE;
      }
    }
    return FALSE;
  }

359
  /**
360
   * {@inheritdoc}
361
   */
362
  public function invoke($module, $hook, array $args = array()) {
363 364 365 366 367 368 369
    if (!$this->implementsHook($module, $hook)) {
      return;
    }
    $function = $module . '_' . $hook;
    return call_user_func_array($function, $args);
  }

370
  /**
371
   * {@inheritdoc}
372
   */
373
  public function invokeAll($hook, array $args = array()) {
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
    $return = array();
    $implementations = $this->getImplementations($hook);
    foreach ($implementations as $module) {
      $function = $module . '_' . $hook;
      if (function_exists($function)) {
        $result = call_user_func_array($function, $args);
        if (isset($result) && is_array($result)) {
          $return = NestedArray::mergeDeep($return, $result);
        }
        elseif (isset($result)) {
          $return[] = $result;
        }
      }
    }

    return $return;
  }

  /**
393
   * {@inheritdoc}
394 395 396 397 398 399 400 401 402 403 404
   */
  public function alter($type, &$data, &$context1 = NULL, &$context2 = NULL) {
    // Most of the time, $type is passed as a string, so for performance,
    // normalize it to that. When passed as an array, usually the first item in
    // the array is a generic type, and additional items in the array are more
    // specific variants of it, as in the case of array('form', 'form_FORM_ID').
    if (is_array($type)) {
      $cid = implode(',', $type);
      $extra_types = $type;
      $type = array_shift($extra_types);
      // Allow if statements in this function to use the faster isset() rather
405 406
      // than !empty() both when $type is passed as a string, or as an array
      // with one item.
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
      if (empty($extra_types)) {
        unset($extra_types);
      }
    }
    else {
      $cid = $type;
    }

    // Some alter hooks are invoked many times per page request, so store the
    // list of functions to call, and on subsequent calls, iterate through them
    // quickly.
    if (!isset($this->alterFunctions[$cid])) {
      $this->alterFunctions[$cid] = array();
      $hook = $type . '_alter';
      $modules = $this->getImplementations($hook);
      if (!isset($extra_types)) {
        // For the more common case of a single hook, we do not need to call
424 425
        // function_exists(), since $this->getImplementations() returns only
        // modules with implementations.
426 427 428 429 430 431 432 433 434 435 436 437 438
        foreach ($modules as $module) {
          $this->alterFunctions[$cid][] = $module . '_' . $hook;
        }
      }
      else {
        // For multiple hooks, we need $modules to contain every module that
        // implements at least one of them.
        $extra_modules = array();
        foreach ($extra_types as $extra_type) {
          $extra_modules = array_merge($extra_modules, $this->getImplementations($extra_type . '_alter'));
        }
        // If any modules implement one of the extra hooks that do not implement
        // the primary hook, we need to add them to the $modules array in their
439 440 441 442 443
        // appropriate order. $this->getImplementations() can only return
        // ordered implementations of a single hook. To get the ordered
        // implementations of multiple hooks, we mimic the
        // $this->getImplementations() logic of first ordering by
        // $this->getModuleList(), and then calling
444 445 446 447
        // $this->alter('module_implements').
        if (array_diff($extra_modules, $modules)) {
          // Merge the arrays and order by getModuleList().
          $modules = array_intersect(array_keys($this->moduleList), array_merge($modules, $extra_modules));
448 449 450
          // Since $this->getImplementations() already took care of loading the
          // necessary include files, we can safely pass FALSE for the array
          // values.
451 452 453
          $implementations = array_fill_keys($modules, FALSE);
          // Let modules adjust the order solely based on the primary hook. This
          // ensures the same module order regardless of whether this if block
454 455 456
          // runs. Calling $this->alter() recursively in this way does not
          // result in an infinite loop, because this call is for a single
          // $type, so we won't end up in this code block again.
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
          $this->alter('module_implements', $implementations, $hook);
          $modules = array_keys($implementations);
        }
        foreach ($modules as $module) {
          // Since $modules is a merged array, for any given module, we do not
          // know whether it has any particular implementation, so we need a
          // function_exists().
          $function = $module . '_' . $hook;
          if (function_exists($function)) {
            $this->alterFunctions[$cid][] = $function;
          }
          foreach ($extra_types as $extra_type) {
            $function = $module . '_' . $extra_type . '_alter';
            if (function_exists($function)) {
              $this->alterFunctions[$cid][] = $function;
            }
          }
        }
      }
      // Allow the theme to alter variables after the theme system has been
      // initialized.
      global $theme, $base_theme_info;
      if (isset($theme)) {
        $theme_keys = array();
        foreach ($base_theme_info as $base) {
482
          $theme_keys[] = $base->getName();
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
        }
        $theme_keys[] = $theme;
        foreach ($theme_keys as $theme_key) {
          $function = $theme_key . '_' . $hook;
          if (function_exists($function)) {
            $this->alterFunctions[$cid][] = $function;
          }
          if (isset($extra_types)) {
            foreach ($extra_types as $extra_type) {
              $function = $theme_key . '_' . $extra_type . '_alter';
              if (function_exists($function)) {
                $this->alterFunctions[$cid][] = $function;
              }
            }
          }
        }
      }
    }

    foreach ($this->alterFunctions[$cid] as $function) {
      $function($data, $context1, $context2);
    }
  }

  /**
   * Provides information about modules' implementations of a hook.
   *
   * @param string $hook
   *   The name of the hook (e.g. "help" or "menu").
   *
   * @return array
   *   An array whose keys are the names of the modules which are implementing
   *   this hook and whose values are either an array of information from
   *   hook_hook_info() or FALSE if the implementation is in the module file.
   */
  protected function getImplementationInfo($hook) {
519 520 521 522 523 524 525 526 527 528 529
    if (!isset($this->implementations)) {
      $this->implementations = array();
      if ($cache = $this->cacheBackend->get('module_implements')) {
        $this->implementations = $cache->data;
      }
    }
    if (!isset($this->implementations[$hook])) {
      // The hook is not cached, so ensure that whether or not it has
      // implementations, the cache is updated at the end of the request.
      $this->cacheNeedsWriting = TRUE;
      $this->implementations[$hook] = $this->buildImplementationInfo($hook);
530
    }
531 532 533 534 535 536 537 538 539 540 541 542 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
    else {
      foreach ($this->implementations[$hook] as $module => $group) {
        // If this hook implementation is stored in a lazy-loaded file, include
        // that file first.
        if ($group) {
          $this->loadInclude($module, 'inc', "$module.$group");
        }
        // It is possible that a module removed a hook implementation without
        // the implementations cache being rebuilt yet, so we check whether the
        // function exists on each request to avoid undefined function errors.
        // Since ModuleHandler::implementsHook() may needlessly try to
        // load the include file again, function_exists() is used directly here.
        if (!function_exists($module . '_' . $hook)) {
          // Clear out the stale implementation from the cache and force a cache
          // refresh to forget about no longer existing hook implementations.
          unset($this->implementations[$hook][$module]);
          $this->cacheNeedsWriting = TRUE;
        }
      }
    }
    return $this->implementations[$hook];
  }

  /**
   * Builds hook implementation information for a given hook name.
   *
   * @param string $hook
   *   The name of the hook (e.g. "help" or "menu").
   *
   * @return array
   *   An array whose keys are the names of the modules which are implementing
   *   this hook and whose values are either an array of information from
   *   hook_hook_info() or FALSE if the implementation is in the module file.
   *
   * @see \Drupal\Core\Extension\ModuleHandler::getImplementationInfo()
   */
  protected function buildImplementationInfo($hook) {
568 569 570 571
    $this->implementations[$hook] = array();
    $hook_info = $this->getHookInfo();
    foreach ($this->moduleList as $module => $filename) {
      $include_file = isset($hook_info[$hook]['group']) && $this->loadInclude($module, 'inc', $module . '.' . $hook_info[$hook]['group']);
572
      // Since $this->implementsHook() may needlessly try to load the include
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
      // file again, function_exists() is used directly here.
      if (function_exists($module . '_' . $hook)) {
        $this->implementations[$hook][$module] = $include_file ? $hook_info[$hook]['group'] : FALSE;
      }
    }
    // Allow modules to change the weight of specific implementations but avoid
    // an infinite loop.
    if ($hook != 'module_implements_alter') {
      $this->alter('module_implements', $this->implementations[$hook], $hook);
    }
    return $this->implementations[$hook];
  }

  /**
   * Parses a dependency for comparison by drupal_check_incompatibility().
   *
   * @param $dependency
   *   A dependency string, for example 'foo (>=8.x-4.5-beta5, 3.x)'.
   *
   * @return
   *   An associative array with three keys:
   *   - 'name' includes the name of the thing to depend on (e.g. 'foo').
   *   - 'original_version' contains the original version string (which can be
   *     used in the UI for reporting incompatibilities).
   *   - 'versions' is a list of associative arrays, each containing the keys
   *     'op' and 'version'. 'op' can be one of: '=', '==', '!=', '<>', '<',
   *     '<=', '>', or '>='. 'version' is one piece like '4.5-beta3'.
   *   Callers should pass this structure to drupal_check_incompatibility().
   *
   * @see drupal_check_incompatibility()
   */
604
  public static function parseDependency($dependency) {
605 606
    // We use named subpatterns and support every op that version_compare
    // supports. Also, op is optional and defaults to equals.
607
    $p_op = '(?<operation>!=|==|=|<|<=|>|>=|<>)?';
608
    // Core version is always optional: 8.x-2.x and 2.x is treated the same.
609
    $p_core = '(?:' . preg_quote(\Drupal::CORE_COMPATIBILITY) . '-)?';
610
    $p_major = '(?<major>\d+)';
611
    // By setting the minor version to x, branches can be matched.
612
    $p_minor = '(?<minor>(?:\d+|x)(?:-[A-Za-z]+\d+)?)';
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
    $value = array();
    $parts = explode('(', $dependency, 2);
    $value['name'] = trim($parts[0]);
    if (isset($parts[1])) {
      $value['original_version'] = ' (' . $parts[1];
      foreach (explode(',', $parts[1]) as $version) {
        if (preg_match("/^\s*$p_op\s*$p_core$p_major\.$p_minor/", $version, $matches)) {
          $op = !empty($matches['operation']) ? $matches['operation'] : '=';
          if ($matches['minor'] == 'x') {
            // Drupal considers "2.x" to mean any version that begins with
            // "2" (e.g. 2.0, 2.9 are all "2.x"). PHP's version_compare(),
            // on the other hand, treats "x" as a string; so to
            // version_compare(), "2.x" is considered less than 2.0. This
            // means that >=2.x and <2.x are handled by version_compare()
            // as we need, but > and <= are not.
            if ($op == '>' || $op == '<=') {
              $matches['major']++;
            }
            // Equivalence can be checked by adding two restrictions.
            if ($op == '=' || $op == '==') {
              $value['versions'][] = array('op' => '<', 'version' => ($matches['major'] + 1) . '.x');
              $op = '>=';
            }
          }
          $value['versions'][] = array('op' => $op, 'version' => $matches['major'] . '.' . $matches['minor']);
        }
      }
    }
    return $value;
  }
643 644 645 646

  /**
   * {@inheritdoc}
   */
647
  public function install(array $module_list, $enable_dependencies = TRUE) {
648
    $extension_config = \Drupal::config('core.extension');
649 650 651
    if ($enable_dependencies) {
      // Get all module data so we can find dependencies and sort.
      $module_data = system_rebuild_module_data();
652 653 654 655 656
      $module_list = $module_list ? array_combine($module_list, $module_list) : array();
      if (array_diff_key($module_list, $module_data)) {
        // One or more of the given modules doesn't exist.
        return FALSE;
      }
657

658
      // Only process currently uninstalled modules.
659
      $installed_modules = $extension_config->get('module') ?: array();
660 661 662 663
      if (!$module_list = array_diff_key($module_list, $installed_modules)) {
        // Nothing to do. All modules already installed.
        return TRUE;
      }
664

665 666 667 668 669 670 671 672
      // Add dependencies to the list. The new modules will be processed as
      // the while loop continues.
      while (list($module) = each($module_list)) {
        foreach (array_keys($module_data[$module]->requires) as $dependency) {
          if (!isset($module_data[$dependency])) {
            // The dependency does not exist.
            return FALSE;
          }
673

674 675 676
          // Skip already installed modules.
          if (!isset($module_list[$dependency]) && !isset($installed_modules[$dependency])) {
            $module_list[$dependency] = $dependency;
677 678 679 680
          }
        }
      }

681 682 683 684
      // Set the actual module weights.
      $module_list = array_map(function ($module) use ($module_data) {
        return $module_data[$module]->sort;
      }, $module_list);
685

686
      // Sort the module list by their weights (reverse).
687 688 689 690 691 692 693
      arsort($module_list);
      $module_list = array_keys($module_list);
    }

    // Required for module installation checks.
    include_once DRUPAL_ROOT . '/core/includes/install.inc';

694 695 696 697 698 699
    /** @var \Drupal\Core\Config\ConfigInstaller $config_installer */
    $config_installer = \Drupal::service('config.installer');
    $sync_status = $config_installer->isSyncing();
    if ($sync_status) {
      $source_storage = $config_installer->getSourceStorage();
    }
700 701
    $modules_installed = array();
    foreach ($module_list as $module) {
702
      $enabled = $extension_config->get("module.$module") !== NULL;
703
      if (!$enabled) {
704 705 706 707 708 709
        // Throw an exception if the module name is too long.
        if (strlen($module) > DRUPAL_EXTENSION_NAME_MAX_LENGTH) {
          throw new ExtensionNameLengthException(format_string('Module name %name is over the maximum allowed length of @max characters.', array(
            '%name' => $module,
            '@max' => DRUPAL_EXTENSION_NAME_MAX_LENGTH,
          )));
710
        }
711

712 713 714
        $extension_config
          ->set("module.$module", 0)
          ->set('module', module_config_sort($extension_config->get('module')))
715 716 717
          ->save();

        // Prepare the new module list, sorted by weight, including filenames.
718 719 720 721 722 723 724 725 726
        // This list is used for both the ModuleHandler and DrupalKernel. It
        // needs to be kept in sync between both. A DrupalKernel reboot or
        // rebuild will automatically re-instantiate a new ModuleHandler that
        // uses the new module list of the kernel. However, DrupalKernel does
        // not cause any modules to be loaded.
        // Furthermore, the currently active (fixed) module list can be
        // different from the configured list of enabled modules. For all active
        // modules not contained in the configured enabled modules, we assume a
        // weight of 0.
727 728
        $current_module_filenames = $this->getModuleList();
        $current_modules = array_fill_keys(array_keys($current_module_filenames), 0);
729
        $current_modules = module_config_sort(array_merge($current_modules, $extension_config->get('module')));
730 731 732
        $module_filenames = array();
        foreach ($current_modules as $name => $weight) {
          if (isset($current_module_filenames[$name])) {
733
            $module_filenames[$name] = $current_module_filenames[$name];
734 735
          }
          else {
736 737 738 739
            $module_path = drupal_get_path('module', $name);
            $pathname = "$module_path/$name.info.yml";
            $filename = file_exists($module_path . "/$name.module") ? "$name.module" : NULL;
            $module_filenames[$name] = new Extension('module', $pathname, $filename);
740 741 742 743
          }
        }

        // Update the module handler in order to load the module's code.
744 745 746 747
        // This allows the module to participate in hooks and its existence to
        // be discovered by other modules.
        // The current ModuleHandler instance is obsolete with the kernel
        // rebuild below.
748 749 750 751
        $this->setModuleList($module_filenames);
        $this->load($module);
        module_load_install($module);

752 753 754 755
        // Clear the static cache of system_rebuild_module_data() to pick up the
        // new module, since it merges the installation status of modules into
        // its statically cached list.
        drupal_static_reset('system_rebuild_module_data');
756 757 758 759

        // Update the kernel to include it.
        // This reboots the kernel to register the module's bundle and its
        // services in the service container. The $module_filenames argument is
760 761
        // taken over as %container.modules% parameter, which is passed to a
        // fresh ModuleHandler instance upon first retrieval.
762
        // @todo install_begin_request() creates a container without a kernel.
763
        if ($kernel = \Drupal::service('kernel', ContainerInterface::NULL_ON_INVALID_REFERENCE)) {
764 765 766 767 768 769 770
          $kernel->updateModules($module_filenames, $module_filenames);
        }

        // Refresh the schema to include it.
        drupal_get_schema(NULL, TRUE);

        // Allow modules to react prior to the installation of a module.
771
        $this->invokeAll('module_preinstall', array($module));
772

773 774
        // Now install the module's schema if necessary.
        drupal_install_schema($module);
775

776 777 778
        // Clear plugin manager caches.
        \Drupal::getContainer()->get('plugin.cache_clearer')->clearCachedDefinitions();

779 780 781
        // Set the schema version to the number of the last update provided by
        // the module, or the minimum core schema version.
        $version = \Drupal::CORE_MINIMUM_SCHEMA_VERSION;
782
        $versions = drupal_get_schema_versions($module);
783 784 785
        if ($versions) {
          $version = max(max($versions), $version);
        }
786

787
        // Install default configuration of the module.
788 789 790 791 792 793 794 795 796 797 798 799
        $config_installer = \Drupal::service('config.installer');
        if ($sync_status) {
          $config_installer
            ->setSyncing(TRUE)
            ->setSourceStorage($source_storage);
        }
        else {
          // If we're not in a config synchronisation reset the source storage
          // so that the extension install storage will pick up the new
          // configuration.
          $config_installer->resetSourceStorage();
        }
800
        \Drupal::service('config.installer')->installDefaultConfig('module', $module);
801

802 803 804 805 806
        // If the module has no current updates, but has some that were
        // previously removed, set the version to the value of
        // hook_update_last_removed().
        if ($last_removed = $this->invoke($module, 'update_last_removed')) {
          $version = max($version, $last_removed);
807
        }
808
        drupal_set_installed_schema_version($module, $version);
809

810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
        // Install any entity schemas belonging to the module.
        $entity_manager = \Drupal::entityManager();
        $schema = \Drupal::database()->schema();
        foreach ($entity_manager->getDefinitions() as $entity_type) {
          if ($entity_type->getProvider() == $module) {
            $storage = $entity_manager->getStorage($entity_type->id());
            if ($storage instanceof EntitySchemaProviderInterface) {
              foreach ($storage->getSchema() as $table_name => $table_schema) {
                if (!$schema->tableExists($table_name)) {
                  $schema->createTable($table_name, $table_schema);
                }
              }
            }
          }
        }

826 827
        // Record the fact that it was installed.
        $modules_installed[] = $module;
828

829 830 831 832 833 834 835 836 837
        // Update the theme registry to include it.
        drupal_theme_rebuild();

        // Modules can alter theme info, so refresh theme data.
        // @todo ThemeHandler cannot be injected into ModuleHandler, since that
        //   causes a circular service dependency.
        // @see https://drupal.org/node/2208429
        \Drupal::service('theme_handler')->refreshInfo();

838 839
        // Allow the module to perform install tasks.
        $this->invoke($module, 'install');
840

841 842
        // Record the fact that it was installed.
        watchdog('system', '%module module installed.', array('%module' => $module), WATCHDOG_INFO);
843 844 845 846 847 848 849 850 851 852 853 854 855 856
      }
    }

    // If any modules were newly installed, invoke hook_modules_installed().
    if (!empty($modules_installed)) {
      $this->invokeAll('modules_installed', array($modules_installed));
    }

    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
857 858 859 860 861 862 863 864
  public function uninstall(array $module_list, $uninstall_dependents = TRUE) {
    // Get all module data so we can find dependencies and sort.
    $module_data = system_rebuild_module_data();
    $module_list = $module_list ? array_combine($module_list, $module_list) : array();
    if (array_diff_key($module_list, $module_data)) {
      // One or more of the given modules doesn't exist.
      return FALSE;
    }
865

866
    // Only process currently installed modules.
867 868
    $extension_config = \Drupal::config('core.extension');
    $installed_modules = $extension_config->get('module') ?: array();
869 870 871 872 873 874 875 876
    if (!$module_list = array_intersect_key($module_list, $installed_modules)) {
      // Nothing to do. All modules already uninstalled.
      return TRUE;
    }

    if ($uninstall_dependents) {
      // Add dependent modules to the list. The new modules will be processed as
      // the while loop continues.
877 878
      $profile = drupal_get_profile();
      while (list($module) = each($module_list)) {
879 880 881 882 883
        foreach (array_keys($module_data[$module]->required_by) as $dependent) {
          if (!isset($module_data[$dependent])) {
            // The dependent module does not exist.
            return FALSE;
          }
884

885 886
          // Skip already uninstalled modules.
          if (isset($installed_modules[$dependent]) && !isset($module_list[$dependent]) && $dependent != $profile) {
887
            $module_list[$dependent] = $dependent;
888 889 890 891 892
          }
        }
      }
    }

893 894 895 896
    // Set the actual module weights.
    $module_list = array_map(function ($module) use ($module_data) {
      return $module_data[$module]->sort;
    }, $module_list);
897

898 899 900 901 902 903 904 905 906
    // Sort the module list by their weights.
    asort($module_list);
    $module_list = array_keys($module_list);

    // Only process modules that are enabled. A module is only enabled if it is
    // configured as enabled. Custom or overridden module handlers might contain
    // the module already, which means that it might be loaded, but not
    // necessarily installed.
    $schema_store = \Drupal::keyValue('system.schema');
907
    foreach ($module_list as $module) {
908 909
      // Allow modules to react prior to the uninstallation of a module.
      $this->invokeAll('module_preuninstall', array($module));
910

911 912 913
      // Uninstall the module.
      module_load_install($module);
      $this->invoke($module, 'uninstall');
914 915 916 917

      // Remove all configuration belonging to the module.
      \Drupal::service('config.manager')->uninstall('module', $module);

918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
      // Remove any entity schemas belonging to the module.
      $entity_manager = \Drupal::entityManager();
      $schema = \Drupal::database()->schema();
      foreach ($entity_manager->getDefinitions() as $entity_type) {
        if ($entity_type->getProvider() == $module) {
          $storage = $entity_manager->getStorage($entity_type->id());
          if ($storage instanceof EntitySchemaProviderInterface) {
            foreach ($storage->getSchema() as $table_name => $table_schema) {
              if ($schema->tableExists($table_name)) {
                $schema->dropTable($table_name);
              }
            }
          }
        }
      }

934
      // Remove the schema.
935
      drupal_uninstall_schema($module);
936

937
      // Remove the module's entry from the config.
938
      $extension_config->clear("module.$module")->save();
939

940 941 942 943 944 945
      // Update the module handler to remove the module.
      // The current ModuleHandler instance is obsolete with the kernel rebuild
      // below.
      $module_filenames = $this->getModuleList();
      unset($module_filenames[$module]);
      $this->setModuleList($module_filenames);
946

947 948 949
      // Remove any potential cache bins provided by the module.
      $this->removeCacheBins($module);

950 951 952 953
      // Clear the static cache of system_rebuild_module_data() to pick up the
      // new module, since it merges the installation status of modules into
      // its statically cached list.
      drupal_static_reset('system_rebuild_module_data');
954

955
      \Drupal::getContainer()->get('plugin.cache_clearer')->clearCachedDefinitions();
956

957 958
      // Update the kernel to exclude the uninstalled modules.
      \Drupal::service('kernel')->updateModules($module_filenames, $module_filenames);
959

960
      // Update the theme registry to remove the newly uninstalled module.
961 962
      drupal_theme_rebuild();

963 964 965 966 967 968
      // Modules can alter theme info, so refresh theme data.
      // @todo ThemeHandler cannot be injected into ModuleHandler, since that
      //   causes a circular service dependency.
      // @see https://drupal.org/node/2208429
      \Drupal::service('theme_handler')->refreshInfo();

969
      watchdog('system', '%module module uninstalled.', array('%module' => $module), WATCHDOG_INFO);
970

971
      $schema_store->delete($module);
972
    }
973
    drupal_get_installed_schema_version(NULL, TRUE);
974

975 976
    // Let other modules react.
    $this->invokeAll('modules_uninstalled', array($module_list));
977

978 979 980 981
    drupal_flush_all_caches();

    return TRUE;
  }
982

983 984 985 986 987 988 989 990 991 992
  /**
   * Helper method for removing all cache bins registered by a given module.
   *
   * @param string $module
   *   The name of the module for which to remove all registered cache bins.
   */
  protected function removeCacheBins($module) {
    // Remove any cache bins defined by a module.
    $service_yaml_file = drupal_get_path('module', $module) . "/$module.services.yml";
    if (file_exists($service_yaml_file)) {
993
      $definitions = Yaml::decode(file_get_contents($service_yaml_file));
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
      if (isset($definitions['services'])) {
        foreach ($definitions['services'] as $id => $definition) {
          if (isset($definition['tags'])) {
            foreach ($definition['tags'] as $tag) {
              // This works for the default cache registration and even in some
              // cases when a non-default "super" factory is used. That should
              // be extremely rare.
              if ($tag['name'] == 'cache.bin' && isset($definition['factory_service']) && isset($definition['factory_method']) && !empty($definition['arguments'])) {
                try {
                  $factory = \Drupal::service($definition['factory_service']);
                  if (method_exists($factory, $definition['factory_method'])) {
                    $backend = call_user_func_array(array($factory, $definition['factory_method']), $definition['arguments']);
                    if ($backend instanceof CacheBackendInterface) {
                      $backend->removeBin();
1008 1009
                    }
                  }
1010 1011 1012
                }
                catch (\Exception $e) {
                  watchdog_exception('system', $e, 'Failed to remove cache bin defined by the service %id.', array('%id' => $id));
1013 1014 1015 1016 1017 1018 1019 1020 1021
                }
              }
            }
          }
        }
      }
    }
  }

1022 1023 1024 1025 1026
  /**
   * {@inheritdoc}
   */
  public function getModuleDirectories() {
    $dirs = array();
1027 1028
    foreach ($this->getModuleList() as $name => $module) {
      $dirs[$name] = DRUPAL_ROOT . '/' . $module->getPath();
1029 1030 1031
    }
    return $dirs;
  }
1032

1033
}