comparison core/lib/Drupal/Core/Extension/ModuleInstaller.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 7a779792577d
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 namespace Drupal\Core\Extension;
4
5 use Drupal\Core\Cache\Cache;
6 use Drupal\Core\Cache\CacheBackendInterface;
7 use Drupal\Core\DrupalKernelInterface;
8 use Drupal\Core\Entity\EntityStorageException;
9 use Drupal\Core\Entity\FieldableEntityInterface;
10 use Drupal\Core\Serialization\Yaml;
11
12 /**
13 * Default implementation of the module installer.
14 *
15 * It registers the module in config, installs its own configuration,
16 * installs the schema, updates the Drupal kernel and more.
17 */
18 class ModuleInstaller implements ModuleInstallerInterface {
19
20 /**
21 * The module handler.
22 *
23 * @var \Drupal\Core\Extension\ModuleHandlerInterface
24 */
25 protected $moduleHandler;
26
27 /**
28 * The drupal kernel.
29 *
30 * @var \Drupal\Core\DrupalKernelInterface
31 */
32 protected $kernel;
33
34 /**
35 * The app root.
36 *
37 * @var string
38 */
39 protected $root;
40
41 /**
42 * The uninstall validators.
43 *
44 * @var \Drupal\Core\Extension\ModuleUninstallValidatorInterface[]
45 */
46 protected $uninstallValidators;
47
48 /**
49 * Constructs a new ModuleInstaller instance.
50 *
51 * @param string $root
52 * The app root.
53 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
54 * The module handler.
55 * @param \Drupal\Core\DrupalKernelInterface $kernel
56 * The drupal kernel.
57 *
58 * @see \Drupal\Core\DrupalKernel
59 * @see \Drupal\Core\CoreServiceProvider
60 */
61 public function __construct($root, ModuleHandlerInterface $module_handler, DrupalKernelInterface $kernel) {
62 $this->root = $root;
63 $this->moduleHandler = $module_handler;
64 $this->kernel = $kernel;
65 }
66
67 /**
68 * {@inheritdoc}
69 */
70 public function addUninstallValidator(ModuleUninstallValidatorInterface $uninstall_validator) {
71 $this->uninstallValidators[] = $uninstall_validator;
72 }
73
74 /**
75 * {@inheritdoc}
76 */
77 public function install(array $module_list, $enable_dependencies = TRUE) {
78 $extension_config = \Drupal::configFactory()->getEditable('core.extension');
79 if ($enable_dependencies) {
80 // Get all module data so we can find dependencies and sort.
81 $module_data = system_rebuild_module_data();
82 $module_list = $module_list ? array_combine($module_list, $module_list) : [];
83 if ($missing_modules = array_diff_key($module_list, $module_data)) {
84 // One or more of the given modules doesn't exist.
85 throw new MissingDependencyException(sprintf('Unable to install modules %s due to missing modules %s.', implode(', ', $module_list), implode(', ', $missing_modules)));
86 }
87
88 // Only process currently uninstalled modules.
89 $installed_modules = $extension_config->get('module') ?: [];
90 if (!$module_list = array_diff_key($module_list, $installed_modules)) {
91 // Nothing to do. All modules already installed.
92 return TRUE;
93 }
94
95 // Add dependencies to the list. The new modules will be processed as
96 // the while loop continues.
97 while (list($module) = each($module_list)) {
98 foreach (array_keys($module_data[$module]->requires) as $dependency) {
99 if (!isset($module_data[$dependency])) {
100 // The dependency does not exist.
101 throw new MissingDependencyException("Unable to install modules: module '$module' is missing its dependency module $dependency.");
102 }
103
104 // Skip already installed modules.
105 if (!isset($module_list[$dependency]) && !isset($installed_modules[$dependency])) {
106 $module_list[$dependency] = $dependency;
107 }
108 }
109 }
110
111 // Set the actual module weights.
112 $module_list = array_map(function ($module) use ($module_data) {
113 return $module_data[$module]->sort;
114 }, $module_list);
115
116 // Sort the module list by their weights (reverse).
117 arsort($module_list);
118 $module_list = array_keys($module_list);
119 }
120
121 // Required for module installation checks.
122 include_once $this->root . '/core/includes/install.inc';
123
124 /** @var \Drupal\Core\Config\ConfigInstaller $config_installer */
125 $config_installer = \Drupal::service('config.installer');
126 $sync_status = $config_installer->isSyncing();
127 if ($sync_status) {
128 $source_storage = $config_installer->getSourceStorage();
129 }
130 $modules_installed = [];
131 foreach ($module_list as $module) {
132 $enabled = $extension_config->get("module.$module") !== NULL;
133 if (!$enabled) {
134 // Throw an exception if the module name is too long.
135 if (strlen($module) > DRUPAL_EXTENSION_NAME_MAX_LENGTH) {
136 throw new ExtensionNameLengthException("Module name '$module' is over the maximum allowed length of " . DRUPAL_EXTENSION_NAME_MAX_LENGTH . ' characters');
137 }
138
139 // Load a new config object for each iteration, otherwise changes made
140 // in hook_install() are not reflected in $extension_config.
141 $extension_config = \Drupal::configFactory()->getEditable('core.extension');
142
143 // Check the validity of the default configuration. This will throw
144 // exceptions if the configuration is not valid.
145 $config_installer->checkConfigurationToInstall('module', $module);
146
147 // Save this data without checking schema. This is a performance
148 // improvement for module installation.
149 $extension_config
150 ->set("module.$module", 0)
151 ->set('module', module_config_sort($extension_config->get('module')))
152 ->save(TRUE);
153
154 // Prepare the new module list, sorted by weight, including filenames.
155 // This list is used for both the ModuleHandler and DrupalKernel. It
156 // needs to be kept in sync between both. A DrupalKernel reboot or
157 // rebuild will automatically re-instantiate a new ModuleHandler that
158 // uses the new module list of the kernel. However, DrupalKernel does
159 // not cause any modules to be loaded.
160 // Furthermore, the currently active (fixed) module list can be
161 // different from the configured list of enabled modules. For all active
162 // modules not contained in the configured enabled modules, we assume a
163 // weight of 0.
164 $current_module_filenames = $this->moduleHandler->getModuleList();
165 $current_modules = array_fill_keys(array_keys($current_module_filenames), 0);
166 $current_modules = module_config_sort(array_merge($current_modules, $extension_config->get('module')));
167 $module_filenames = [];
168 foreach ($current_modules as $name => $weight) {
169 if (isset($current_module_filenames[$name])) {
170 $module_filenames[$name] = $current_module_filenames[$name];
171 }
172 else {
173 $module_path = drupal_get_path('module', $name);
174 $pathname = "$module_path/$name.info.yml";
175 $filename = file_exists($module_path . "/$name.module") ? "$name.module" : NULL;
176 $module_filenames[$name] = new Extension($this->root, 'module', $pathname, $filename);
177 }
178 }
179
180 // Update the module handler in order to load the module's code.
181 // This allows the module to participate in hooks and its existence to
182 // be discovered by other modules.
183 // The current ModuleHandler instance is obsolete with the kernel
184 // rebuild below.
185 $this->moduleHandler->setModuleList($module_filenames);
186 $this->moduleHandler->load($module);
187 module_load_install($module);
188
189 // Clear the static cache of system_rebuild_module_data() to pick up the
190 // new module, since it merges the installation status of modules into
191 // its statically cached list.
192 drupal_static_reset('system_rebuild_module_data');
193
194 // Update the kernel to include it.
195 $this->updateKernel($module_filenames);
196
197 // Allow modules to react prior to the installation of a module.
198 $this->moduleHandler->invokeAll('module_preinstall', [$module]);
199
200 // Now install the module's schema if necessary.
201 drupal_install_schema($module);
202
203 // Clear plugin manager caches.
204 \Drupal::getContainer()->get('plugin.cache_clearer')->clearCachedDefinitions();
205
206 // Set the schema version to the number of the last update provided by
207 // the module, or the minimum core schema version.
208 $version = \Drupal::CORE_MINIMUM_SCHEMA_VERSION;
209 $versions = drupal_get_schema_versions($module);
210 if ($versions) {
211 $version = max(max($versions), $version);
212 }
213
214 // Notify interested components that this module's entity types and
215 // field storage definitions are new. For example, a SQL-based storage
216 // handler can use this as an opportunity to create the necessary
217 // database tables.
218 // @todo Clean this up in https://www.drupal.org/node/2350111.
219 $entity_manager = \Drupal::entityManager();
220 $update_manager = \Drupal::entityDefinitionUpdateManager();
221 foreach ($entity_manager->getDefinitions() as $entity_type) {
222 if ($entity_type->getProvider() == $module) {
223 $update_manager->installEntityType($entity_type);
224 }
225 elseif ($entity_type->entityClassImplements(FieldableEntityInterface::CLASS)) {
226 // The module being installed may be adding new fields to existing
227 // entity types. Field definitions for any entity type defined by
228 // the module are handled in the if branch.
229 foreach ($entity_manager->getFieldStorageDefinitions($entity_type->id()) as $storage_definition) {
230 if ($storage_definition->getProvider() == $module) {
231 // If the module being installed is also defining a storage key
232 // for the entity type, the entity schema may not exist yet. It
233 // will be created later in that case.
234 try {
235 $update_manager->installFieldStorageDefinition($storage_definition->getName(), $entity_type->id(), $module, $storage_definition);
236 }
237 catch (EntityStorageException $e) {
238 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()]);
239 }
240 }
241 }
242 }
243 }
244
245 // Install default configuration of the module.
246 $config_installer = \Drupal::service('config.installer');
247 if ($sync_status) {
248 $config_installer
249 ->setSyncing(TRUE)
250 ->setSourceStorage($source_storage);
251 }
252 \Drupal::service('config.installer')->installDefaultConfig('module', $module);
253
254 // If the module has no current updates, but has some that were
255 // previously removed, set the version to the value of
256 // hook_update_last_removed().
257 if ($last_removed = $this->moduleHandler->invoke($module, 'update_last_removed')) {
258 $version = max($version, $last_removed);
259 }
260 drupal_set_installed_schema_version($module, $version);
261
262 // Ensure that all post_update functions are registered already.
263 /** @var \Drupal\Core\Update\UpdateRegistry $post_update_registry */
264 $post_update_registry = \Drupal::service('update.post_update_registry');
265 $post_update_registry->registerInvokedUpdates($post_update_registry->getModuleUpdateFunctions($module));
266
267 // Record the fact that it was installed.
268 $modules_installed[] = $module;
269
270 // Drupal's stream wrappers needs to be re-registered in case a
271 // module-provided stream wrapper is used later in the same request. In
272 // particular, this happens when installing Drupal via Drush, as the
273 // 'translations' stream wrapper is provided by Interface Translation
274 // module and is later used to import translations.
275 \Drupal::service('stream_wrapper_manager')->register();
276
277 // Update the theme registry to include it.
278 drupal_theme_rebuild();
279
280 // Modules can alter theme info, so refresh theme data.
281 // @todo ThemeHandler cannot be injected into ModuleHandler, since that
282 // causes a circular service dependency.
283 // @see https://www.drupal.org/node/2208429
284 \Drupal::service('theme_handler')->refreshInfo();
285
286 // In order to make uninstalling transactional if anything uses routes.
287 \Drupal::getContainer()->set('router.route_provider.old', \Drupal::service('router.route_provider'));
288 \Drupal::getContainer()->set('router.route_provider', \Drupal::service('router.route_provider.lazy_builder'));
289
290 // Allow the module to perform install tasks.
291 $this->moduleHandler->invoke($module, 'install');
292
293 // Record the fact that it was installed.
294 \Drupal::logger('system')->info('%module module installed.', ['%module' => $module]);
295 }
296 }
297
298 // If any modules were newly installed, invoke hook_modules_installed().
299 if (!empty($modules_installed)) {
300 \Drupal::getContainer()->set('router.route_provider', \Drupal::service('router.route_provider.old'));
301 if (!\Drupal::service('router.route_provider.lazy_builder')->hasRebuilt()) {
302 // Rebuild routes after installing module. This is done here on top of
303 // \Drupal\Core\Routing\RouteBuilder::destruct to not run into errors on
304 // fastCGI which executes ::destruct() after the module installation
305 // page was sent already.
306 \Drupal::service('router.builder')->rebuild();
307 }
308
309 $this->moduleHandler->invokeAll('modules_installed', [$modules_installed]);
310 }
311
312 return TRUE;
313 }
314
315 /**
316 * {@inheritdoc}
317 */
318 public function uninstall(array $module_list, $uninstall_dependents = TRUE) {
319 // Get all module data so we can find dependencies and sort.
320 $module_data = system_rebuild_module_data();
321 $module_list = $module_list ? array_combine($module_list, $module_list) : [];
322 if (array_diff_key($module_list, $module_data)) {
323 // One or more of the given modules doesn't exist.
324 return FALSE;
325 }
326
327 $extension_config = \Drupal::configFactory()->getEditable('core.extension');
328 $installed_modules = $extension_config->get('module') ?: [];
329 if (!$module_list = array_intersect_key($module_list, $installed_modules)) {
330 // Nothing to do. All modules already uninstalled.
331 return TRUE;
332 }
333
334 if ($uninstall_dependents) {
335 // Add dependent modules to the list. The new modules will be processed as
336 // the while loop continues.
337 $profile = drupal_get_profile();
338 while (list($module) = each($module_list)) {
339 foreach (array_keys($module_data[$module]->required_by) as $dependent) {
340 if (!isset($module_data[$dependent])) {
341 // The dependent module does not exist.
342 return FALSE;
343 }
344
345 // Skip already uninstalled modules.
346 if (isset($installed_modules[$dependent]) && !isset($module_list[$dependent]) && $dependent != $profile) {
347 $module_list[$dependent] = $dependent;
348 }
349 }
350 }
351 }
352
353 // Use the validators and throw an exception with the reasons.
354 if ($reasons = $this->validateUninstall($module_list)) {
355 foreach ($reasons as $reason) {
356 $reason_message[] = implode(', ', $reason);
357 }
358 throw new ModuleUninstallValidatorException('The following reasons prevent the modules from being uninstalled: ' . implode('; ', $reason_message));
359 }
360 // Set the actual module weights.
361 $module_list = array_map(function ($module) use ($module_data) {
362 return $module_data[$module]->sort;
363 }, $module_list);
364
365 // Sort the module list by their weights.
366 asort($module_list);
367 $module_list = array_keys($module_list);
368
369 // Only process modules that are enabled. A module is only enabled if it is
370 // configured as enabled. Custom or overridden module handlers might contain
371 // the module already, which means that it might be loaded, but not
372 // necessarily installed.
373 foreach ($module_list as $module) {
374
375 // Clean up all entity bundles (including fields) of every entity type
376 // provided by the module that is being uninstalled.
377 // @todo Clean this up in https://www.drupal.org/node/2350111.
378 $entity_manager = \Drupal::entityManager();
379 foreach ($entity_manager->getDefinitions() as $entity_type_id => $entity_type) {
380 if ($entity_type->getProvider() == $module) {
381 foreach (array_keys($entity_manager->getBundleInfo($entity_type_id)) as $bundle) {
382 $entity_manager->onBundleDelete($bundle, $entity_type_id);
383 }
384 }
385 }
386
387 // Allow modules to react prior to the uninstallation of a module.
388 $this->moduleHandler->invokeAll('module_preuninstall', [$module]);
389
390 // Uninstall the module.
391 module_load_install($module);
392 $this->moduleHandler->invoke($module, 'uninstall');
393
394 // Remove all configuration belonging to the module.
395 \Drupal::service('config.manager')->uninstall('module', $module);
396
397 // In order to make uninstalling transactional if anything uses routes.
398 \Drupal::getContainer()->set('router.route_provider.old', \Drupal::service('router.route_provider'));
399 \Drupal::getContainer()->set('router.route_provider', \Drupal::service('router.route_provider.lazy_builder'));
400
401 // Notify interested components that this module's entity types are being
402 // deleted. For example, a SQL-based storage handler can use this as an
403 // opportunity to drop the corresponding database tables.
404 // @todo Clean this up in https://www.drupal.org/node/2350111.
405 $update_manager = \Drupal::entityDefinitionUpdateManager();
406 foreach ($entity_manager->getDefinitions() as $entity_type) {
407 if ($entity_type->getProvider() == $module) {
408 $update_manager->uninstallEntityType($entity_type);
409 }
410 elseif ($entity_type->entityClassImplements(FieldableEntityInterface::CLASS)) {
411 // The module being installed may be adding new fields to existing
412 // entity types. Field definitions for any entity type defined by
413 // the module are handled in the if branch.
414 $entity_type_id = $entity_type->id();
415 /** @var \Drupal\Core\Entity\FieldableEntityStorageInterface $storage */
416 $storage = $entity_manager->getStorage($entity_type_id);
417 foreach ($entity_manager->getFieldStorageDefinitions($entity_type_id) as $storage_definition) {
418 // @todo We need to trigger field purging here.
419 // See https://www.drupal.org/node/2282119.
420 if ($storage_definition->getProvider() == $module && !$storage->countFieldData($storage_definition, TRUE)) {
421 $update_manager->uninstallFieldStorageDefinition($storage_definition);
422 }
423 }
424 }
425 }
426
427 // Remove the schema.
428 drupal_uninstall_schema($module);
429
430 // Remove the module's entry from the config. Don't check schema when
431 // uninstalling a module since we are only clearing a key.
432 \Drupal::configFactory()->getEditable('core.extension')->clear("module.$module")->save(TRUE);
433
434 // Update the module handler to remove the module.
435 // The current ModuleHandler instance is obsolete with the kernel rebuild
436 // below.
437 $module_filenames = $this->moduleHandler->getModuleList();
438 unset($module_filenames[$module]);
439 $this->moduleHandler->setModuleList($module_filenames);
440
441 // Remove any potential cache bins provided by the module.
442 $this->removeCacheBins($module);
443
444 // Clear the static cache of system_rebuild_module_data() to pick up the
445 // new module, since it merges the installation status of modules into
446 // its statically cached list.
447 drupal_static_reset('system_rebuild_module_data');
448
449 // Clear plugin manager caches.
450 \Drupal::getContainer()->get('plugin.cache_clearer')->clearCachedDefinitions();
451
452 // Update the kernel to exclude the uninstalled modules.
453 $this->updateKernel($module_filenames);
454
455 // Update the theme registry to remove the newly uninstalled module.
456 drupal_theme_rebuild();
457
458 // Modules can alter theme info, so refresh theme data.
459 // @todo ThemeHandler cannot be injected into ModuleHandler, since that
460 // causes a circular service dependency.
461 // @see https://www.drupal.org/node/2208429
462 \Drupal::service('theme_handler')->refreshInfo();
463
464 \Drupal::logger('system')->info('%module module uninstalled.', ['%module' => $module]);
465
466 $schema_store = \Drupal::keyValue('system.schema');
467 $schema_store->delete($module);
468
469 /** @var \Drupal\Core\Update\UpdateRegistry $post_update_registry */
470 $post_update_registry = \Drupal::service('update.post_update_registry');
471 $post_update_registry->filterOutInvokedUpdatesByModule($module);
472 }
473 // Rebuild routes after installing module. This is done here on top of
474 // \Drupal\Core\Routing\RouteBuilder::destruct to not run into errors on
475 // fastCGI which executes ::destruct() after the Module uninstallation page
476 // was sent already.
477 \Drupal::service('router.builder')->rebuild();
478 drupal_get_installed_schema_version(NULL, TRUE);
479
480 // Let other modules react.
481 $this->moduleHandler->invokeAll('modules_uninstalled', [$module_list]);
482
483 // Flush all persistent caches.
484 // Any cache entry might implicitly depend on the uninstalled modules,
485 // so clear all of them explicitly.
486 $this->moduleHandler->invokeAll('cache_flush');
487 foreach (Cache::getBins() as $service_id => $cache_backend) {
488 $cache_backend->deleteAll();
489 }
490
491 return TRUE;
492 }
493
494 /**
495 * Helper method for removing all cache bins registered by a given module.
496 *
497 * @param string $module
498 * The name of the module for which to remove all registered cache bins.
499 */
500 protected function removeCacheBins($module) {
501 // Remove any cache bins defined by a module.
502 $service_yaml_file = drupal_get_path('module', $module) . "/$module.services.yml";
503 if (file_exists($service_yaml_file)) {
504 $definitions = Yaml::decode(file_get_contents($service_yaml_file));
505 if (isset($definitions['services'])) {
506 foreach ($definitions['services'] as $id => $definition) {
507 if (isset($definition['tags'])) {
508 foreach ($definition['tags'] as $tag) {
509 // This works for the default cache registration and even in some
510 // cases when a non-default "super" factory is used. That should
511 // be extremely rare.
512 if ($tag['name'] == 'cache.bin' && isset($definition['factory_service']) && isset($definition['factory_method']) && !empty($definition['arguments'])) {
513 try {
514 $factory = \Drupal::service($definition['factory_service']);
515 if (method_exists($factory, $definition['factory_method'])) {
516 $backend = call_user_func_array([$factory, $definition['factory_method']], $definition['arguments']);
517 if ($backend instanceof CacheBackendInterface) {
518 $backend->removeBin();
519 }
520 }
521 }
522 catch (\Exception $e) {
523 watchdog_exception('system', $e, 'Failed to remove cache bin defined by the service %id.', ['%id' => $id]);
524 }
525 }
526 }
527 }
528 }
529 }
530 }
531 }
532
533 /**
534 * Updates the kernel module list.
535 *
536 * @param string $module_filenames
537 * The list of installed modules.
538 */
539 protected function updateKernel($module_filenames) {
540 // This reboots the kernel to register the module's bundle and its services
541 // in the service container. The $module_filenames argument is taken over as
542 // %container.modules% parameter, which is passed to a fresh ModuleHandler
543 // instance upon first retrieval.
544 $this->kernel->updateModules($module_filenames, $module_filenames);
545 // After rebuilding the container we need to update the injected
546 // dependencies.
547 $container = $this->kernel->getContainer();
548 $this->moduleHandler = $container->get('module_handler');
549 }
550
551 /**
552 * {@inheritdoc}
553 */
554 public function validateUninstall(array $module_list) {
555 $reasons = [];
556 foreach ($module_list as $module) {
557 foreach ($this->uninstallValidators as $validator) {
558 $validation_reasons = $validator->validate($module);
559 if (!empty($validation_reasons)) {
560 if (!isset($reasons[$module])) {
561 $reasons[$module] = [];
562 }
563 $reasons[$module] = array_merge($reasons[$module], $validation_reasons);
564 }
565 }
566 }
567 return $reasons;
568 }
569
570 }