Chris@0: root = $root; Chris@0: $this->moduleHandler = $module_handler; Chris@0: $this->kernel = $kernel; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function addUninstallValidator(ModuleUninstallValidatorInterface $uninstall_validator) { Chris@0: $this->uninstallValidators[] = $uninstall_validator; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function install(array $module_list, $enable_dependencies = TRUE) { Chris@0: $extension_config = \Drupal::configFactory()->getEditable('core.extension'); Chris@0: if ($enable_dependencies) { Chris@0: // Get all module data so we can find dependencies and sort. Chris@0: $module_data = system_rebuild_module_data(); Chris@0: $module_list = $module_list ? array_combine($module_list, $module_list) : []; Chris@0: if ($missing_modules = array_diff_key($module_list, $module_data)) { Chris@0: // One or more of the given modules doesn't exist. Chris@0: throw new MissingDependencyException(sprintf('Unable to install modules %s due to missing modules %s.', implode(', ', $module_list), implode(', ', $missing_modules))); Chris@0: } Chris@0: Chris@0: // Only process currently uninstalled modules. Chris@0: $installed_modules = $extension_config->get('module') ?: []; Chris@0: if (!$module_list = array_diff_key($module_list, $installed_modules)) { Chris@0: // Nothing to do. All modules already installed. Chris@0: return TRUE; Chris@0: } Chris@0: Chris@0: // Add dependencies to the list. The new modules will be processed as Chris@14: // the foreach loop continues. Chris@14: foreach ($module_list as $module => $value) { Chris@0: foreach (array_keys($module_data[$module]->requires) as $dependency) { Chris@0: if (!isset($module_data[$dependency])) { Chris@0: // The dependency does not exist. Chris@0: throw new MissingDependencyException("Unable to install modules: module '$module' is missing its dependency module $dependency."); Chris@0: } Chris@0: Chris@0: // Skip already installed modules. Chris@0: if (!isset($module_list[$dependency]) && !isset($installed_modules[$dependency])) { Chris@0: $module_list[$dependency] = $dependency; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: // Set the actual module weights. Chris@0: $module_list = array_map(function ($module) use ($module_data) { Chris@0: return $module_data[$module]->sort; Chris@0: }, $module_list); Chris@0: Chris@0: // Sort the module list by their weights (reverse). Chris@0: arsort($module_list); Chris@0: $module_list = array_keys($module_list); Chris@0: } Chris@0: Chris@0: // Required for module installation checks. Chris@0: include_once $this->root . '/core/includes/install.inc'; Chris@0: Chris@0: /** @var \Drupal\Core\Config\ConfigInstaller $config_installer */ Chris@0: $config_installer = \Drupal::service('config.installer'); Chris@0: $sync_status = $config_installer->isSyncing(); Chris@0: if ($sync_status) { Chris@0: $source_storage = $config_installer->getSourceStorage(); Chris@0: } Chris@0: $modules_installed = []; Chris@0: foreach ($module_list as $module) { Chris@0: $enabled = $extension_config->get("module.$module") !== NULL; Chris@0: if (!$enabled) { Chris@0: // Throw an exception if the module name is too long. Chris@0: if (strlen($module) > DRUPAL_EXTENSION_NAME_MAX_LENGTH) { Chris@0: throw new ExtensionNameLengthException("Module name '$module' is over the maximum allowed length of " . DRUPAL_EXTENSION_NAME_MAX_LENGTH . ' characters'); Chris@0: } Chris@0: Chris@0: // Load a new config object for each iteration, otherwise changes made Chris@0: // in hook_install() are not reflected in $extension_config. Chris@0: $extension_config = \Drupal::configFactory()->getEditable('core.extension'); Chris@0: Chris@0: // Check the validity of the default configuration. This will throw Chris@0: // exceptions if the configuration is not valid. Chris@0: $config_installer->checkConfigurationToInstall('module', $module); Chris@0: Chris@0: // Save this data without checking schema. This is a performance Chris@0: // improvement for module installation. Chris@0: $extension_config Chris@0: ->set("module.$module", 0) Chris@0: ->set('module', module_config_sort($extension_config->get('module'))) Chris@0: ->save(TRUE); Chris@0: Chris@0: // Prepare the new module list, sorted by weight, including filenames. Chris@0: // This list is used for both the ModuleHandler and DrupalKernel. It Chris@0: // needs to be kept in sync between both. A DrupalKernel reboot or Chris@0: // rebuild will automatically re-instantiate a new ModuleHandler that Chris@0: // uses the new module list of the kernel. However, DrupalKernel does Chris@0: // not cause any modules to be loaded. Chris@0: // Furthermore, the currently active (fixed) module list can be Chris@0: // different from the configured list of enabled modules. For all active Chris@0: // modules not contained in the configured enabled modules, we assume a Chris@0: // weight of 0. Chris@0: $current_module_filenames = $this->moduleHandler->getModuleList(); Chris@0: $current_modules = array_fill_keys(array_keys($current_module_filenames), 0); Chris@0: $current_modules = module_config_sort(array_merge($current_modules, $extension_config->get('module'))); Chris@0: $module_filenames = []; Chris@0: foreach ($current_modules as $name => $weight) { Chris@0: if (isset($current_module_filenames[$name])) { Chris@0: $module_filenames[$name] = $current_module_filenames[$name]; Chris@0: } Chris@0: else { Chris@17: $module_path = \Drupal::service('extension.list.module')->getPath($name); Chris@0: $pathname = "$module_path/$name.info.yml"; Chris@0: $filename = file_exists($module_path . "/$name.module") ? "$name.module" : NULL; Chris@0: $module_filenames[$name] = new Extension($this->root, 'module', $pathname, $filename); Chris@0: } Chris@0: } Chris@0: Chris@0: // Update the module handler in order to load the module's code. Chris@0: // This allows the module to participate in hooks and its existence to Chris@0: // be discovered by other modules. Chris@0: // The current ModuleHandler instance is obsolete with the kernel Chris@0: // rebuild below. Chris@0: $this->moduleHandler->setModuleList($module_filenames); Chris@0: $this->moduleHandler->load($module); Chris@0: module_load_install($module); Chris@0: Chris@17: // Clear the static cache of the "extension.list.module" service to pick Chris@17: // up the new module, since it merges the installation status of modules Chris@17: // into its statically cached list. Chris@17: \Drupal::service('extension.list.module')->reset(); Chris@0: Chris@0: // Update the kernel to include it. Chris@0: $this->updateKernel($module_filenames); Chris@0: Chris@12: // Replace the route provider service with a version that will rebuild Chris@12: // if routes used during installation. This ensures that a module's Chris@12: // routes are available during installation. This has to occur before Chris@12: // any services that depend on it are instantiated otherwise those Chris@12: // services will have the old route provider injected. Note that, since Chris@12: // the container is rebuilt by updating the kernel, the route provider Chris@12: // service is the regular one even though we are in a loop and might Chris@12: // have replaced it before. Chris@12: \Drupal::getContainer()->set('router.route_provider.old', \Drupal::service('router.route_provider')); Chris@12: \Drupal::getContainer()->set('router.route_provider', \Drupal::service('router.route_provider.lazy_builder')); Chris@12: Chris@0: // Allow modules to react prior to the installation of a module. Chris@0: $this->moduleHandler->invokeAll('module_preinstall', [$module]); Chris@0: Chris@0: // Now install the module's schema if necessary. Chris@0: drupal_install_schema($module); Chris@0: Chris@0: // Clear plugin manager caches. Chris@0: \Drupal::getContainer()->get('plugin.cache_clearer')->clearCachedDefinitions(); Chris@0: Chris@0: // Set the schema version to the number of the last update provided by Chris@0: // the module, or the minimum core schema version. Chris@0: $version = \Drupal::CORE_MINIMUM_SCHEMA_VERSION; Chris@0: $versions = drupal_get_schema_versions($module); Chris@0: if ($versions) { Chris@0: $version = max(max($versions), $version); Chris@0: } Chris@0: Chris@0: // Notify interested components that this module's entity types and Chris@0: // field storage definitions are new. For example, a SQL-based storage Chris@0: // handler can use this as an opportunity to create the necessary Chris@0: // database tables. Chris@0: // @todo Clean this up in https://www.drupal.org/node/2350111. Chris@0: $entity_manager = \Drupal::entityManager(); Chris@0: $update_manager = \Drupal::entityDefinitionUpdateManager(); Chris@0: foreach ($entity_manager->getDefinitions() as $entity_type) { Chris@0: if ($entity_type->getProvider() == $module) { Chris@0: $update_manager->installEntityType($entity_type); Chris@0: } Chris@0: elseif ($entity_type->entityClassImplements(FieldableEntityInterface::CLASS)) { Chris@0: // The module being installed may be adding new fields to existing Chris@0: // entity types. Field definitions for any entity type defined by Chris@0: // the module are handled in the if branch. Chris@0: foreach ($entity_manager->getFieldStorageDefinitions($entity_type->id()) as $storage_definition) { Chris@0: if ($storage_definition->getProvider() == $module) { Chris@0: // If the module being installed is also defining a storage key Chris@0: // for the entity type, the entity schema may not exist yet. It Chris@0: // will be created later in that case. Chris@0: try { Chris@0: $update_manager->installFieldStorageDefinition($storage_definition->getName(), $entity_type->id(), $module, $storage_definition); Chris@0: } Chris@0: catch (EntityStorageException $e) { Chris@0: watchdog_exception('system', $e, 'An error occurred while notifying the creation of the @name field storage definition: "!message" in %function (line %line of %file).', ['@name' => $storage_definition->getName()]); Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: // Install default configuration of the module. Chris@0: $config_installer = \Drupal::service('config.installer'); Chris@0: if ($sync_status) { Chris@0: $config_installer Chris@0: ->setSyncing(TRUE) Chris@0: ->setSourceStorage($source_storage); Chris@0: } Chris@0: \Drupal::service('config.installer')->installDefaultConfig('module', $module); Chris@0: Chris@0: // If the module has no current updates, but has some that were Chris@0: // previously removed, set the version to the value of Chris@0: // hook_update_last_removed(). Chris@0: if ($last_removed = $this->moduleHandler->invoke($module, 'update_last_removed')) { Chris@0: $version = max($version, $last_removed); Chris@0: } Chris@0: drupal_set_installed_schema_version($module, $version); Chris@0: Chris@0: // Ensure that all post_update functions are registered already. Chris@0: /** @var \Drupal\Core\Update\UpdateRegistry $post_update_registry */ Chris@0: $post_update_registry = \Drupal::service('update.post_update_registry'); Chris@0: $post_update_registry->registerInvokedUpdates($post_update_registry->getModuleUpdateFunctions($module)); Chris@0: Chris@0: // Record the fact that it was installed. Chris@0: $modules_installed[] = $module; Chris@0: Chris@0: // Drupal's stream wrappers needs to be re-registered in case a Chris@0: // module-provided stream wrapper is used later in the same request. In Chris@0: // particular, this happens when installing Drupal via Drush, as the Chris@0: // 'translations' stream wrapper is provided by Interface Translation Chris@0: // module and is later used to import translations. Chris@0: \Drupal::service('stream_wrapper_manager')->register(); Chris@0: Chris@0: // Update the theme registry to include it. Chris@0: drupal_theme_rebuild(); Chris@0: Chris@0: // Modules can alter theme info, so refresh theme data. Chris@0: // @todo ThemeHandler cannot be injected into ModuleHandler, since that Chris@0: // causes a circular service dependency. Chris@0: // @see https://www.drupal.org/node/2208429 Chris@0: \Drupal::service('theme_handler')->refreshInfo(); Chris@0: Chris@0: // Allow the module to perform install tasks. Chris@0: $this->moduleHandler->invoke($module, 'install'); Chris@0: Chris@0: // Record the fact that it was installed. Chris@0: \Drupal::logger('system')->info('%module module installed.', ['%module' => $module]); Chris@0: } Chris@0: } Chris@0: Chris@0: // If any modules were newly installed, invoke hook_modules_installed(). Chris@0: if (!empty($modules_installed)) { Chris@14: // If the container was rebuilt during hook_install() it might not have Chris@14: // the 'router.route_provider.old' service. Chris@14: if (\Drupal::hasService('router.route_provider.old')) { Chris@14: \Drupal::getContainer()->set('router.route_provider', \Drupal::service('router.route_provider.old')); Chris@14: } Chris@0: if (!\Drupal::service('router.route_provider.lazy_builder')->hasRebuilt()) { Chris@0: // Rebuild routes after installing module. This is done here on top of Chris@0: // \Drupal\Core\Routing\RouteBuilder::destruct to not run into errors on Chris@0: // fastCGI which executes ::destruct() after the module installation Chris@0: // page was sent already. Chris@0: \Drupal::service('router.builder')->rebuild(); Chris@0: } Chris@0: Chris@0: $this->moduleHandler->invokeAll('modules_installed', [$modules_installed]); Chris@0: } Chris@0: Chris@0: return TRUE; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function uninstall(array $module_list, $uninstall_dependents = TRUE) { Chris@0: // Get all module data so we can find dependencies and sort. Chris@0: $module_data = system_rebuild_module_data(); Chris@0: $module_list = $module_list ? array_combine($module_list, $module_list) : []; Chris@0: if (array_diff_key($module_list, $module_data)) { Chris@0: // One or more of the given modules doesn't exist. Chris@0: return FALSE; Chris@0: } Chris@0: Chris@0: $extension_config = \Drupal::configFactory()->getEditable('core.extension'); Chris@0: $installed_modules = $extension_config->get('module') ?: []; Chris@0: if (!$module_list = array_intersect_key($module_list, $installed_modules)) { Chris@0: // Nothing to do. All modules already uninstalled. Chris@0: return TRUE; Chris@0: } Chris@0: Chris@0: if ($uninstall_dependents) { Chris@0: // Add dependent modules to the list. The new modules will be processed as Chris@14: // the foreach loop continues. Chris@14: foreach ($module_list as $module => $value) { Chris@0: foreach (array_keys($module_data[$module]->required_by) as $dependent) { Chris@0: if (!isset($module_data[$dependent])) { Chris@0: // The dependent module does not exist. Chris@0: return FALSE; Chris@0: } Chris@0: Chris@0: // Skip already uninstalled modules. Chris@17: if (isset($installed_modules[$dependent]) && !isset($module_list[$dependent])) { Chris@0: $module_list[$dependent] = $dependent; Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: // Use the validators and throw an exception with the reasons. Chris@0: if ($reasons = $this->validateUninstall($module_list)) { Chris@0: foreach ($reasons as $reason) { Chris@0: $reason_message[] = implode(', ', $reason); Chris@0: } Chris@0: throw new ModuleUninstallValidatorException('The following reasons prevent the modules from being uninstalled: ' . implode('; ', $reason_message)); Chris@0: } Chris@0: // Set the actual module weights. Chris@0: $module_list = array_map(function ($module) use ($module_data) { Chris@0: return $module_data[$module]->sort; Chris@0: }, $module_list); Chris@0: Chris@0: // Sort the module list by their weights. Chris@0: asort($module_list); Chris@0: $module_list = array_keys($module_list); Chris@0: Chris@0: // Only process modules that are enabled. A module is only enabled if it is Chris@0: // configured as enabled. Custom or overridden module handlers might contain Chris@0: // the module already, which means that it might be loaded, but not Chris@0: // necessarily installed. Chris@0: foreach ($module_list as $module) { Chris@0: Chris@0: // Clean up all entity bundles (including fields) of every entity type Chris@0: // provided by the module that is being uninstalled. Chris@0: // @todo Clean this up in https://www.drupal.org/node/2350111. Chris@0: $entity_manager = \Drupal::entityManager(); Chris@18: $entity_type_bundle_info = \Drupal::service('entity_type.bundle.info'); Chris@0: foreach ($entity_manager->getDefinitions() as $entity_type_id => $entity_type) { Chris@0: if ($entity_type->getProvider() == $module) { Chris@18: foreach (array_keys($entity_type_bundle_info->getBundleInfo($entity_type_id)) as $bundle) { Chris@18: \Drupal::service('entity_bundle.listener')->onBundleDelete($bundle, $entity_type_id); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: // Allow modules to react prior to the uninstallation of a module. Chris@0: $this->moduleHandler->invokeAll('module_preuninstall', [$module]); Chris@0: Chris@0: // Uninstall the module. Chris@0: module_load_install($module); Chris@0: $this->moduleHandler->invoke($module, 'uninstall'); Chris@0: Chris@0: // Remove all configuration belonging to the module. Chris@0: \Drupal::service('config.manager')->uninstall('module', $module); Chris@0: Chris@0: // In order to make uninstalling transactional if anything uses routes. Chris@0: \Drupal::getContainer()->set('router.route_provider.old', \Drupal::service('router.route_provider')); Chris@0: \Drupal::getContainer()->set('router.route_provider', \Drupal::service('router.route_provider.lazy_builder')); Chris@0: Chris@0: // Notify interested components that this module's entity types are being Chris@0: // deleted. For example, a SQL-based storage handler can use this as an Chris@0: // opportunity to drop the corresponding database tables. Chris@0: // @todo Clean this up in https://www.drupal.org/node/2350111. Chris@0: $update_manager = \Drupal::entityDefinitionUpdateManager(); Chris@0: foreach ($entity_manager->getDefinitions() as $entity_type) { Chris@0: if ($entity_type->getProvider() == $module) { Chris@0: $update_manager->uninstallEntityType($entity_type); Chris@0: } Chris@0: elseif ($entity_type->entityClassImplements(FieldableEntityInterface::CLASS)) { Chris@14: // The module being uninstalled might have added new fields to Chris@14: // existing entity types. This will add them to the deleted fields Chris@14: // repository so their data will be purged on cron. Chris@14: foreach ($entity_manager->getFieldStorageDefinitions($entity_type->id()) as $storage_definition) { Chris@14: if ($storage_definition->getProvider() == $module) { Chris@0: $update_manager->uninstallFieldStorageDefinition($storage_definition); Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: // Remove the schema. Chris@0: drupal_uninstall_schema($module); Chris@0: Chris@0: // Remove the module's entry from the config. Don't check schema when Chris@0: // uninstalling a module since we are only clearing a key. Chris@0: \Drupal::configFactory()->getEditable('core.extension')->clear("module.$module")->save(TRUE); Chris@0: Chris@0: // Update the module handler to remove the module. Chris@0: // The current ModuleHandler instance is obsolete with the kernel rebuild Chris@0: // below. Chris@0: $module_filenames = $this->moduleHandler->getModuleList(); Chris@0: unset($module_filenames[$module]); Chris@0: $this->moduleHandler->setModuleList($module_filenames); Chris@0: Chris@0: // Remove any potential cache bins provided by the module. Chris@0: $this->removeCacheBins($module); Chris@0: Chris@17: // Clear the static cache of the "extension.list.module" service to pick Chris@17: // up the new module, since it merges the installation status of modules Chris@17: // into its statically cached list. Chris@17: \Drupal::service('extension.list.module')->reset(); Chris@0: Chris@0: // Clear plugin manager caches. Chris@0: \Drupal::getContainer()->get('plugin.cache_clearer')->clearCachedDefinitions(); Chris@0: Chris@0: // Update the kernel to exclude the uninstalled modules. Chris@0: $this->updateKernel($module_filenames); Chris@0: Chris@0: // Update the theme registry to remove the newly uninstalled module. Chris@0: drupal_theme_rebuild(); Chris@0: Chris@0: // Modules can alter theme info, so refresh theme data. Chris@0: // @todo ThemeHandler cannot be injected into ModuleHandler, since that Chris@0: // causes a circular service dependency. Chris@0: // @see https://www.drupal.org/node/2208429 Chris@0: \Drupal::service('theme_handler')->refreshInfo(); Chris@0: Chris@0: \Drupal::logger('system')->info('%module module uninstalled.', ['%module' => $module]); Chris@0: Chris@0: $schema_store = \Drupal::keyValue('system.schema'); Chris@0: $schema_store->delete($module); Chris@0: Chris@0: /** @var \Drupal\Core\Update\UpdateRegistry $post_update_registry */ Chris@0: $post_update_registry = \Drupal::service('update.post_update_registry'); Chris@0: $post_update_registry->filterOutInvokedUpdatesByModule($module); Chris@0: } Chris@0: // Rebuild routes after installing module. This is done here on top of Chris@0: // \Drupal\Core\Routing\RouteBuilder::destruct to not run into errors on Chris@0: // fastCGI which executes ::destruct() after the Module uninstallation page Chris@0: // was sent already. Chris@0: \Drupal::service('router.builder')->rebuild(); Chris@0: drupal_get_installed_schema_version(NULL, TRUE); Chris@0: Chris@0: // Let other modules react. Chris@0: $this->moduleHandler->invokeAll('modules_uninstalled', [$module_list]); Chris@0: Chris@0: // Flush all persistent caches. Chris@0: // Any cache entry might implicitly depend on the uninstalled modules, Chris@0: // so clear all of them explicitly. Chris@0: $this->moduleHandler->invokeAll('cache_flush'); Chris@0: foreach (Cache::getBins() as $service_id => $cache_backend) { Chris@0: $cache_backend->deleteAll(); Chris@0: } Chris@0: Chris@0: return TRUE; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Helper method for removing all cache bins registered by a given module. Chris@0: * Chris@0: * @param string $module Chris@0: * The name of the module for which to remove all registered cache bins. Chris@0: */ Chris@0: protected function removeCacheBins($module) { Chris@0: $service_yaml_file = drupal_get_path('module', $module) . "/$module.services.yml"; Chris@12: if (!file_exists($service_yaml_file)) { Chris@12: return; Chris@12: } Chris@12: Chris@12: $definitions = Yaml::decode(file_get_contents($service_yaml_file)); Chris@12: Chris@12: $cache_bin_services = array_filter( Chris@12: isset($definitions['services']) ? $definitions['services'] : [], Chris@12: function ($definition) { Chris@12: $tags = isset($definition['tags']) ? $definition['tags'] : []; Chris@12: foreach ($tags as $tag) { Chris@12: if (isset($tag['name']) && ($tag['name'] == 'cache.bin')) { Chris@12: return TRUE; Chris@0: } Chris@0: } Chris@12: return FALSE; Chris@12: } Chris@12: ); Chris@12: Chris@12: foreach (array_keys($cache_bin_services) as $service_id) { Chris@12: $backend = $this->kernel->getContainer()->get($service_id); Chris@12: if ($backend instanceof CacheBackendInterface) { Chris@12: $backend->removeBin(); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Updates the kernel module list. Chris@0: * Chris@0: * @param string $module_filenames Chris@0: * The list of installed modules. Chris@0: */ Chris@0: protected function updateKernel($module_filenames) { Chris@0: // This reboots the kernel to register the module's bundle and its services Chris@0: // in the service container. The $module_filenames argument is taken over as Chris@0: // %container.modules% parameter, which is passed to a fresh ModuleHandler Chris@0: // instance upon first retrieval. Chris@0: $this->kernel->updateModules($module_filenames, $module_filenames); Chris@0: // After rebuilding the container we need to update the injected Chris@0: // dependencies. Chris@0: $container = $this->kernel->getContainer(); Chris@0: $this->moduleHandler = $container->get('module_handler'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function validateUninstall(array $module_list) { Chris@0: $reasons = []; Chris@0: foreach ($module_list as $module) { Chris@0: foreach ($this->uninstallValidators as $validator) { Chris@0: $validation_reasons = $validator->validate($module); Chris@0: if (!empty($validation_reasons)) { Chris@0: if (!isset($reasons[$module])) { Chris@0: $reasons[$module] = []; Chris@0: } Chris@0: $reasons[$module] = array_merge($reasons[$module], $validation_reasons); Chris@0: } Chris@0: } Chris@0: } Chris@0: return $reasons; Chris@0: } Chris@0: Chris@0: }