block.module 13 KB

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