SystemController.php 16.2 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\system\Controller\SystemController.
 */

namespace Drupal\system\Controller;

10
use Drupal\Component\Serialization\Json;
11 12
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\Query\QueryFactory;
13 14
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Form\FormBuilderInterface;
15 16
use Drupal\Core\Menu\MenuLinkTreeInterface;
use Drupal\Core\Menu\MenuTreeParameters;
17
use Drupal\Core\Theme\ThemeAccessCheck;
18
use Drupal\system\SystemManager;
19 20 21 22 23
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Returns responses for System routes.
 */
24
class SystemController extends ControllerBase {
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

  /**
   * The entity query factory object.
   *
   * @var \Drupal\Core\Entity\Query\QueryFactory
   */
  protected $queryFactory;

  /**
   * System Manager Service.
   *
   * @var \Drupal\system\SystemManager
   */
  protected $systemManager;

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
  /**
   * The theme access checker service.
   *
   * @var \Drupal\Core\Theme\ThemeAccessCheck
   */
  protected $themeAccess;

  /**
   * The form builder service.
   *
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
  protected $formBuilder;

  /**
   * The theme handler service.
   *
   * @var \Drupal\Core\Extension\ThemeHandlerInterface
   */
  protected $themeHandler;

61 62 63 64 65 66 67
  /**
   * The menu link tree service.
   *
   * @var \Drupal\Core\Menu\MenuLinkTreeInterface
   */
  protected $menuLinkTree;

68
  /**
69
   * Constructs a new SystemController.
70 71 72 73 74
   *
   * @param \Drupal\system\SystemManager $systemManager
   *   System manager service.
   * @param \Drupal\Core\Entity\Query\QueryFactory $queryFactory
   *   The entity query object.
75 76 77 78 79 80
   * @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.
81 82
   * @param \Drupal\Core\Menu\MenuLinkTreeInterface
   *   The menu link tree service.
83
   */
84
  public function __construct(SystemManager $systemManager, QueryFactory $queryFactory, ThemeAccessCheck $theme_access, FormBuilderInterface $form_builder, ThemeHandlerInterface $theme_handler, MenuLinkTreeInterface $menu_link_tree) {
85 86
    $this->systemManager = $systemManager;
    $this->queryFactory = $queryFactory;
87 88 89
    $this->themeAccess = $theme_access;
    $this->formBuilder = $form_builder;
    $this->themeHandler = $theme_handler;
90
    $this->menuLinkTree = $menu_link_tree;
91
  }
92 93 94 95 96

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
97 98
    return new static(
      $container->get('system.manager'),
99 100 101
      $container->get('entity.query'),
      $container->get('access_check.theme'),
      $container->get('form_builder'),
102 103
      $container->get('theme_handler'),
      $container->get('menu.link_tree')
104 105 106 107 108 109
    );
  }

  /**
   * Provide the administration overview page.
   *
110 111
   * @param string $link_id
   *   The ID of the administrative path link for which to display child links.
112
   *
113 114 115
   * @return array
   *   A renderable array of the administration overview page.
   */
116
  public function overview($link_id) {
117 118 119 120
    // Check for status report errors.
    if ($this->systemManager->checkRequirements() && $this->currentUser()->hasPermission('administer site configuration')) {
      drupal_set_message($this->t('One or more problems were detected with your Drupal installation. Check the <a href="@status">status report</a> for more information.', array('@status' => url('admin/reports/status'))), 'error');
    }
121 122
    // Load all menu links below it.
    $parameters = new MenuTreeParameters();
123
    $parameters->setRoot($link_id)->excludeRoot()->setTopLevelOnly()->onlyEnabledLinks();
124 125 126 127 128 129
    $tree = $this->menuLinkTree->load(NULL, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $tree = $this->menuLinkTree->transform($tree, $manipulators);
130
    $blocks = array();
131 132 133 134 135 136 137 138 139 140 141
    foreach ($tree as $key => $element) {
      $link = $element->link;
      $block['title'] = $link->getTitle();
      $block['description'] = $link->getDescription();
      $block['content'] = array(
        '#theme' => 'admin_block_content',
        '#content' => $this->systemManager->getAdminBlock($link),
      );

      if (!empty($block['content']['#content'])) {
        $blocks[$key] = $block;
142 143
      }
    }
144

145 146 147 148 149 150 151 152 153 154 155 156
    if ($blocks) {
      ksort($blocks);
      return array(
        '#theme' => 'admin_page',
        '#blocks' => $blocks,
      );
    }
    else {
      return array(
        '#markup' => $this->t('You do not have any administrative items.'),
      );
    }
157 158 159 160 161 162 163 164 165 166
  }

  /**
   * Sets whether the admin menu is in compact mode or not.
   *
   * @param string $mode
   *   Valid values are 'on' and 'off'.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   */
167
  public function compactPage($mode) {
168
    user_cookie_save(array('admin_compact_mode' => ($mode == 'on')));
169
    return $this->redirect('<front>');
170 171
  }

172 173 174 175 176 177 178
  /**
   * Provides a single block from the administration menu as a page.
   */
  public function systemAdminMenuBlockPage() {
    return $this->systemManager->getBlockContents();
  }

179
  /**
180 181 182 183
   * Returns a theme listing.
   *
   * @return string
   *   An HTML string of the theme listing page.
184 185
   *
   * @todo Move into ThemeController.
186 187
   */
  public function themesPage() {
188
    $config = $this->config('system.theme');
189 190
    // Get all available themes.
    $themes = $this->themeHandler->rebuildThemeData();
191 192 193
    uasort($themes, 'system_sort_modules_by_info_name');

    $theme_default = $config->get('default');
194
    $theme_groups  = array('enabled' => array(), 'disabled' => array());
195
    $admin_theme = $config->get('admin');
196
    $admin_theme_options = array();
197 198 199 200 201

    foreach ($themes as &$theme) {
      if (!empty($theme->info['hidden'])) {
        continue;
      }
202
      $theme->is_default = ($theme->getName() == $theme_default);
203 204 205 206

      // Identify theme screenshot.
      $theme->screenshot = NULL;
      // Create a list which includes the current theme and all its base themes.
207 208 209
      if (isset($themes[$theme->getName()]->base_themes)) {
        $theme_keys = array_keys($themes[$theme->getName()]->base_themes);
        $theme_keys[] = $theme->getName();
210 211
      }
      else {
212
        $theme_keys = array($theme->getName());
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
      }
      // 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 = array(
            'uri' => $themes[$theme_key]->info['screenshot'],
            'alt' => $this->t('Screenshot for !theme theme', array('!theme' => $theme->info['name'])),
            'title' => $this->t('Screenshot for !theme theme', array('!theme' => $theme->info['name'])),
            'attributes' => array('class' => array('screenshot')),
          );
          break;
        }
      }

      if (empty($theme->status)) {
        // Ensure this theme is compatible with this version of core.
        // Require the 'content' region to make sure the main page
        // content has a common place in all themes.
        $theme->incompatible_core = !isset($theme->info['core']) || ($theme->info['core'] != \DRUPAL::CORE_COMPATIBILITY) || !isset($theme->info['regions']['content']);
        $theme->incompatible_php = version_compare(phpversion(), $theme->info['php']) < 0;
        // Confirmed that the base theme is available.
        $theme->incompatible_base = isset($theme->info['base theme']) && !isset($themes[$theme->info['base theme']]);
        // Confirm that the theme engine is available.
        $theme->incompatible_engine = isset($theme->info['engine']) && !isset($theme->owner);
      }
      $theme->operations = array();
      if (!empty($theme->status) || !$theme->incompatible_core && !$theme->incompatible_php && !$theme->incompatible_base && !$theme->incompatible_engine) {
        // Create the operations links.
241 242
        $query['theme'] = $theme->getName();
        if ($this->themeAccess->checkAccess($theme->getName())) {
243 244 245
          $theme->operations[] = array(
            'title' => $this->t('Settings'),
            'route_name' => 'system.theme_settings_theme',
246
            'route_parameters' => array('theme' => $theme->getName()),
247 248 249 250 251
            'attributes' => array('title' => $this->t('Settings for !theme theme', array('!theme' => $theme->info['name']))),
          );
        }
        if (!empty($theme->status)) {
          if (!$theme->is_default) {
252
            if ($theme->getName() != $admin_theme) {
253 254 255 256 257 258 259 260
              $theme->operations[] = array(
                'title' => $this->t('Disable'),
                'route_name' => 'system.theme_disable',
                'query' => $query,
                'attributes' => array('title' => $this->t('Disable !theme theme', array('!theme' => $theme->info['name']))),
              );
            }
            $theme->operations[] = array(
261
              'title' => $this->t('Set as default'),
262 263 264 265 266
              'route_name' => 'system.theme_set_default',
              'query' => $query,
              'attributes' => array('title' => $this->t('Set !theme as default theme', array('!theme' => $theme->info['name']))),
            );
          }
267
          $admin_theme_options[$theme->getName()] = $theme->info['name'];
268 269 270 271 272 273 274 275 276
        }
        else {
          $theme->operations[] = array(
            'title' => $this->t('Enable'),
            'route_name' => 'system.theme_enable',
            'query' => $query,
            'attributes' => array('title' => $this->t('Enable !theme theme', array('!theme' => $theme->info['name']))),
          );
          $theme->operations[] = array(
277
            'title' => $this->t('Enable and set as default'),
278 279 280 281 282 283 284 285 286 287 288 289 290 291
            'route_name' => 'system.theme_set_default',
            'query' => $query,
            'attributes' => array('title' => $this->t('Enable !theme as default theme', array('!theme' => $theme->info['name']))),
          );
        }
      }

      // Add notes to default and administration theme.
      $theme->notes = array();
      $theme->classes = array();
      if ($theme->is_default) {
        $theme->classes[] = 'theme-default';
        $theme->notes[] = $this->t('default theme');
      }
292
      if ($theme->getName() == $admin_theme || ($theme->is_default && $admin_theme == '0')) {
293 294 295 296 297 298 299 300 301 302
        $theme->classes[] = 'theme-admin';
        $theme->notes[] = $this->t('admin theme');
      }

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

    // There are two possible theme groups.
    $theme_group_titles = array(
303
      'enabled' => $this->formatPlural(count($theme_groups['enabled']), 'Enabled theme', 'Enabled themes'),
304 305
    );
    if (!empty($theme_groups['disabled'])) {
306
      $theme_group_titles['disabled'] = $this->formatPlural(count($theme_groups['disabled']), 'Disabled theme', 'Disabled themes');
307 308 309 310 311 312 313 314 315 316 317 318 319 320
    }

    uasort($theme_groups['enabled'], 'system_sort_themes');
    $this->moduleHandler()->alter('system_themes_page', $theme_groups);

    $build = array();
    $build[] = array(
      '#theme' => 'system_themes_page',
      '#theme_groups' => $theme_groups,
      '#theme_group_titles' => $theme_group_titles,
    );
    $build[] = $this->formBuilder->getForm('Drupal\system\Form\ThemeAdminForm', $admin_theme_options);

    return $build;
321 322
  }

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
  /**
   * #post_render_cache callback; sets the "active" class on relevant links.
   *
   * This is a PHP implementation of the drupal.active-link JavaScript library.
   *
   * @param array $element
   *  A renderable array with the following keys:
   *    - #markup
   *    - #attached
   * @param array $context
   *   An array with the following keys:
   *   - path: the system path of the currently active page
   *   - front: whether the current page is the front page (which implies the
   *     current path might also be <front>)
   *   - language: the language code of the currently active page
   *   - query: the query string for the currently active page
   *
   * @return array
   *   The updated renderable array.
   *
   * @todo Once a future version of PHP supports parsing HTML5 properly
   *   (i.e. doesn't fail on https://drupal.org/comment/7938201#comment-7938201)
   *   then we can get rid of this manual parsing and use DOMDocument instead.
   */
  public static function setLinkActiveClass(array $element, array $context) {
    $search_key_current_path = 'data-drupal-link-system-path="' . $context['path'] . '"';
    $search_key_front = 'data-drupal-link-system-path="&lt;front&gt;"';

    // An active link's path is equal to the current path, so search the HTML
    // for an attribute with that value.
    $offset = 0;
    while ((strpos($element['#markup'], 'data-drupal-link-system-path="' . $context['path'] . '"', $offset) !== FALSE || ($context['front'] && strpos($element['#markup'], 'data-drupal-link-system-path="&lt;front&gt;"', $offset) !== FALSE))) {
      $pos_current_path = strpos($element['#markup'], $search_key_current_path, $offset);
      $pos_front = strpos($element['#markup'], $search_key_front, $offset);

      // Determine which of the two values matched: the exact path, or the
      // <front> special case.
      $pos_match = NULL;
      $type_match = NULL;
      if ($pos_current_path !== FALSE) {
        $pos_match = $pos_current_path;
        $type_match = 'path';
      }
      elseif ($context['front'] && $pos_front !== FALSE) {
        $pos_match = $pos_front;
        $type_match = 'front';
      }

      // Find beginning and ending of opening tag.
      $pos_tag_start = NULL;
      for ($i = $pos_match; $pos_tag_start === NULL && $i > 0; $i--) {
        if ($element['#markup'][$i] === '<') {
          $pos_tag_start = $i;
        }
      }
      $pos_tag_end = NULL;
      for ($i = $pos_match; $pos_tag_end === NULL && $i < strlen($element['#markup']); $i++) {
        if ($element['#markup'][$i] === '>') {
          $pos_tag_end = $i;
        }
      }

      // Get the HTML: this will be the opening part of a single tag, e.g.:
      //   <a href="/" data-drupal-link-system-path="&lt;front&gt;">
      $tag = substr($element['#markup'], $pos_tag_start, $pos_tag_end - $pos_tag_start + 1);

      // Parse it into a DOMDocument so we can reliably read and modify
      // attributes.
      $dom = new \DOMDocument();
      @$dom->loadHTML('<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body>' . $tag . '</body></html>');
      $node = $dom->getElementsByTagName('body')->item(0)->firstChild;

      // The language of an active link is equal to the current language.
      $is_active = TRUE;
      if ($context['language']) {
        if ($node->hasAttribute('hreflang') && $node->getAttribute('hreflang') !== $context['language']) {
          $is_active = FALSE;
        }
      }
      // The query parameters of an active link are equal to the current
      // parameters.
      if ($is_active) {
        if ($context['query']) {
          if (!$node->hasAttribute('data-drupal-link-query') || $node->getAttribute('data-drupal-link-query') !== Json::encode($context['query'])) {
            $is_active = FALSE;
          }
        }
        else {
          if ($node->hasAttribute('data-drupal-link-query')) {
            $is_active = FALSE;
          }
        }
      }

      // Only if the the path, the language and the query match, we set the
      // "active" class.
      if ($is_active) {
        $class = $node->getAttribute('class');
        if (strlen($class) > 0) {
          $class .= ' ';
        }
        $class .= 'active';
        $node->setAttribute('class', $class);

        // Get the updated tag.
        $updated_tag = $dom->saveXML($node, LIBXML_NOEMPTYTAG);
        // saveXML() added a closing tag, remove it.
        $updated_tag = substr($updated_tag, 0, strrpos($updated_tag, '<'));

        $element['#markup'] = str_replace($tag, $updated_tag, $element['#markup']);

        // Ensure we only search the remaining HTML.
        $offset = $pos_tag_end - strlen($tag) + strlen($updated_tag);
      }
      else {
        // Ensure we only search the remaining HTML.
        $offset = $pos_tag_end + 1;
      }
    }

    return $element;
  }

446
}