You are here

class AccessController in Theme permission 8

Access Controller.

@package Drupal\theme_permission\Controller.

Hierarchy

Expanded class hierarchy of AccessController

File

src/Controller/AccessController.php, line 24

Namespace

Drupal\theme_permission\Controller
View source
class AccessController extends SystemController {

  /**
   * Current user account.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * Request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * Constructs a  AccessController.
   *
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   A request stack symfony instance.
   * @param \Drupal\system\SystemManager $systemManager
   *   System manager service.
   * @param \Drupal\Core\Theme\ThemeAccessCheck $theme_access
   *   The theme access checker service.
   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
   *   The form builder.
   * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
   *   The theme handler.
   * @param \Drupal\Core\Menu\MenuLinkTreeInterface $menu_link_tree
   *   The menu link tree service.
   */
  public function __construct(AccountInterface $current_user, RequestStack $request_stack, SystemManager $systemManager, ThemeAccessCheck $theme_access, FormBuilderInterface $form_builder, ThemeHandlerInterface $theme_handler, MenuLinkTreeInterface $menu_link_tree) {
    parent::__construct($systemManager, $theme_access, $form_builder, $theme_handler, $menu_link_tree);
    $this->currentUser = $current_user;
    $this->requestStack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('current_user'), $container
      ->get('request_stack'), $container
      ->get('system.manager'), $container
      ->get('access_check.theme'), $container
      ->get('form_builder'), $container
      ->get('theme_handler'), $container
      ->get('menu.link_tree'));
  }

  /**
   * Check permission.
   *
   * @param Drupal\Core\Session\AccountInterface $account
   *   Get Account.
   * @param string $theme
   *   Theme Name.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(AccountInterface $account, $theme = NULL) {
    if (empty($theme)) {
      $theme = $this->requestStack
        ->getCurrentRequest()->query
        ->get('theme');
    }
    $auth = $account
      ->hasPermission("administer themes {$theme}");
    if ($auth) {
      return AccessResult::allowed();
    }
    else {
      return AccessResult::forbidden();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function themesPage() {
    $config = $this
      ->config('system.theme');

    // Get all available themes.
    $themes = $this->themeHandler
      ->rebuildThemeData();
    uasort($themes, 'system_sort_modules_by_info_name');
    $theme_default = $config
      ->get('default');
    $theme_groups = [
      'installed' => [],
      'uninstalled' => [],
    ];
    $admin_theme = $config
      ->get('admin');
    $admin_theme_options = [];
    foreach ($themes as &$theme) {
      $theme_name = $theme
        ->getName();
      $auth = $this->currentUser
        ->hasPermission("administer themes {$theme_name}");
      $uninstall_theme = $this->currentUser
        ->hasPermission("uninstall themes {$theme_name}");
      if ($auth) {
        if (!empty($theme->info['hidden'])) {
          continue;
        }
        $theme->is_default = $theme
          ->getName() == $theme_default;
        $theme->is_admin = $theme
          ->getName() == $admin_theme || $theme->is_default && $admin_theme == '0';

        // Identify theme screenshot.
        $theme->screenshot = NULL;

        // Create a list which includes the current theme and
        // all its base themes.
        if (isset($themes[$theme
          ->getName()]->base_themes)) {
          $theme_keys = array_keys($themes[$theme
            ->getName()]->base_themes);
          $theme_keys[] = $theme
            ->getName();
        }
        else {
          $theme_keys = [
            $theme
              ->getName(),
          ];
        }

        // Look for a screenshot in the current theme
        // or in its closest ancestor.
        foreach (array_reverse($theme_keys) as $theme_key) {
          if (isset($themes[$theme_key]) && file_exists($themes[$theme_key]->info['screenshot'])) {
            $theme->screenshot = [
              'uri' => $themes[$theme_key]->info['screenshot'],
              'alt' => $this
                ->t('Screenshot  for @theme theme', [
                '@theme' => $theme->info['name'],
              ]),
              'title' => $this
                ->t('Screenshot  for @theme theme', [
                '@theme' => $theme->info['name'],
              ]),
              'attributes' => [
                'class' => [
                  'screenshot',
                ],
              ],
            ];
            break;
          }
        }
        if (empty($theme->status)) {

          // Ensure this theme is compatible with this version of core.
          $theme->incompatible_core = !isset($theme->info['core']) || $theme->info['core'] != \DRUPAL::CORE_COMPATIBILITY;

          // Require the 'content' region to make sure the main page
          // content has a common place in all themes.
          $theme->incompatible_region = !isset($theme->info['regions']['content']);
          $theme->incompatible_php = version_compare(phpversion(), $theme->info['php']) < 0;

          // Confirm that all base themes are available.
          $theme->incompatible_base = isset($theme->info['base theme']) && !($theme->base_themes === array_filter($theme->base_themes));

          // Confirm that the theme engine is available.
          $theme->incompatible_engine = isset($theme->info['engine']) && !isset($theme->owner);
        }
        $theme->operations = [];
        if (!empty($theme->status) || !$theme->incompatible_core && !$theme->incompatible_php && !$theme->incompatible_base && !$theme->incompatible_engine) {

          // Create the operations links.
          $query['theme'] = $theme
            ->getName();
          if ($this->themeAccess
            ->checkAccess($theme
            ->getName()) && $auth) {
            $theme->operations[] = [
              'title' => $this
                ->t('Settings'),
              'url' => Url::fromRoute('system.theme_settings_theme', [
                'theme' => $theme
                  ->getName(),
              ]),
              'attributes' => [
                'title' => $this
                  ->t('Settings for @theme theme', [
                  '@theme' => $theme->info['name'],
                ]),
              ],
            ];
          }
          if (!empty($theme->status)) {
            if (!$theme->is_default) {
              $theme_uninstallable = TRUE;
              if ($theme
                ->getName() == $admin_theme) {
                $theme_uninstallable = FALSE;
              }

              // Check it isn't the base of theme of an installed theme.
              foreach ($theme->required_by as $themename => $dependency) {
                if (!empty($themes[$themename]->status)) {
                  $theme_uninstallable = FALSE;
                }
              }
              if ($theme_uninstallable && $uninstall_theme) {
                $theme->operations[] = [
                  'title' => $this
                    ->t('Uninstall'),
                  'url' => Url::fromRoute('system.theme_uninstall'),
                  'query' => $query,
                  'attributes' => [
                    'title' => $this
                      ->t('Uninstall @theme theme', [
                      '@theme' => $theme->info['name'],
                    ]),
                  ],
                ];
              }
              $theme->operations[] = [
                'title' => $this
                  ->t('Set as default'),
                'url' => Url::fromRoute('system.theme_set_default'),
                'query' => $query,
                'attributes' => [
                  'title' => $this
                    ->t('Set @theme as default theme', [
                    '@theme' => $theme->info['name'],
                  ]),
                ],
              ];
            }
            $admin_theme_options[$theme
              ->getName()] = $theme->info['name'];
          }
          else {
            $theme->operations[] = [
              'title' => $this
                ->t('Install'),
              'url' => Url::fromRoute('system.theme_install'),
              'query' => $query,
              'attributes' => [
                'title' => $this
                  ->t('Install @theme theme', [
                  '@theme' => $theme->info['name'],
                ]),
              ],
            ];
            $theme->operations[] = [
              'title' => $this
                ->t('Install and set as default'),
              'url' => Url::fromRoute('system.theme_set_default'),
              'query' => $query,
              'attributes' => [
                'title' => $this
                  ->t('Install @theme as default theme', [
                  '@theme' => $theme->info['name'],
                ]),
              ],
            ];
          }
        }

        // Add notes to default and administration theme.
        $theme->notes = [];
        if ($theme->is_default) {
          $theme->notes[] = $this
            ->t('default theme');
        }
        if ($theme->is_admin) {
          $theme->notes[] = $this
            ->t('administration theme');
        }

        // Sort installed and uninstalled themes into their own groups.
        $theme_groups[$theme->status ? 'installed' : 'uninstalled'][] = $theme;
      }
    }

    // There are two possible theme groups.
    $theme_group_titles = [
      'installed' => $this
        ->formatPlural(count($theme_groups['installed']), 'Installed theme', 'Installed themes'),
    ];
    if (!empty($theme_groups['uninstalled'])) {
      $theme_group_titles['uninstalled'] = $this
        ->formatPlural(count($theme_groups['uninstalled']), 'Uninstalled theme', 'Uninstalled themes');
    }
    uasort($theme_groups['installed'], 'system_sort_themes');
    $this
      ->moduleHandler()
      ->alter('system_themes_page', $theme_groups);
    $build = [];
    $build[] = [
      '#theme' => 'system_themes_page',
      '#theme_groups' => $theme_groups,
      '#theme_group_titles' => $theme_group_titles,
    ];
    $admin_theme_auth = $this->currentUser
      ->hasPermission("Edit Administration theme");
    if ($admin_theme_auth) {
      $build[] = $this->formBuilder
        ->getForm('Drupal\\system\\Form\\ThemeAdminForm', $admin_theme_options);
    }
    return $build;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AccessController::$currentUser protected property Current user account. Overrides ControllerBase::$currentUser
AccessController::$requestStack protected property Request stack.
AccessController::access public function Check permission.
AccessController::create public static function Instantiates a new instance of this class. Overrides SystemController::create
AccessController::themesPage public function Returns a theme listing. Overrides SystemController::themesPage
AccessController::__construct public function Constructs a AccessController. Overrides SystemController::__construct
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
ModuleDependencyMessageTrait::checkDependencyMessage public function Provides messages for missing modules or incompatible dependencies.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
SystemController::$formBuilder protected property The form builder service. Overrides ControllerBase::$formBuilder
SystemController::$menuLinkTree protected property The menu link tree service.
SystemController::$moduleExtensionList protected property The module extension list.
SystemController::$systemManager protected property System Manager Service.
SystemController::$themeAccess protected property The theme access checker service.
SystemController::$themeHandler protected property The theme handler service.
SystemController::compactPage public function Sets whether the admin menu is in compact mode or not.
SystemController::overview public function Provide the administration overview page.
SystemController::systemAdminMenuBlockPage public function Provides a single block from the administration menu as a page.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.