You are here

module_blacklist.module in Module Blacklist 8

Module Blacklist implementation of hooks.

File

module_blacklist.module
View source
<?php

/**
 * @file
 * Module Blacklist implementation of hooks.
 */
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Site\Settings;
use Drupal\module_blacklist\Exception\ModuleInstallationBlocked;

/**
 * Implements hook_module_preinstall().
 */
function module_blacklist_module_preinstall($module) {

  // Allow Drush if config is TRUE.
  if (PHP_SAPI === 'cli' && Settings::get('module_blacklist_drush', FALSE)) {
    return;
  }
  $module_blacklist = Settings::get('module_blacklist');
  if (!$module_blacklist || !in_array($module, $module_blacklist)) {
    return;
  }

  // Before Drupal invokes the hook hook_module_preinstall() the method
  // install() at Drupal\Core\Extension\ModuleInstaller performs some tasks
  // changing the configs and system files data from the module that is being
  // installed, so, before throw the exception it is necessary performs a
  // rollback to those changes.
  \Drupal::service('module_blacklist.module_installer')
    ->rollbackPreinstall($module);
  throw new ModuleInstallationBlocked("Unable to install '{$module}' module. The installation of this module is blocked by Module Blacklist.");
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function module_blacklist_form_system_modules_alter(&$form, FormStateInterface $form_state, $form_id) {
  $module_blacklist = Settings::get('module_blacklist');
  if (!$module_blacklist) {

    // Skips if the blacklist is empty.
    return;
  }
  foreach ($form['modules'] as $module_package => $modules) {
    if (!is_array($modules)) {
      continue;
    }
    foreach ($modules as $module_name => $module_info) {

      // Checks whether the module is blacklisted.
      if (!in_array($module_name, $module_blacklist)) {
        continue;
      }

      // Skips modules that are already enabled, even if it is blacklisted.
      if ($form['modules'][$module_package][$module_name]['enable']['#default_value'] === TRUE) {
        continue;
      }

      // Alters the module form row, disabling the module installation.
      $form['modules'][$module_package][$module_name]['enable']['#disabled'] = TRUE;
      $form['modules'][$module_package][$module_name]['name']['#markup'] .= " (blocked)";
      $form['modules'][$module_package][$module_name]['description']['#markup'] .= ' ' . t('WARNING: The installation of this module is being blocked by Module Blacklist.');
    }
  }
}