1. 8.3.x core/modules/block/block.module
  2. 8.0.x core/modules/block/block.module
  3. 8.1.x core/modules/block/block.module
  4. 8.2.x core/modules/block/block.module
  5. 8.4.x core/modules/block/block.module
  6. 4.6.x modules/block.module
  7. 4.7.x modules/block.module
  8. 5.x modules/block/block.module
  9. 6.x modules/block/block.module
  10. 7.x modules/block/block.module

Controls the visual building blocks a page is constructed with.

File

modules/block/block.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Controls the visual building blocks a page is constructed with.
  5. */
  6. /**
  7. * Denotes that a block is not enabled in any region and should not be shown.
  8. */
  9. define('BLOCK_REGION_NONE', -1);
  10. /**
  11. * Users cannot control whether or not they see this block.
  12. */
  13. define('BLOCK_CUSTOM_FIXED', 0);
  14. /**
  15. * Shows this block by default, but lets individual users hide it.
  16. */
  17. define('BLOCK_CUSTOM_ENABLED', 1);
  18. /**
  19. * Hides this block by default but lets individual users show it.
  20. */
  21. define('BLOCK_CUSTOM_DISABLED', 2);
  22. /**
  23. * Shows this block on every page except the listed pages.
  24. */
  25. define('BLOCK_VISIBILITY_NOTLISTED', 0);
  26. /**
  27. * Shows this block on only the listed pages.
  28. */
  29. define('BLOCK_VISIBILITY_LISTED', 1);
  30. /**
  31. * Shows this block if the associated PHP code returns TRUE.
  32. */
  33. define('BLOCK_VISIBILITY_PHP', 2);
  34. /**
  35. * Implements hook_help().
  36. */
  37. function block_help($path, $arg) {
  38. switch ($path) {
  39. case 'admin/help#block':
  40. $output = '';
  41. $output .= '<h3>' . t('About') . '</h3>';
  42. $output .= '<p>' . t('The Block module allows you to create boxes of content, which are rendered into an area, or region, of one or more pages of a website. The core Seven administration theme, for example, implements the regions "Content", "Help", "Dashboard main", and "Dashboard sidebar", and a block may appear in any one of these regions. The <a href="@blocks">Blocks administration page</a> provides a drag-and-drop interface for assigning a block to a region, and for controlling the order of blocks within regions. For more information, see the online handbook entry for <a href="@block">Block module</a>.', array('@block' => 'http://drupal.org/documentation/modules/block/', '@blocks' => url('admin/structure/block'))) . '</p>';
  43. $output .= '<h3>' . t('Uses') . '</h3>';
  44. $output .= '<dl>';
  45. $output .= '<dt>' . t('Positioning content') . '</dt>';
  46. $output .= '<dd>' . t('When working with blocks, remember that all themes do <em>not</em> implement the same regions, or display regions in the same way. Blocks are positioned on a per-theme basis. Users with the <em>Administer blocks</em> permission can disable blocks. Disabled blocks are listed on the <a href="@blocks">Blocks administration page</a>, but are not displayed in any region.', array('@block' => 'http://drupal.org/documentation/modules/block/', '@blocks' => url('admin/structure/block'))) . '</dd>';
  47. $output .= '<dt>' . t('Controlling visibility') . '</dt>';
  48. $output .= '<dd>' . t('Blocks can be configured to be visible only on certain pages, only to users of certain roles, or only on pages displaying certain <a href="@content-type">content types</a>. Administrators can also allow specific blocks to be enabled or disabled by users when they edit their <a href="@user">My account</a> page. Some dynamic blocks, such as those generated by modules, will be displayed only on certain pages.', array('@content-type' => url('admin/structure/types'), '@user' => url('user'))) . '</dd>';
  49. $output .= '<dt>' . t('Creating custom blocks') . '</dt>';
  50. $output .= '<dd>' . t('Users with the <em>Administer blocks</em> permission can <a href="@block-add">add custom blocks</a>, which are then listed on the <a href="@blocks">Blocks administration page</a>. Once created, custom blocks behave just like default and module-generated blocks.', array('@blocks' => url('admin/structure/block'), '@block-add' => url('admin/structure/block/add'))) . '</dd>';
  51. $output .= '</dl>';
  52. return $output;
  53. case 'admin/structure/block/add':
  54. return '<p>' . t('Use this page to create a new custom block.') . '</p>';
  55. }
  56. if ($arg[0] == 'admin' && $arg[1] == 'structure' && $arg['2'] == 'block' && (empty($arg[3]) || $arg[3] == 'list')) {
  57. $demo_theme = !empty($arg[4]) ? $arg[4] : variable_get('theme_default', 'bartik');
  58. $themes = list_themes();
  59. $output = '<p>' . t('This page provides a drag-and-drop interface for assigning a block to a region, and for controlling the order of blocks within regions. 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. Click the <em>configure</em> link next to each block to configure its specific title and visibility settings.') . '</p>';
  60. $output .= '<p>' . l(t('Demonstrate block regions (!theme)', array('!theme' => $themes[$demo_theme]->info['name'])), 'admin/structure/block/demo/' . $demo_theme) . '</p>';
  61. return $output;
  62. }
  63. }
  64. /**
  65. * Implements hook_theme().
  66. */
  67. function block_theme() {
  68. return array(
  69. 'block' => array(
  70. 'render element' => 'elements',
  71. 'template' => 'block',
  72. ),
  73. 'block_admin_display_form' => array(
  74. 'template' => 'block-admin-display-form',
  75. 'file' => 'block.admin.inc',
  76. 'render element' => 'form',
  77. ),
  78. );
  79. }
  80. /**
  81. * Implements hook_permission().
  82. */
  83. function block_permission() {
  84. return array(
  85. 'administer blocks' => array(
  86. 'title' => t('Administer blocks'),
  87. ),
  88. );
  89. }
  90. /**
  91. * Implements hook_menu().
  92. */
  93. function block_menu() {
  94. $default_theme = variable_get('theme_default', 'bartik');
  95. $items['admin/structure/block'] = array(
  96. 'title' => 'Blocks',
  97. 'description' => 'Configure what block content appears in your site\'s sidebars and other regions.',
  98. 'page callback' => 'block_admin_display',
  99. 'page arguments' => array($default_theme),
  100. 'access arguments' => array('administer blocks'),
  101. 'file' => 'block.admin.inc',
  102. );
  103. $items['admin/structure/block/manage/%/%'] = array(
  104. 'title' => 'Configure block',
  105. 'page callback' => 'drupal_get_form',
  106. 'page arguments' => array('block_admin_configure', 4, 5),
  107. 'access arguments' => array('administer blocks'),
  108. 'file' => 'block.admin.inc',
  109. );
  110. $items['admin/structure/block/manage/%/%/configure'] = array(
  111. 'title' => 'Configure block',
  112. 'type' => MENU_DEFAULT_LOCAL_TASK,
  113. 'context' => MENU_CONTEXT_INLINE,
  114. );
  115. $items['admin/structure/block/manage/%/%/delete'] = array(
  116. 'title' => 'Delete block',
  117. 'page callback' => 'drupal_get_form',
  118. 'page arguments' => array('block_custom_block_delete', 4, 5),
  119. 'access arguments' => array('administer blocks'),
  120. 'type' => MENU_LOCAL_TASK,
  121. 'context' => MENU_CONTEXT_NONE,
  122. 'file' => 'block.admin.inc',
  123. );
  124. $items['admin/structure/block/add'] = array(
  125. 'title' => 'Add block',
  126. 'page callback' => 'drupal_get_form',
  127. 'page arguments' => array('block_add_block_form'),
  128. 'access arguments' => array('administer blocks'),
  129. 'type' => MENU_LOCAL_ACTION,
  130. 'file' => 'block.admin.inc',
  131. );
  132. foreach (list_themes() as $key => $theme) {
  133. $items['admin/structure/block/list/' . $key] = array(
  134. 'title' => $theme->info['name'],
  135. 'page arguments' => array($key),
  136. 'type' => $key == $default_theme ? MENU_DEFAULT_LOCAL_TASK : MENU_LOCAL_TASK,
  137. 'weight' => $key == $default_theme ? -10 : 0,
  138. 'access callback' => '_block_themes_access',
  139. 'access arguments' => array($theme),
  140. 'file' => 'block.admin.inc',
  141. );
  142. if ($key != $default_theme) {
  143. $items['admin/structure/block/list/' . $key . '/add'] = array(
  144. 'title' => 'Add block',
  145. 'page callback' => 'drupal_get_form',
  146. 'page arguments' => array('block_add_block_form'),
  147. 'access arguments' => array('administer blocks'),
  148. 'type' => MENU_LOCAL_ACTION,
  149. 'file' => 'block.admin.inc',
  150. );
  151. }
  152. $items['admin/structure/block/demo/' . $key] = array(
  153. 'title' => $theme->info['name'],
  154. 'page callback' => 'block_admin_demo',
  155. 'page arguments' => array($key),
  156. 'type' => MENU_CALLBACK,
  157. 'access callback' => '_block_themes_access',
  158. 'access arguments' => array($theme),
  159. 'theme callback' => '_block_custom_theme',
  160. 'theme arguments' => array($key),
  161. 'file' => 'block.admin.inc',
  162. );
  163. }
  164. return $items;
  165. }
  166. /**
  167. * Menu item access callback - only admin or enabled themes can be accessed.
  168. */
  169. function _block_themes_access($theme) {
  170. return user_access('administer blocks') && drupal_theme_access($theme);
  171. }
  172. /**
  173. * Theme callback for the block configuration pages.
  174. *
  175. * @param $theme
  176. * The theme whose blocks are being configured. If not set, the default theme
  177. * is assumed.
  178. *
  179. * @return
  180. * The theme that should be used for the block configuration page, or NULL
  181. * to indicate that the default theme should be used.
  182. */
  183. function _block_custom_theme($theme = NULL) {
  184. // We return exactly what was passed in, to guarantee that the page will
  185. // always be displayed using the theme whose blocks are being configured.
  186. return $theme;
  187. }
  188. /**
  189. * Implements hook_block_info().
  190. */
  191. function block_block_info() {
  192. $blocks = array();
  193. $result = db_query('SELECT bid, info FROM {block_custom} ORDER BY info');
  194. foreach ($result as $block) {
  195. $blocks[$block->bid]['info'] = $block->info;
  196. // Not worth caching.
  197. $blocks[$block->bid]['cache'] = DRUPAL_NO_CACHE;
  198. }
  199. return $blocks;
  200. }
  201. /**
  202. * Implements hook_block_configure().
  203. */
  204. function block_block_configure($delta = 0) {
  205. if ($delta) {
  206. $custom_block = block_custom_block_get($delta);
  207. }
  208. else {
  209. $custom_block = array();
  210. }
  211. return block_custom_block_form($custom_block);
  212. }
  213. /**
  214. * Implements hook_block_save().
  215. */
  216. function block_block_save($delta = 0, $edit = array()) {
  217. block_custom_block_save($edit, $delta);
  218. }
  219. /**
  220. * Implements hook_block_view().
  221. *
  222. * Generates the administrator-defined blocks for display.
  223. */
  224. function block_block_view($delta = '') {
  225. $block = db_query('SELECT body, format FROM {block_custom} WHERE bid = :bid', array(':bid' => $delta))->fetchObject();
  226. $data['subject'] = NULL;
  227. $data['content'] = check_markup($block->body, $block->format, '', TRUE);
  228. return $data;
  229. }
  230. /**
  231. * Implements hook_page_build().
  232. *
  233. * Renders blocks into their regions.
  234. */
  235. function block_page_build(&$page) {
  236. global $theme;
  237. // The theme system might not yet be initialized. We need $theme.
  238. drupal_theme_initialize();
  239. // Fetch a list of regions for the current theme.
  240. $all_regions = system_region_list($theme);
  241. $item = menu_get_item();
  242. if ($item['path'] != 'admin/structure/block/demo/' . $theme) {
  243. // Load all region content assigned via blocks.
  244. foreach (array_keys($all_regions) as $region) {
  245. // Assign blocks to region.
  246. if ($blocks = block_get_blocks_by_region($region)) {
  247. $page[$region] = $blocks;
  248. }
  249. }
  250. // Once we've finished attaching all blocks to the page, clear the static
  251. // cache to allow modules to alter the block list differently in different
  252. // contexts. For example, any code that triggers hook_page_build() more
  253. // than once in the same page request may need to alter the block list
  254. // differently each time, so that only certain parts of the page are
  255. // actually built. We do not clear the cache any earlier than this, though,
  256. // because it is used each time block_get_blocks_by_region() gets called
  257. // above.
  258. drupal_static_reset('block_list');
  259. }
  260. else {
  261. // Append region description if we are rendering the regions demo page.
  262. $item = menu_get_item();
  263. if ($item['path'] == 'admin/structure/block/demo/' . $theme) {
  264. foreach (system_region_list($theme, REGIONS_VISIBLE, FALSE) as $region) {
  265. $description = '<div class="block-region">' . $all_regions[$region] . '</div>';
  266. $page[$region]['block_description'] = array(
  267. '#markup' => $description,
  268. '#weight' => 15,
  269. );
  270. }
  271. $page['page_top']['backlink'] = array(
  272. '#type' => 'link',
  273. '#title' => t('Exit block region demonstration'),
  274. '#href' => 'admin/structure/block' . (variable_get('theme_default', 'bartik') == $theme ? '' : '/list/' . $theme),
  275. // Add the "overlay-restore" class to indicate this link should restore
  276. // the context in which the region demonstration page was opened.
  277. '#options' => array('attributes' => array('class' => array('block-demo-backlink', 'overlay-restore'))),
  278. '#weight' => -10,
  279. );
  280. }
  281. }
  282. }
  283. /**
  284. * Gets a renderable array of a region containing all enabled blocks.
  285. *
  286. * @param $region
  287. * The requested region.
  288. *
  289. * @return
  290. * A renderable array of a region containing all enabled blocks.
  291. */
  292. function block_get_blocks_by_region($region) {
  293. $build = array();
  294. if ($list = block_list($region)) {
  295. $build = _block_get_renderable_array($list);
  296. }
  297. return $build;
  298. }
  299. /**
  300. * Gets an array of blocks suitable for drupal_render().
  301. *
  302. * @param $list
  303. * A list of blocks such as that returned by block_list().
  304. *
  305. * @return
  306. * A renderable array.
  307. */
  308. function _block_get_renderable_array($list = array()) {
  309. $weight = 0;
  310. $build = array();
  311. foreach ($list as $key => $block) {
  312. $build[$key] = $block->content;
  313. unset($block->content);
  314. // Add contextual links for this block; skip the main content block, since
  315. // contextual links are basically output as tabs/local tasks already. Also
  316. // skip the help block, since we assume that most users do not need or want
  317. // to perform contextual actions on the help block, and the links needlessly
  318. // draw attention on it.
  319. if ($key != 'system_main' && $key != 'system_help') {
  320. $build[$key]['#contextual_links']['block'] = array(
  321. 'admin/structure/block/manage',
  322. array($block->module, $block->delta),
  323. );
  324. }
  325. $build[$key] += array(
  326. '#block' => $block,
  327. '#weight' => ++$weight,
  328. );
  329. $build[$key]['#theme_wrappers'][] = 'block';
  330. }
  331. $build['#sorted'] = TRUE;
  332. return $build;
  333. }
  334. /**
  335. * Updates the 'block' DB table with the blocks currently exported by modules.
  336. *
  337. * @param $theme
  338. * The theme to rehash blocks for. If not provided, defaults to the currently
  339. * used theme.
  340. *
  341. * @return
  342. * Blocks currently exported by modules.
  343. */
  344. function _block_rehash($theme = NULL) {
  345. global $theme_key;
  346. drupal_theme_initialize();
  347. if (!isset($theme)) {
  348. // If theme is not specifically set, rehash for the current theme.
  349. $theme = $theme_key;
  350. }
  351. $regions = system_region_list($theme);
  352. // These are the blocks the function will return.
  353. $blocks = array();
  354. // These are the blocks defined by code and modified by the database.
  355. $current_blocks = array();
  356. // These are {block}.bid values to be kept.
  357. $bids = array();
  358. $or = db_or();
  359. // Gather the blocks defined by modules.
  360. foreach (module_implements('block_info') as $module) {
  361. $module_blocks = module_invoke($module, 'block_info');
  362. $delta_list = array();
  363. foreach ($module_blocks as $delta => $block) {
  364. // Compile a condition to retrieve this block from the database.
  365. // Add identifiers.
  366. $delta_list[] = $delta;
  367. $block['module'] = $module;
  368. $block['delta'] = $delta;
  369. $block['theme'] = $theme;
  370. $current_blocks[$module][$delta] = $block;
  371. }
  372. if (!empty($delta_list)) {
  373. $condition = db_and()->condition('module', $module)->condition('delta', $delta_list);
  374. $or->condition($condition);
  375. }
  376. }
  377. // Save the blocks defined in code for alter context.
  378. $code_blocks = $current_blocks;
  379. $database_blocks = db_select('block', 'b', array('fetch' => PDO::FETCH_ASSOC))
  380. ->fields('b')
  381. ->condition($or)
  382. ->condition('theme', $theme)
  383. ->execute();
  384. $original_database_blocks = array();
  385. foreach ($database_blocks as $block) {
  386. $module = $block['module'];
  387. $delta = $block['delta'];
  388. $original_database_blocks[$module][$delta] = $block;
  389. // The cache mode can only by set from hook_block_info(), so that has
  390. // precedence over the database's value.
  391. if (isset($current_blocks[$module][$delta]['cache'])) {
  392. $block['cache'] = $current_blocks[$module][$delta]['cache'];
  393. }
  394. // Preserve info which is not in the database.
  395. $block['info'] = $current_blocks[$module][$delta]['info'];
  396. // Blocks stored in the database override the blocks defined in code.
  397. $current_blocks[$module][$delta] = $block;
  398. // Preserve this block.
  399. $bids[$block['bid']] = $block['bid'];
  400. }
  401. drupal_alter('block_info', $current_blocks, $theme, $code_blocks);
  402. foreach ($current_blocks as $module => $module_blocks) {
  403. foreach ($module_blocks as $delta => $block) {
  404. // Make sure certain attributes are set.
  405. $block += array(
  406. 'pages' => '',
  407. 'weight' => 0,
  408. 'status' => 0,
  409. );
  410. // Check for active blocks in regions that are not available.
  411. if (!empty($block['region']) && $block['region'] != BLOCK_REGION_NONE && !isset($regions[$block['region']]) && $block['status'] == 1) {
  412. drupal_set_message(t('The block %info was assigned to the invalid region %region and has been disabled.', array('%info' => $block['info'], '%region' => $block['region'])), 'warning');
  413. // Disabled modules are moved into the BLOCK_REGION_NONE later so no
  414. // need to move the block to another region.
  415. $block['status'] = 0;
  416. }
  417. // Set region to none if not enabled.
  418. if (empty($block['status'])) {
  419. $block['status'] = 0;
  420. $block['region'] = BLOCK_REGION_NONE;
  421. }
  422. // There is no point saving disabled blocks. Still, we need to save them
  423. // because the 'title' attribute is saved to the {blocks} table.
  424. if (isset($block['bid'])) {
  425. // If the block has a bid property, it comes from the database and
  426. // the record needs to be updated, so set the primary key to 'bid'
  427. // before passing to drupal_write_record().
  428. $primary_keys = array('bid');
  429. // Remove a block from the list of blocks to keep if it became disabled.
  430. unset($bids[$block['bid']]);
  431. }
  432. else {
  433. $primary_keys = array();
  434. }
  435. // If the block is new or differs from the original database block, save
  436. // it. To determine whether there was a change it is enough to examine
  437. // the values for the keys in the original database record as that
  438. // contained every database field.
  439. if (!$primary_keys || array_diff_assoc($original_database_blocks[$module][$delta], $block)) {
  440. drupal_write_record('block', $block, $primary_keys);
  441. // Make it possible to test this.
  442. $block['saved'] = TRUE;
  443. }
  444. // Add to the list of blocks we return.
  445. $blocks[] = $block;
  446. }
  447. }
  448. if ($bids) {
  449. // Remove disabled that are no longer defined by the code from the
  450. // database.
  451. db_delete('block')
  452. ->condition('bid', $bids, 'NOT IN')
  453. ->condition('theme', $theme)
  454. ->execute();
  455. }
  456. return $blocks;
  457. }
  458. /**
  459. * Returns information from database about a user-created (custom) block.
  460. *
  461. * @param $bid
  462. * ID of the block to get information for.
  463. *
  464. * @return
  465. * Associative array of information stored in the database for this block.
  466. * Array keys:
  467. * - bid: Block ID.
  468. * - info: Block description.
  469. * - body: Block contents.
  470. * - format: Filter ID of the filter format for the body.
  471. */
  472. function block_custom_block_get($bid) {
  473. return db_query("SELECT * FROM {block_custom} WHERE bid = :bid", array(':bid' => $bid))->fetchAssoc();
  474. }
  475. /**
  476. * Form constructor for the custom block form.
  477. *
  478. * @param $edit
  479. * (optional) An associative array of information retrieved by
  480. * block_custom_get_block() if an existing block is being edited, or an empty
  481. * array otherwise. Defaults to array().
  482. *
  483. * @ingroup forms
  484. */
  485. function block_custom_block_form($edit = array()) {
  486. $edit += array(
  487. 'info' => '',
  488. 'body' => '',
  489. );
  490. $form['info'] = array(
  491. '#type' => 'textfield',
  492. '#title' => t('Block description'),
  493. '#default_value' => $edit['info'],
  494. '#maxlength' => 64,
  495. '#description' => t('A brief description of your block. Used on the <a href="@overview">Blocks administration page</a>.', array('@overview' => url('admin/structure/block'))),
  496. '#required' => TRUE,
  497. '#weight' => -18,
  498. );
  499. $form['body_field']['#weight'] = -17;
  500. $form['body_field']['body'] = array(
  501. '#type' => 'text_format',
  502. '#title' => t('Block body'),
  503. '#default_value' => $edit['body'],
  504. '#format' => isset($edit['format']) ? $edit['format'] : NULL,
  505. '#rows' => 15,
  506. '#description' => t('The content of the block as shown to the user.'),
  507. '#required' => TRUE,
  508. '#weight' => -17,
  509. );
  510. return $form;
  511. }
  512. /**
  513. * Saves a user-created block in the database.
  514. *
  515. * @param $edit
  516. * Associative array of fields to save. Array keys:
  517. * - info: Block description.
  518. * - body: Associative array of body value and format. Array keys:
  519. * - value: Block contents.
  520. * - format: Filter ID of the filter format for the body.
  521. * @param $delta
  522. * Block ID of the block to save.
  523. *
  524. * @return
  525. * Always returns TRUE.
  526. */
  527. function block_custom_block_save($edit, $delta) {
  528. db_update('block_custom')
  529. ->fields(array(
  530. 'body' => $edit['body']['value'],
  531. 'info' => $edit['info'],
  532. 'format' => $edit['body']['format'],
  533. ))
  534. ->condition('bid', $delta)
  535. ->execute();
  536. return TRUE;
  537. }
  538. /**
  539. * Implements hook_form_FORM_ID_alter() for user_profile_form().
  540. */
  541. function block_form_user_profile_form_alter(&$form, &$form_state) {
  542. if ($form['#user_category'] == 'account') {
  543. $account = $form['#user'];
  544. $rids = array_keys($account->roles);
  545. $result = db_query("SELECT DISTINCT b.* FROM {block} b LEFT JOIN {block_role} r ON b.module = r.module AND b.delta = r.delta WHERE b.status = 1 AND b.custom <> 0 AND (r.rid IN (:rids) OR r.rid IS NULL) ORDER BY b.weight, b.module", array(':rids' => $rids));
  546. $blocks = array();
  547. foreach ($result as $block) {
  548. $data = module_invoke($block->module, 'block_info');
  549. if ($data[$block->delta]['info']) {
  550. $blocks[$block->module][$block->delta] = array(
  551. '#type' => 'checkbox',
  552. '#title' => check_plain($data[$block->delta]['info']),
  553. '#default_value' => isset($account->data['block'][$block->module][$block->delta]) ? $account->data['block'][$block->module][$block->delta] : ($block->custom == 1),
  554. );
  555. }
  556. }
  557. // Only display the fieldset if there are any personalizable blocks.
  558. if ($blocks) {
  559. $form['block'] = array(
  560. '#type' => 'fieldset',
  561. '#title' => t('Personalize blocks'),
  562. '#description' => t('Blocks consist of content or information that complements the main content of the page. Enable or disable optional blocks using the checkboxes below.'),
  563. '#weight' => 3,
  564. '#collapsible' => TRUE,
  565. '#tree' => TRUE,
  566. );
  567. $form['block'] += $blocks;
  568. }
  569. }
  570. }
  571. /**
  572. * Implements hook_user_presave().
  573. */
  574. function block_user_presave(&$edit, $account, $category) {
  575. if (isset($edit['block'])) {
  576. $edit['data']['block'] = $edit['block'];
  577. }
  578. }
  579. /**
  580. * Initializes blocks for enabled themes.
  581. *
  582. * @param $theme_list
  583. * An array of theme names.
  584. */
  585. function block_themes_enabled($theme_list) {
  586. foreach ($theme_list as $theme) {
  587. block_theme_initialize($theme);
  588. }
  589. }
  590. /**
  591. * Assigns an initial, default set of blocks for a theme.
  592. *
  593. * This function is called the first time a new theme is enabled. The new theme
  594. * gets a copy of the default theme's blocks, with the difference that if a
  595. * particular region isn't available in the new theme, the block is assigned
  596. * to the new theme's default region.
  597. *
  598. * @param $theme
  599. * The name of a theme.
  600. */
  601. function block_theme_initialize($theme) {
  602. // Initialize theme's blocks if none already registered.
  603. $has_blocks = (bool) db_query_range('SELECT 1 FROM {block} WHERE theme = :theme', 0, 1, array(':theme' => $theme))->fetchField();
  604. if (!$has_blocks) {
  605. $default_theme = variable_get('theme_default', 'bartik');
  606. // Apply only to new theme's visible regions.
  607. $regions = system_region_list($theme, REGIONS_VISIBLE);
  608. $result = db_query("SELECT * FROM {block} WHERE theme = :theme", array(':theme' => $default_theme), array('fetch' => PDO::FETCH_ASSOC));
  609. foreach ($result as $block) {
  610. // If the region isn't supported by the theme, assign the block to the
  611. // theme's default region.
  612. if ($block['status'] && !isset($regions[$block['region']])) {
  613. $block['region'] = system_default_region($theme);
  614. }
  615. $block['theme'] = $theme;
  616. unset($block['bid']);
  617. drupal_write_record('block', $block);
  618. }
  619. }
  620. }
  621. /**
  622. * Returns all blocks in the specified region for the current user.
  623. *
  624. * @param $region
  625. * The name of a region.
  626. *
  627. * @return
  628. * An array of block objects, indexed with the module name and block delta
  629. * concatenated with an underscore, thus: MODULE_DELTA. If you are displaying
  630. * your blocks in one or two sidebars, you may check whether this array is
  631. * empty to see how many columns are going to be displayed.
  632. *
  633. * @todo
  634. * Now that the block table has a primary key, we should use that as the
  635. * array key instead of MODULE_DELTA.
  636. */
  637. function block_list($region) {
  638. $blocks = &drupal_static(__FUNCTION__);
  639. if (!isset($blocks)) {
  640. $blocks = _block_load_blocks();
  641. }
  642. // Create an empty array if there are no entries.
  643. if (!isset($blocks[$region])) {
  644. $blocks[$region] = array();
  645. }
  646. else {
  647. $blocks[$region] = _block_render_blocks($blocks[$region]);
  648. }
  649. return $blocks[$region];
  650. }
  651. /**
  652. * Loads a block object from the database.
  653. *
  654. * This function returns the first block matching the module and delta
  655. * parameters, so it should not be used for theme-specific functionality.
  656. *
  657. * @param $module
  658. * Name of the module that implements the block to load.
  659. * @param $delta
  660. * Unique ID of the block within the context of $module. Pass NULL to return
  661. * an empty block object for $module.
  662. *
  663. * @return
  664. * A block object.
  665. */
  666. function block_load($module, $delta) {
  667. if (isset($delta)) {
  668. $block = db_query('SELECT * FROM {block} WHERE module = :module AND delta = :delta', array(':module' => $module, ':delta' => $delta))->fetchObject();
  669. }
  670. // If the block does not exist in the database yet return a stub block
  671. // object.
  672. if (empty($block)) {
  673. $block = new stdClass();
  674. $block->module = $module;
  675. $block->delta = $delta;
  676. }
  677. return $block;
  678. }
  679. /**
  680. * Loads blocks' information from the database.
  681. *
  682. * @return
  683. * An array of blocks grouped by region.
  684. */
  685. function _block_load_blocks() {
  686. global $theme_key;
  687. $query = db_select('block', 'b');
  688. $result = $query
  689. ->fields('b')
  690. ->condition('b.theme', $theme_key)
  691. ->condition('b.status', 1)
  692. ->orderBy('b.region')
  693. ->orderBy('b.weight')
  694. ->orderBy('b.module')
  695. ->addTag('block_load')
  696. ->addTag('translatable')
  697. ->execute();
  698. $block_info = $result->fetchAllAssoc('bid');
  699. // Allow modules to modify the block list.
  700. drupal_alter('block_list', $block_info);
  701. $blocks = array();
  702. foreach ($block_info as $block) {
  703. $blocks[$block->region]["{$block->module}_{$block->delta}"] = $block;
  704. }
  705. return $blocks;
  706. }
  707. /**
  708. * Implements hook_block_list_alter().
  709. *
  710. * Checks the page, user role, and user-specific visibility settings.
  711. * Removes the block if the visibility conditions are not met.
  712. */
  713. function block_block_list_alter(&$blocks) {
  714. global $user, $theme_key;
  715. // Build an array of roles for each block.
  716. $block_roles = array();
  717. $result = db_query('SELECT module, delta, rid FROM {block_role}');
  718. foreach ($result as $record) {
  719. $block_roles[$record->module][$record->delta][] = $record->rid;
  720. }
  721. foreach ($blocks as $key => $block) {
  722. if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
  723. // This block was added by a contrib module, leave it in the list.
  724. continue;
  725. }
  726. // If a block has no roles associated, it is displayed for every role.
  727. // For blocks with roles associated, if none of the user's roles matches
  728. // the settings from this block, remove it from the block list.
  729. if (isset($block_roles[$block->module][$block->delta]) && !array_intersect($block_roles[$block->module][$block->delta], array_keys($user->roles))) {
  730. // No match.
  731. unset($blocks[$key]);
  732. continue;
  733. }
  734. // Use the user's block visibility setting, if necessary.
  735. if ($block->custom != BLOCK_CUSTOM_FIXED) {
  736. if ($user->uid && isset($user->data['block'][$block->module][$block->delta])) {
  737. $enabled = $user->data['block'][$block->module][$block->delta];
  738. }
  739. else {
  740. $enabled = ($block->custom == BLOCK_CUSTOM_ENABLED);
  741. }
  742. }
  743. else {
  744. $enabled = TRUE;
  745. }
  746. // Limited visibility blocks must list at least one page.
  747. if ($block->visibility == BLOCK_VISIBILITY_LISTED && empty($block->pages)) {
  748. $enabled = FALSE;
  749. }
  750. if (!$enabled) {
  751. unset($blocks[$key]);
  752. continue;
  753. }
  754. // Match path if necessary.
  755. if ($block->pages) {
  756. // Convert path to lowercase. This allows comparison of the same path
  757. // with different case. Ex: /Page, /page, /PAGE.
  758. $pages = drupal_strtolower($block->pages);
  759. if ($block->visibility < BLOCK_VISIBILITY_PHP) {
  760. // Convert the Drupal path to lowercase.
  761. $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
  762. // Compare the lowercase internal and lowercase path alias (if any).
  763. $page_match = drupal_match_path($path, $pages);
  764. if ($path != $_GET['q']) {
  765. $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
  766. }
  767. // When $block->visibility has a value of 0
  768. // (BLOCK_VISIBILITY_NOTLISTED), the block is displayed on all pages
  769. // except those listed in $block->pages. When set to 1
  770. // (BLOCK_VISIBILITY_LISTED), it is displayed only on those pages
  771. // listed in $block->pages.
  772. $page_match = !($block->visibility xor $page_match);
  773. }
  774. elseif (module_exists('php')) {
  775. $page_match = php_eval($block->pages);
  776. }
  777. else {
  778. $page_match = FALSE;
  779. }
  780. }
  781. else {
  782. $page_match = TRUE;
  783. }
  784. if (!$page_match) {
  785. unset($blocks[$key]);
  786. }
  787. }
  788. }
  789. /**
  790. * Render the content and subject for a set of blocks.
  791. *
  792. * @param $region_blocks
  793. * An array of block objects such as returned for one region by
  794. * _block_load_blocks().
  795. *
  796. * @return
  797. * An array of visible blocks as expected by drupal_render().
  798. */
  799. function _block_render_blocks($region_blocks) {
  800. $cacheable = TRUE;
  801. // We preserve the submission of forms in blocks, by fetching from cache only
  802. // if the request method is 'GET' (or 'HEAD').
  803. if ($_SERVER['REQUEST_METHOD'] != 'GET' && $_SERVER['REQUEST_METHOD'] != 'HEAD') {
  804. $cacheable = FALSE;
  805. }
  806. // Block caching is not usually compatible with node access modules, so by
  807. // default it is disabled when node access modules exist. However, it can be
  808. // allowed by using the variable 'block_cache_bypass_node_grants'.
  809. elseif (!variable_get('block_cache_bypass_node_grants', FALSE) && count(module_implements('node_grants'))) {
  810. $cacheable = FALSE;
  811. }
  812. // Proceed to loop over all blocks in order to compute their respective cache
  813. // identifiers; this allows us to do one single cache_get_multiple() call
  814. // instead of doing one cache_get() call per block.
  815. $cached_blocks = array();
  816. $cids = array();
  817. if ($cacheable) {
  818. foreach ($region_blocks as $key => $block) {
  819. if (!isset($block->content)) {
  820. if (($cid = _block_get_cache_id($block))) {
  821. $cids[$key] = $cid;
  822. }
  823. }
  824. }
  825. if ($cids) {
  826. // We cannot pass $cids in directly because cache_get_multiple() will
  827. // modify it, and we need to use it later on in this function.
  828. $cid_values = array_values($cids);
  829. $cached_blocks = cache_get_multiple($cid_values, 'cache_block');
  830. }
  831. }
  832. foreach ($region_blocks as $key => $block) {
  833. // Render the block content if it has not been created already.
  834. if (!isset($block->content)) {
  835. // Erase the block from the static array - we'll put it back if it has
  836. // content.
  837. unset($region_blocks[$key]);
  838. $cid = empty($cids[$key]) ? NULL : $cids[$key];
  839. // Try fetching the block from the previously loaded cache entries.
  840. if (isset($cached_blocks[$cid])) {
  841. $array = $cached_blocks[$cid]->data;
  842. }
  843. else {
  844. $array = module_invoke($block->module, 'block_view', $block->delta);
  845. // Valid PHP function names cannot contain hyphens.
  846. $delta = str_replace('-', '_', $block->delta);
  847. // Allow modules to modify the block before it is viewed, via either
  848. // hook_block_view_alter() or hook_block_view_MODULE_DELTA_alter().
  849. drupal_alter(array('block_view', "block_view_{$block->module}_{$delta}"), $array, $block);
  850. if (isset($cid)) {
  851. cache_set($cid, $array, 'cache_block', CACHE_TEMPORARY);
  852. }
  853. }
  854. if (isset($array) && is_array($array)) {
  855. foreach ($array as $k => $v) {
  856. $block->$k = $v;
  857. }
  858. }
  859. if (isset($block->content) && $block->content) {
  860. // Normalize to the drupal_render() structure.
  861. if (is_string($block->content)) {
  862. $block->content = array('#markup' => $block->content);
  863. }
  864. // Override default block title if a custom display title is present.
  865. if ($block->title) {
  866. // Check plain here to allow module generated titles to keep any
  867. // markup.
  868. $block->subject = $block->title == '<none>' ? '' : check_plain($block->title);
  869. }
  870. if (!isset($block->subject)) {
  871. $block->subject = '';
  872. }
  873. $region_blocks["{$block->module}_{$block->delta}"] = $block;
  874. }
  875. }
  876. }
  877. return $region_blocks;
  878. }
  879. /**
  880. * Assemble the cache_id to use for a given block.
  881. *
  882. * The cache_id string reflects the viewing context for the current block
  883. * instance, obtained by concatenating the relevant context information
  884. * (user, page, ...) according to the block's cache settings (BLOCK_CACHE_*
  885. * constants). Two block instances can use the same cached content when
  886. * they share the same cache_id.
  887. *
  888. * Theme and language contexts are automatically differentiated.
  889. *
  890. * @param $block
  891. * The block to get the cache_id from.
  892. *
  893. * @return
  894. * The string used as cache_id for the block.
  895. */
  896. function _block_get_cache_id($block) {
  897. global $user;
  898. // User 1 being out of the regular 'roles define permissions' schema,
  899. // it brings too many chances of having unwanted output get in the cache
  900. // and later be served to other users. We therefore exclude user 1 from
  901. // block caching.
  902. if (variable_get('block_cache', FALSE) && !in_array($block->cache, array(DRUPAL_NO_CACHE, DRUPAL_CACHE_CUSTOM)) && $user->uid != 1) {
  903. // Start with common sub-patterns: block identification, theme, language.
  904. $cid_parts[] = $block->module;
  905. $cid_parts[] = $block->delta;
  906. drupal_alter('block_cid_parts', $cid_parts, $block);
  907. $cid_parts = array_merge($cid_parts, drupal_render_cid_parts($block->cache));
  908. return implode(':', $cid_parts);
  909. }
  910. }
  911. /**
  912. * Implements hook_flush_caches().
  913. */
  914. function block_flush_caches() {
  915. // Rehash blocks for active themes. We don't use list_themes() here,
  916. // because if MAINTENANCE_MODE is defined it skips reading the database,
  917. // and we can't tell which themes are active.
  918. $themes = db_query("SELECT name FROM {system} WHERE type = 'theme' AND status = 1");
  919. foreach ($themes as $theme) {
  920. _block_rehash($theme->name);
  921. }
  922. return array('cache_block');
  923. }
  924. /**
  925. * Processes variables for block.tpl.php.
  926. *
  927. * Prepares the values passed to the theme_block function to be passed
  928. * into a pluggable template engine. Uses block properties to generate a
  929. * series of template file suggestions. If none are found, the default
  930. * block.tpl.php is used.
  931. *
  932. * Most themes utilize their own copy of block.tpl.php. The default is located
  933. * inside "modules/block/block.tpl.php". Look in there for the full list of
  934. * variables.
  935. *
  936. * The $variables array contains the following arguments:
  937. * - $block
  938. *
  939. * @see block.tpl.php
  940. */
  941. function template_preprocess_block(&$variables) {
  942. $block_counter = &drupal_static(__FUNCTION__, array());
  943. $variables['block'] = $variables['elements']['#block'];
  944. // All blocks get an independent counter for each region.
  945. if (!isset($block_counter[$variables['block']->region])) {
  946. $block_counter[$variables['block']->region] = 1;
  947. }
  948. // Same with zebra striping.
  949. $variables['block_zebra'] = ($block_counter[$variables['block']->region] % 2) ? 'odd' : 'even';
  950. $variables['block_id'] = $block_counter[$variables['block']->region]++;
  951. // Create the $content variable that templates expect.
  952. $variables['content'] = $variables['elements']['#children'];
  953. $variables['classes_array'][] = drupal_html_class('block-' . $variables['block']->module);
  954. $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->region;
  955. $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->module;
  956. // Hyphens (-) and underscores (_) play a special role in theme suggestions.
  957. // Theme suggestions should only contain underscores, because within
  958. // drupal_find_theme_templates(), underscores are converted to hyphens to
  959. // match template file names, and then converted back to underscores to match
  960. // pre-processing and other function names. So if your theme suggestion
  961. // contains a hyphen, it will end up as an underscore after this conversion,
  962. // and your function names won't be recognized. So, we need to convert
  963. // hyphens to underscores in block deltas for the theme suggestions.
  964. $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->module . '__' . strtr($variables['block']->delta, '-', '_');
  965. // Create a valid HTML ID and make sure it is unique.
  966. $variables['block_html_id'] = drupal_html_id('block-' . $variables['block']->module . '-' . $variables['block']->delta);
  967. }
  968. /**
  969. * Implements hook_user_role_delete().
  970. *
  971. * Removes deleted role from blocks that use it.
  972. */
  973. function block_user_role_delete($role) {
  974. db_delete('block_role')
  975. ->condition('rid', $role->rid)
  976. ->execute();
  977. }
  978. /**
  979. * Implements hook_menu_delete().
  980. */
  981. function block_menu_delete($menu) {
  982. db_delete('block')
  983. ->condition('module', 'menu')
  984. ->condition('delta', $menu['menu_name'])
  985. ->execute();
  986. db_delete('block_role')
  987. ->condition('module', 'menu')
  988. ->condition('delta', $menu['menu_name'])
  989. ->execute();
  990. }
  991. /**
  992. * Implements hook_form_FORM_ID_alter().
  993. */
  994. function block_form_system_performance_settings_alter(&$form, &$form_state) {
  995. $disabled = (!variable_get('block_cache_bypass_node_grants', FALSE) && count(module_implements('node_grants')));
  996. $form['caching']['block_cache'] = array(
  997. '#type' => 'checkbox',
  998. '#title' => t('Cache blocks'),
  999. '#default_value' => variable_get('block_cache', FALSE),
  1000. '#disabled' => $disabled,
  1001. '#description' => $disabled ? t('Block caching is inactive because you have enabled modules defining content access restrictions.') : NULL,
  1002. '#weight' => -1,
  1003. );
  1004. }
  1005. /**
  1006. * Implements hook_admin_paths().
  1007. */
  1008. function block_admin_paths() {
  1009. $paths = array(
  1010. // Exclude the block demonstration page from admin (overlay) treatment.
  1011. // This allows us to present this page in its true form, full page.
  1012. 'admin/structure/block/demo/*' => FALSE,
  1013. );
  1014. return $paths;
  1015. }
  1016. /**
  1017. * Implements hook_modules_uninstalled().
  1018. *
  1019. * Cleans up {block} and {block_role} tables from modules' blocks.
  1020. */
  1021. function block_modules_uninstalled($modules) {
  1022. db_delete('block')
  1023. ->condition('module', $modules, 'IN')
  1024. ->execute();
  1025. db_delete('block_role')
  1026. ->condition('module', $modules, 'IN')
  1027. ->execute();
  1028. }

Functions

Namesort descending Description
block_admin_paths Implements hook_admin_paths().
block_block_configure Implements hook_block_configure().
block_block_info Implements hook_block_info().
block_block_list_alter Implements hook_block_list_alter().
block_block_save Implements hook_block_save().
block_block_view Implements hook_block_view().
block_custom_block_form Form constructor for the custom block form.
block_custom_block_get Returns information from database about a user-created (custom) block.
block_custom_block_save Saves a user-created block in the database.
block_flush_caches Implements hook_flush_caches().
block_form_system_performance_settings_alter Implements hook_form_FORM_ID_alter().
block_form_user_profile_form_alter Implements hook_form_FORM_ID_alter() for user_profile_form().
block_get_blocks_by_region Gets a renderable array of a region containing all enabled blocks.
block_help Implements hook_help().
block_list Returns all blocks in the specified region for the current user.
block_load Loads a block object from the database.
block_menu Implements hook_menu().
block_menu_delete Implements hook_menu_delete().
block_modules_uninstalled Implements hook_modules_uninstalled().
block_page_build Implements hook_page_build().
block_permission Implements hook_permission().
block_theme Implements hook_theme().
block_themes_enabled Initializes blocks for enabled themes.
block_theme_initialize Assigns an initial, default set of blocks for a theme.
block_user_presave Implements hook_user_presave().
block_user_role_delete Implements hook_user_role_delete().
template_preprocess_block Processes variables for block.tpl.php.
_block_custom_theme Theme callback for the block configuration pages.
_block_get_cache_id Assemble the cache_id to use for a given block.
_block_get_renderable_array Gets an array of blocks suitable for drupal_render().
_block_load_blocks Loads blocks' information from the database.
_block_rehash Updates the 'block' DB table with the blocks currently exported by modules.
_block_render_blocks Render the content and subject for a set of blocks.
_block_themes_access Menu item access callback - only admin or enabled themes can be accessed.

Constants

Namesort descending Description
BLOCK_CUSTOM_DISABLED Hides this block by default but lets individual users show it.
BLOCK_CUSTOM_ENABLED Shows this block by default, but lets individual users hide it.
BLOCK_CUSTOM_FIXED Users cannot control whether or not they see this block.
BLOCK_REGION_NONE Denotes that a block is not enabled in any region and should not be shown.
BLOCK_VISIBILITY_LISTED Shows this block on only the listed pages.
BLOCK_VISIBILITY_NOTLISTED Shows this block on every page except the listed pages.
BLOCK_VISIBILITY_PHP Shows this block if the associated PHP code returns TRUE.