block.module 14.7 KB
Newer Older
1
<?php
Dries's avatar
Dries committed
2

3 4
/**
 * @file
5
 * Controls the visual building blocks a page is constructed with.
6 7
 */

8
use Drupal\block\BlockInterface;
9
use Drupal\Core\Routing\RouteMatchInterface;
10
use Drupal\language\Entity\ConfigurableLanguage;
11
use Drupal\system\Entity\Menu;
12
use Drupal\block\Entity\Block;
13

14
/**
15
 * Implements hook_help().
16
 */
17
function block_help($route_name, RouteMatchInterface $route_match) {
18 19
  switch ($route_name) {
    case 'help.page.block':
20
      $output = '';
21
      $output .= '<h3>' . t('About') . '</h3>';
22
      $output .= '<p>' . t('The Block module allows you to place blocks in regions and to configure their settings. For more information, see <a href="!blocks-documentation">the online documentation for the Blocks module</a>.', array('!blocks-documentation' => 'https://drupal.org/documentation/modules/block/')) . '</p>';
23 24
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
25 26 27 28 29 30 31 32
      $output .= '<dt>' . t('Placing and moving blocks') . '</dt>';
      $output .= '<dd>' . t('You can place a block by clicking on its title in the in the <em>Place blocks</em> list on the <a href="!blocks">Block layout page</a>. You can then choose the appropriate region from the <em>Region</em> dropdown menu. Once a block has been placed, it can also be moved to a different region by chosing a region from the <em>Region</em> dropdown menu on the Block layout page, or by dragging and dropping it to the right posititon.', array('!blocks' => \Drupal::url('block.admin_display'))) . '</dd>';
      $output .= '<dt>' . t('Demonstrating block regions for a theme') . '</dt>';
      $output .= '<dd>' . t('You can see which region is where in a theme by clicking an the <em>Demonstrate block regions</em> link on the <a href="!blocks">Block layout page</a>. Regions are specific to each theme, so you need to toggle to a different theme first to demonstrate its block regions.', array('!blocks' => \Drupal::url('block.admin_display'))) . '</dd>';
      $output .= '<dt>' . t('Toggling between different themes') . '</dt>';
      $output .= '<dd>' . t('Blocks are placed and configured specifically for each theme. The Block layout page opens with the default theme, but you can toggle to other enabled themes.') . '</dd>';
      $output .= '<dt>' . t('Configuring block settings') . '</dt>';
      $output .= '<dd>' . t('To change the settings of an individual block click on the <em>Configure</em> link on the <a href="!blocks">Block layout page</a>. The available options vary depending on the module that provides the block. For all blocks you can change the block title and toggle whether to display it.', array('!blocks' => Drupal::url('block.admin_display'))) . '</dd>';
33
      $output .= '<dt>' . t('Controlling visibility') . '</dt>';
34 35
      $output .= '<dd>' . t('You can control the visibility of a block by restricting it to specific pages, content types, and/or roles by setting the appropriate options under <em>Visibility settings</em> of the block configuration.') . '</dd>';
      $output .= '<dt>' . t('Adding custom blocks') . '</dt>';
36
      $output .= '<dd>' . t('You can add custom blocks, if the the <em>Custom Block</em> module is enabled on the <a href="!extend">Extend page</a>. For more information, see the <a href="!blockcontent-help">Custom Block help page</a>.', array('!extend' => \Drupal::url('system.modules_list'), '!blockcontent-help' => \Drupal::url('help.page', array('name' => 'block_content')))) . '</dd>';
37
      $output .= '</dl>';
38
      return $output;
39
  }
40
  if ($route_name == 'block.admin_display' || $route_name == 'block.admin_display_theme') {
41
    $demo_theme = $route_match->getParameter('theme') ?: \Drupal::config('system.theme')->get('default');
42
    $themes = list_themes();
43
    $output = '<p>' . t('This page provides a drag-and-drop interface for adding a block to a region, and for controlling the order of blocks within regions. To add a block to a region, or to configure its specific title and visibility settings, click the block title under <em>Place blocks</em>. Since not all themes implement the same regions, or display regions in the same way, blocks are positioned on a per-theme basis. Remember that your changes will not be saved until you click the <em>Save blocks</em> button at the bottom of the page.') . '</p>';
44
    $output .= '<p>' . l(t('Demonstrate block regions (!theme)', array('!theme' => $themes[$demo_theme]->info['name'])), 'admin/structure/block/demo/' . $demo_theme) . '</p>';
45 46
    return $output;
  }
47 48
}

49
/**
50
 * Implements hook_theme().
51 52 53
 */
function block_theme() {
  return array(
54
    'block' => array(
55
      'render element' => 'elements',
56
      'template' => 'block',
57
    ),
58 59 60 61
    'block_list' => array(
      'render element' => 'form',
      'template' => 'block-list',
    ),
62 63 64
  );
}

65
/**
66
 * Implements hook_permission().
67
 */
68
function block_permission() {
69
  return array(
70 71 72
    'administer blocks' => array(
      'title' => t('Administer blocks'),
    ),
73
  );
Dries's avatar
Dries committed
74 75
}

76
/**
77
 * Implements hook_page_build().
78
 *
79
 * Renders blocks into their regions.
80
 */
81
function block_page_build(&$page) {
82
  $theme = \Drupal::theme()->getActiveTheme()->getName();
83

84
  // Fetch a list of regions for the current theme.
85
  $all_regions = system_region_list($theme);
86
  if (\Drupal::routeMatch()->getRouteName() != 'block.admin_demo') {
87 88 89 90 91
    // Create a full page display variant, which will load blocks into their
    // regions.
    $page += \Drupal::service('plugin.manager.display_variant')
      ->createInstance('full_page')
      ->build();
92 93 94
  }
  else {
    // Append region description if we are rendering the regions demo page.
95 96 97 98 99 100
    $visible_regions = array_keys(system_region_list($theme, REGIONS_VISIBLE));
    foreach ($visible_regions as $region) {
      $description = '<div class="block-region">' . $all_regions[$region] . '</div>';
      $page[$region]['block_description'] = array(
        '#markup' => $description,
        '#weight' => 15,
101
      );
102
    }
103 104 105
    $page['page_top']['backlink'] = array(
      '#type' => 'link',
      '#title' => t('Exit block region demonstration'),
106
      '#href' => 'admin/structure/block' . (\Drupal::config('system.theme')->get('default') == $theme ? '' : '/list/' . $theme),
107
      '#options' => array('attributes' => array('class' => array('block-demo-backlink'))),
108 109
      '#weight' => -10,
    );
110 111 112
  }
}

113
/**
114
 * Returns an array of block class instances by theme.
115
 *
116
 * @param $theme
117 118
 *   The theme to rehash blocks for. If not provided, defaults to the currently
 *   used theme.
119
 *
120
 * @return
121
 *   Blocks currently exported by modules.
122
 */
123
function _block_rehash($theme = NULL) {
124
  $theme = $theme ? $theme : \Drupal::config('system.theme')->get('default');
125
  $regions = system_region_list($theme);
126 127
  $blocks = entity_load_multiple_by_properties('block', array('theme' => $theme));
  foreach ($blocks as $block_id => $block) {
128 129 130 131 132 133
    // Remove any invalid block from the list.
    // @todo Remove this check as part of https://drupal.org/node/1776830.
    if (!$block->getPlugin()) {
      unset($blocks[$block_id]);
      continue;
    }
134
    $region = $block->get('region');
135
    $status = $block->status();
136
    // Disable blocks in invalid regions.
137
    if (!empty($region) && $region != BlockInterface::BLOCK_REGION_NONE && !isset($regions[$region]) && $status) {
138
      drupal_set_message(t('The block %info was assigned to the invalid region %region and has been disabled.', array('%info' => $block_id, '%region' => $region)), 'warning');
139 140
      // Disabled modules are moved into the BlockInterface::BLOCK_REGION_NONE
      // later so no need to move the block to another region.
141
      $block->disable()->save();
142
    }
143
    // Set region to none if not enabled.
144
    if (!$status && $region != BlockInterface::BLOCK_REGION_NONE) {
145
      $block->set('region', BlockInterface::BLOCK_REGION_NONE);
146
      $block->save();
147
    }
148
  }
Dries's avatar
Dries committed
149 150
  return $blocks;
}
Dries's avatar
Dries committed
151

152
/**
153 154 155 156
 * Initializes blocks for enabled themes.
 *
 * @param $theme_list
 *   An array of theme names.
157
 */
158 159 160
function block_themes_enabled($theme_list) {
  foreach ($theme_list as $theme) {
    block_theme_initialize($theme);
161 162 163 164
  }
}

/**
165
 * Assigns an initial, default set of blocks for a theme.
166
 *
167 168 169 170
 * This function is called the first time a new theme is enabled. The new theme
 * gets a copy of the default theme's blocks, with the difference that if a
 * particular region isn't available in the new theme, the block is assigned
 * to the new theme's default region.
171
 *
172 173 174
 * @param $theme
 *   The name of a theme.
 */
175
function block_theme_initialize($theme) {
176
  // Initialize theme's blocks if none already registered.
177
  $has_blocks = entity_load_multiple_by_properties('block', array('theme' => $theme));
178
  if (!$has_blocks) {
179
    $default_theme = \Drupal::config('system.theme')->get('default');
180 181
    // Apply only to new theme's visible regions.
    $regions = system_region_list($theme, REGIONS_VISIBLE);
182 183
    $default_theme_blocks = entity_load_multiple_by_properties('block', array('theme' => $default_theme));
    foreach ($default_theme_blocks as $default_theme_block_id => $default_theme_block) {
184 185 186 187 188 189
      if (strpos($default_theme_block_id, $default_theme . '_') === 0) {
        $id = str_replace($default_theme, $theme, $default_theme_block_id);
      }
      else {
        $id = $theme . '_' . $default_theme_block_id;
      }
190
      $block = $default_theme_block->createDuplicate();
191 192
      $block->set('id', $id);
      $block->set('theme', $theme);
193 194
      // If the region isn't supported by the theme, assign the block to the
      // theme's default region.
195 196
      if (!isset($regions[$block->get('region')])) {
        $block->set('region', system_default_region($theme));
197
      }
198
      $block->save();
199 200 201 202
    }
  }
}

203 204 205 206
/**
 * Implements hook_rebuild().
 */
function block_rebuild() {
207 208 209 210
  foreach (list_themes() as $name => $data) {
    if ($data->status) {
      _block_rehash($name);
    }
211
  }
212
}
213

214 215 216 217 218 219
/**
 * Implements hook_theme_suggestions_HOOK().
 */
function block_theme_suggestions_block(array $variables) {
  $suggestions = array();

220
  $suggestions[] = 'block__' . $variables['elements']['#configuration']['provider'];
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
  // Hyphens (-) and underscores (_) play a special role in theme suggestions.
  // Theme suggestions should only contain underscores, because within
  // drupal_find_theme_templates(), underscores are converted to hyphens to
  // match template file names, and then converted back to underscores to match
  // pre-processing and other function names. So if your theme suggestion
  // contains a hyphen, it will end up as an underscore after this conversion,
  // and your function names won't be recognized. So, we need to convert
  // hyphens to underscores in block deltas for the theme suggestions.

  // We can safely explode on : because we know the Block plugin type manager
  // enforces that delimiter for all derivatives.
  $parts = explode(':', $variables['elements']['#plugin_id']);
  $suggestion = 'block';
  while ($part = array_shift($parts)) {
    $suggestions[] = $suggestion .= '__' . strtr($part, '-', '_');
  }

238 239
  if (!empty($variables['elements']['#id'])) {
    $suggestions[] = 'block__' . $variables['elements']['#id'];
240 241 242 243 244
  }

  return $suggestions;
}

245
/**
246 247 248
 * Prepares variables for block templates.
 *
 * Default template: block.html.twig.
249
 *
250
 * Prepares the values passed to the theme_block function to be passed
251 252
 * into a pluggable template engine. Uses block properties to generate a
 * series of template file suggestions. If none are found, the default
253
 * block.html.twig is used.
254
 *
255 256 257
 * Most themes use their own copy of block.html.twig. The default is located
 * inside "core/modules/block/templates/block.html.twig". Look in there for the
 * full list of available variables.
258
 *
259 260 261 262
 * @param array $variables
 *   An associative array containing:
 *   - elements: An associative array containing the properties of the element.
 *     Properties used: #block, #configuration, #children, #plugin_id.
263 264
 */
function template_preprocess_block(&$variables) {
265 266
  $variables['configuration'] = $variables['elements']['#configuration'];
  $variables['plugin_id'] = $variables['elements']['#plugin_id'];
267 268
  $variables['base_plugin_id'] = $variables['elements']['#base_plugin_id'];
  $variables['derivative_plugin_id'] = $variables['elements']['#derivative_plugin_id'];
269 270
  $variables['label'] = !empty($variables['configuration']['label_display']) ? $variables['configuration']['label'] : '';
  $variables['content'] = $variables['elements']['content'];
271 272 273 274 275
  // A block's label is configuration: it is static. Allow dynamic labels to be
  // set in the render array.
  if (isset($variables['elements']['content']['#title']) && !empty($variables['configuration']['label_display'])) {
    $variables['label'] = $variables['elements']['content']['#title'];
  }
276

277
  $variables['attributes']['class'][] = 'block';
278
  $variables['attributes']['class'][] = drupal_html_class('block-' . $variables['configuration']['provider']);
279

280
  // Add default class for block content.
281
  $variables['content_attributes']['class'][] = 'content';
282

283
  // Create a valid HTML ID and make sure it is unique.
284 285
  if (!empty($variables['elements']['#id'])) {
    $variables['attributes']['id'] = drupal_html_id('block-' . $variables['elements']['#id']);
286
  }
287 288

  // Proactively add aria-describedby if possible to improve accessibility.
289 290 291
  if ($variables['label'] && isset($variables['attributes']['role'])) {
    $variables['title_attributes']['id'] = drupal_html_id($variables['label']);
    $variables['attributes']['aria-describedby'] = $variables['title_attributes']['id'];
292 293
  }

294
}
295

296
/**
297
 * Implements hook_ENTITY_TYPE_delete() for user_role entities.
298
 *
299
 * Removes deleted role from blocks that use it.
300 301
 */
function block_user_role_delete($role) {
302
  foreach (Block::loadMultiple() as $block) {
303 304 305 306 307
    /** @var $block \Drupal\block\BlockInterface */
    $visibility = $block->getVisibility();
    if (isset($visibility['user_role']['roles'][$role->id()])) {
      unset($visibility['user_role']['roles'][$role->id()]);
      $block->getPlugin()->setVisibilityConfig('user_role', $visibility['user_role']);
308
      $block->save();
309 310
    }
  }
311 312
}

313
/**
314
 * Implements hook_ENTITY_TYPE_delete() for menu entities.
315
 */
316 317
function block_menu_delete(Menu $menu) {
  if (!$menu->isSyncing()) {
318
    foreach (Block::loadMultiple() as $block) {
319 320 321
      if ($block->get('plugin') == 'system_menu_block:' . $menu->id()) {
        $block->delete();
      }
322 323
    }
  }
324 325
}

326
/**
327
 * Implements hook_ENTITY_TYPE_delete() for 'configurable_language'.
328 329 330
 *
 * Delete the potential block visibility settings of the deleted language.
 */
331
function block_configurable_language_delete(ConfigurableLanguage $language) {
332
  // Remove the block visibility settings for the deleted language.
333
  foreach (Block::loadMultiple() as $block) {
334 335
    /** @var $block \Drupal\block\BlockInterface */
    $visibility = $block->getVisibility();
336 337
    if (isset($visibility['language']['langcodes'][$language->id()])) {
      unset($visibility['language']['langcodes'][$language->id()]);
338
      $block->getPlugin()->setVisibilityConfig('language', $visibility['language']);
339
      $block->save();
340 341
    }
  }
342
}