28fd7b30c6319635cdcdc12ac2e1d571501a4cc5
[yaffs-website] / web / core / modules / block / block.module
1 <?php
2
3 /**
4  * @file
5  * Controls the visual building blocks a page is constructed with.
6  */
7
8 use Drupal\Component\Utility\Html;
9 use Drupal\Core\Routing\RouteMatchInterface;
10 use Drupal\Core\Url;
11 use Drupal\language\ConfigurableLanguageInterface;
12 use Drupal\system\Entity\Menu;
13 use Drupal\block\Entity\Block;
14
15 /**
16  * Implements hook_help().
17  */
18 function block_help($route_name, RouteMatchInterface $route_match) {
19   switch ($route_name) {
20     case 'help.page.block':
21       $block_content = \Drupal::moduleHandler()->moduleExists('block_content') ? \Drupal::url('help.page', ['name' => 'block_content']) : '#';
22       $output = '';
23       $output .= '<h3>' . t('About') . '</h3>';
24       $output .= '<p>' . t('The Block module allows you to place blocks in regions of your installed themes, and configure block settings. For more information, see the <a href=":blocks-documentation">online documentation for the Block module</a>.', [':blocks-documentation' => 'https://www.drupal.org/documentation/modules/block/']) . '</p>';
25       $output .= '<h3>' . t('Uses') . '</h3>';
26       $output .= '<dl>';
27       $output .= '<dt>' . t('Placing and moving blocks') . '</dt>';
28       $output .= '<dd>' . t('You can place a new block in a region by selecting <em>Place block</em> on the <a href=":blocks">Block layout page</a>. Once a block is placed, it can be moved to a different region by drag-and-drop or by using the <em>Region</em> drop-down list, and then clicking <em>Save blocks</em>.', [':blocks' => \Drupal::url('block.admin_display')]) . '</dd>';
29       $output .= '<dt>' . t('Toggling between different themes') . '</dt>';
30       $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 installed themes.') . '</dd>';
31       $output .= '<dt>' . t('Demonstrating block regions for a theme') . '</dt>';
32       $output .= '<dd>' . t('You can see where the regions are for the current theme by clicking the <em>Demonstrate block regions</em> link on the <a href=":blocks">Block layout page</a>. Regions are specific to each theme.', [':blocks' => \Drupal::url('block.admin_display')]) . '</dd>';
33       $output .= '<dt>' . t('Configuring block settings') . '</dt>';
34       $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.', [':blocks' => Drupal::url('block.admin_display')]) . '</dd>';
35       $output .= '<dt>' . t('Controlling visibility') . '</dt>';
36       $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>';
37       $output .= '<dt>' . t('Adding custom blocks') . '</dt>';
38       $output .= '<dd>' . t('You can add custom blocks, if the <em>Custom Block</em> module is installed. For more information, see the <a href=":blockcontent-help">Custom Block help page</a>.', [':blockcontent-help' => $block_content]) . '</dd>';
39       $output .= '</dl>';
40       return $output;
41   }
42   if ($route_name == 'block.admin_display' || $route_name == 'block.admin_display_theme') {
43     $demo_theme = $route_match->getParameter('theme') ?: \Drupal::config('system.theme')->get('default');
44     $themes = \Drupal::service('theme_handler')->listInfo();
45     $output = '<p>' . t('Block placement is specific to each theme on your site. Changes will not be saved until you click <em>Save blocks</em> at the bottom of the page.') . '</p>';
46     $output .= '<p>' . \Drupal::l(t('Demonstrate block regions (@theme)', ['@theme' => $themes[$demo_theme]->info['name']]), new Url('block.admin_demo', ['theme' => $demo_theme])) . '</p>';
47     return $output;
48   }
49 }
50
51 /**
52  * Implements hook_theme().
53  */
54 function block_theme() {
55   return [
56     'block' => [
57       'render element' => 'elements',
58     ],
59   ];
60 }
61
62 /**
63  * Implements hook_page_top().
64  */
65 function block_page_top(array &$page_top) {
66   if (\Drupal::routeMatch()->getRouteName() === 'block.admin_demo') {
67     $theme = \Drupal::theme()->getActiveTheme()->getName();
68     $page_top['backlink'] = [
69       '#type' => 'link',
70       '#title' => t('Exit block region demonstration'),
71       '#options' => ['attributes' => ['class' => ['block-demo-backlink']]],
72       '#weight' => -10,
73     ];
74     if (\Drupal::config('system.theme')->get('default') == $theme) {
75       $page_top['backlink']['#url'] = Url::fromRoute('block.admin_display');
76     }
77     else {
78       $page_top['backlink']['#url'] = Url::fromRoute('block.admin_display_theme', ['theme' => $theme]);
79     }
80   }
81 }
82
83 /**
84  * Initializes blocks for installed themes.
85  *
86  * @param $theme_list
87  *   An array of theme names.
88  */
89 function block_themes_installed($theme_list) {
90   foreach ($theme_list as $theme) {
91     // Don't initialize themes that are not displayed in the UI.
92     if (\Drupal::service('theme_handler')->hasUi($theme)) {
93       block_theme_initialize($theme);
94     }
95   }
96 }
97
98 /**
99  * Assigns an initial, default set of blocks for a theme.
100  *
101  * This function is called the first time a new theme is installed. The new
102  * theme gets a copy of the default theme's blocks, with the difference that if
103  * a particular region isn't available in the new theme, the block is assigned
104  * to the new theme's default region.
105  *
106  * @param $theme
107  *   The name of a theme.
108  */
109 function block_theme_initialize($theme) {
110   // Initialize theme's blocks if none already registered.
111   $has_blocks = \Drupal::entityTypeManager()->getStorage('block')->loadByProperties(['theme' => $theme]);
112   if (!$has_blocks) {
113     $default_theme = \Drupal::config('system.theme')->get('default');
114     // Apply only to new theme's visible regions.
115     $regions = system_region_list($theme, REGIONS_VISIBLE);
116     $default_theme_blocks = \Drupal::entityTypeManager()->getStorage('block')->loadByProperties(['theme' => $default_theme]);
117     foreach ($default_theme_blocks as $default_theme_block_id => $default_theme_block) {
118       if (strpos($default_theme_block_id, $default_theme . '_') === 0) {
119         $id = str_replace($default_theme, $theme, $default_theme_block_id);
120       }
121       else {
122         $id = $theme . '_' . $default_theme_block_id;
123       }
124       $block = $default_theme_block->createDuplicateBlock($id, $theme);
125       // If the region isn't supported by the theme, assign the block to the
126       // theme's default region.
127       if (!isset($regions[$block->getRegion()])) {
128         $block->setRegion(system_default_region($theme));
129       }
130       $block->save();
131     }
132   }
133 }
134
135 /**
136  * Implements hook_rebuild().
137  */
138 function block_rebuild() {
139   foreach (\Drupal::service('theme_handler')->listInfo() as $theme => $data) {
140     if ($data->status) {
141       $regions = system_region_list($theme);
142       /** @var \Drupal\block\BlockInterface[] $blocks */
143       $blocks = \Drupal::entityTypeManager()->getStorage('block')->loadByProperties(['theme' => $theme]);
144       foreach ($blocks as $block_id => $block) {
145         // Disable blocks in invalid regions.
146         if (!isset($regions[$block->getRegion()])) {
147           if ($block->status()) {
148             \Drupal::messenger()
149               ->addWarning(t('The block %info was assigned to the invalid region %region and has been disabled.', [
150                 '%info' => $block_id,
151                 '%region' => $block->getRegion(),
152               ]));
153           }
154           $block
155             ->setRegion(system_default_region($theme))
156             ->disable()
157             ->save();
158         }
159       }
160     }
161   }
162 }
163
164 /**
165  * Implements hook_theme_suggestions_HOOK().
166  */
167 function block_theme_suggestions_block(array $variables) {
168   $suggestions = [];
169
170   $suggestions[] = 'block__' . $variables['elements']['#configuration']['provider'];
171   // Hyphens (-) and underscores (_) play a special role in theme suggestions.
172   // Theme suggestions should only contain underscores, because within
173   // drupal_find_theme_templates(), underscores are converted to hyphens to
174   // match template file names, and then converted back to underscores to match
175   // pre-processing and other function names. So if your theme suggestion
176   // contains a hyphen, it will end up as an underscore after this conversion,
177   // and your function names won't be recognized. So, we need to convert
178   // hyphens to underscores in block deltas for the theme suggestions.
179
180   // We can safely explode on : because we know the Block plugin type manager
181   // enforces that delimiter for all derivatives.
182   $parts = explode(':', $variables['elements']['#plugin_id']);
183   $suggestion = 'block';
184   while ($part = array_shift($parts)) {
185     $suggestions[] = $suggestion .= '__' . strtr($part, '-', '_');
186   }
187
188   if (!empty($variables['elements']['#id'])) {
189     $suggestions[] = 'block__' . $variables['elements']['#id'];
190   }
191
192   return $suggestions;
193 }
194
195 /**
196  * Prepares variables for block templates.
197  *
198  * Default template: block.html.twig.
199  *
200  * Prepares the values passed to the theme_block function to be passed
201  * into a pluggable template engine. Uses block properties to generate a
202  * series of template file suggestions. If none are found, the default
203  * block.html.twig is used.
204  *
205  * Most themes use their own copy of block.html.twig. The default is located
206  * inside "core/modules/block/templates/block.html.twig". Look in there for the
207  * full list of available variables.
208  *
209  * @param array $variables
210  *   An associative array containing:
211  *   - elements: An associative array containing the properties of the element.
212  *     Properties used: #block, #configuration, #children, #plugin_id.
213  */
214 function template_preprocess_block(&$variables) {
215   $variables['configuration'] = $variables['elements']['#configuration'];
216   $variables['plugin_id'] = $variables['elements']['#plugin_id'];
217   $variables['base_plugin_id'] = $variables['elements']['#base_plugin_id'];
218   $variables['derivative_plugin_id'] = $variables['elements']['#derivative_plugin_id'];
219   $variables['label'] = !empty($variables['configuration']['label_display']) ? $variables['configuration']['label'] : '';
220   $variables['content'] = $variables['elements']['content'];
221   // A block's label is configuration: it is static. Allow dynamic labels to be
222   // set in the render array.
223   if (isset($variables['elements']['content']['#title']) && !empty($variables['configuration']['label_display'])) {
224     $variables['label'] = $variables['elements']['content']['#title'];
225   }
226
227   // Create a valid HTML ID and make sure it is unique.
228   if (!empty($variables['elements']['#id'])) {
229     $variables['attributes']['id'] = Html::getUniqueId('block-' . $variables['elements']['#id']);
230   }
231
232   // Proactively add aria-describedby if possible to improve accessibility.
233   if ($variables['label'] && isset($variables['attributes']['role'])) {
234     $variables['title_attributes']['id'] = Html::getUniqueId($variables['label']);
235     $variables['attributes']['aria-describedby'] = $variables['title_attributes']['id'];
236   }
237
238 }
239
240 /**
241  * Implements hook_ENTITY_TYPE_delete() for user_role entities.
242  *
243  * Removes deleted role from blocks that use it.
244  */
245 function block_user_role_delete($role) {
246   foreach (Block::loadMultiple() as $block) {
247     /** @var $block \Drupal\block\BlockInterface */
248     $visibility = $block->getVisibility();
249     if (isset($visibility['user_role']['roles'][$role->id()])) {
250       unset($visibility['user_role']['roles'][$role->id()]);
251       $block->setVisibilityConfig('user_role', $visibility['user_role']);
252       $block->save();
253     }
254   }
255 }
256
257 /**
258  * Implements hook_ENTITY_TYPE_delete() for menu entities.
259  */
260 function block_menu_delete(Menu $menu) {
261   if (!$menu->isSyncing()) {
262     foreach (Block::loadMultiple() as $block) {
263       if ($block->getPluginId() == 'system_menu_block:' . $menu->id()) {
264         $block->delete();
265       }
266     }
267   }
268 }
269
270 /**
271  * Implements hook_ENTITY_TYPE_delete() for 'configurable_language'.
272  *
273  * Delete the potential block visibility settings of the deleted language.
274  */
275 function block_configurable_language_delete(ConfigurableLanguageInterface $language) {
276   // Remove the block visibility settings for the deleted language.
277   foreach (Block::loadMultiple() as $block) {
278     /** @var $block \Drupal\block\BlockInterface */
279     $visibility = $block->getVisibility();
280     if (isset($visibility['language']['langcodes'][$language->id()])) {
281       unset($visibility['language']['langcodes'][$language->id()]);
282       $block->setVisibilityConfig('language', $visibility['language']);
283       $block->save();
284     }
285   }
286 }