Skip navigation
Help

block.module

  1. drupal
    1. 6 drupal/modules/block/block.module
    2. 7 drupal/modules/block/block.module

Controls the visual building blocks a page is constructed with.

Functions & methods

NameDescription
block_admin_pathsImplements hook_admin_paths().
block_block_configureImplements hook_block_configure().
block_block_infoImplements hook_block_info().
block_block_list_alterImplements hook_block_list_alter().
block_block_saveImplements hook_block_save().
block_block_viewImplements hook_block_view().
block_custom_block_formDefine the custom block form.
block_custom_block_getReturns information from database about a user-created (custom) block.
block_custom_block_saveSaves a user-created block in the database.
block_flush_cachesImplements hook_flush_caches().
block_form_system_performance_settings_alterImplements hook_form_FORM_ID_alter().
block_form_user_profile_form_alterImplements hook_form_FORM_ID_alter().
block_get_blocks_by_regionGet a renderable array of a region containing all enabled blocks.
block_helpImplements hook_help().
block_listReturn all blocks in the specified region for the current user.
block_loadLoad a block object from the database.
block_menuImplements hook_menu().
block_menu_deleteImplements hook_menu_delete().
block_modules_uninstalledImplements hook_modules_uninstalled().
block_page_buildImplements hook_page_build().
block_permissionImplements hook_permission().
block_themeImplements hook_theme().
block_themes_enabledInitialize blocks for enabled themes.
block_theme_initializeAssign an initial, default set of blocks for a theme.
block_user_presaveImplements hook_user_presave().
block_user_role_deleteImplements hook_user_role_delete().
template_preprocess_blockProcess variables for block.tpl.php
_block_custom_themeTheme callback for the block configuration pages.
_block_get_cache_idAssemble the cache_id to use for a given block.
_block_get_renderable_arrayGet an array of blocks suitable for drupal_render().
_block_load_blocksLoad blocks information from the database.
_block_rehashUpdate the 'block' DB table with the blocks currently exported by modules.
_block_render_blocksRender the content and subject for a set of blocks.
_block_themes_accessMenu item access callback - only admin or enabled themes can be accessed.

Constants

NameDescription
BLOCK_CUSTOM_DISABLEDHide this block by default but let individual users show it.
BLOCK_CUSTOM_ENABLEDShow this block by default, but let individual users hide it.
BLOCK_CUSTOM_FIXEDUsers cannot control whether or not they see this block.
BLOCK_REGION_NONEDenotes that a block is not enabled in any region and should not be shown.
BLOCK_VISIBILITY_LISTEDShow this block on only the listed pages.
BLOCK_VISIBILITY_NOTLISTEDShow this block on every page except the listed pages.
BLOCK_VISIBILITY_PHPShow this block if the associated PHP code returns TRUE.

File

drupal/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. * Show this block by default, but let individual users hide it.
  16. */
  17. define('BLOCK_CUSTOM_ENABLED', 1);
  18. /**
  19. * Hide this block by default but let individual users show it.
  20. */
  21. define('BLOCK_CUSTOM_DISABLED', 2);
  22. /**
  23. * Show this block on every page except the listed pages.
  24. */
  25. define('BLOCK_VISIBILITY_NOTLISTED', 0);
  26. /**
  27. * Show this block on only the listed pages.
  28. */
  29. define('BLOCK_VISIBILITY_LISTED', 1);
  30. /**
  31. * Show 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/handbook/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/handbook/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' => check_plain($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' => check_plain($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. * @return
  179. * The theme that should be used for the block configuration page, or NULL
  180. * to indicate that the default theme should be used.
  181. */
  182. function _block_custom_theme($theme = NULL) {
  183. // We return exactly what was passed in, to guarantee that the page will
  184. // always be displayed using the theme whose blocks are being configured.
  185. return $theme;
  186. }
  187. /**
  188. * Implements hook_block_info().
  189. */
  190. function block_block_info() {
  191. $blocks = array();
  192. $result = db_query('SELECT bid, info FROM {block_custom} ORDER BY info');
  193. foreach ($result as $block) {
  194. $blocks[$block->bid]['info'] = $block->info;
  195. // Not worth caching.
  196. $blocks[$block->bid]['cache'] = DRUPAL_NO_CACHE;
  197. }
  198. return $blocks;
  199. }
  200. /**
  201. * Implements hook_block_configure().
  202. */
  203. function block_block_configure($delta = 0) {
  204. if ($delta) {
  205. $custom_block = block_custom_block_get($delta);
  206. }
  207. else {
  208. $custom_block = array();
  209. }
  210. return block_custom_block_form($custom_block);
  211. }
  212. /**
  213. * Implements hook_block_save().
  214. */
  215. function block_block_save($delta = 0, $edit = array()) {
  216. block_custom_block_save($edit, $delta);
  217. }
  218. /**
  219. * Implements hook_block_view().
  220. *
  221. * Generates the administrator-defined blocks for display.
  222. */
  223. function block_block_view($delta = '') {
  224. $block = db_query('SELECT body, format FROM {block_custom} WHERE bid = :bid', array(':bid' => $delta))->fetchObject();
  225. $data['subject'] = NULL;
  226. $data['content'] = check_markup($block->body, $block->format, '', TRUE);
  227. return $data;
  228. }
  229. /**
  230. * Implements hook_page_build().
  231. *
  232. * Render blocks into their regions.
  233. */
  234. function block_page_build(&$page) {
  235. global $theme;
  236. // The theme system might not yet be initialized. We need $theme.
  237. drupal_theme_initialize();
  238. // Fetch a list of regions for the current theme.
  239. $all_regions = system_region_list($theme);
  240. $item = menu_get_item();
  241. if ($item['path'] != 'admin/structure/block/demo/' . $theme) {
  242. // Load all region content assigned via blocks.
  243. foreach (array_keys($all_regions) as $region) {
  244. // Assign blocks to region.
  245. if ($blocks = block_get_blocks_by_region($region)) {
  246. $page[$region] = $blocks;
  247. }
  248. }
  249. // Once we've finished attaching all blocks to the page, clear the static
  250. // cache to allow modules to alter the block list differently in different
  251. // contexts. For example, any code that triggers hook_page_build() more
  252. // than once in the same page request may need to alter the block list
  253. // differently each time, so that only certain parts of the page are
  254. // actually built. We do not clear the cache any earlier than this, though,
  255. // because it is used each time block_get_blocks_by_region() gets called
  256. // above.
  257. drupal_static_reset('block_list');
  258. }
  259. else {
  260. // Append region description if we are rendering the regions demo page.
  261. $item = menu_get_item();
  262. if ($item['path'] == 'admin/structure/block/demo/' . $theme) {
  263. $visible_regions = array_keys(system_region_list($theme, REGIONS_VISIBLE));
  264. foreach ($visible_regions 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. * Get a renderable array of a region containing all enabled blocks.
  285. *
  286. * @param $region
  287. * The requested region.
  288. */
  289. function block_get_blocks_by_region($region) {
  290. $build = array();
  291. if ($list = block_list($region)) {
  292. $build = _block_get_renderable_array($list);
  293. }
  294. return $build;
  295. }
  296. /**
  297. * Get an array of blocks suitable for drupal_render().
  298. *
  299. * @param $list
  300. * A list of blocks such as that returned by block_list().
  301. * @return
  302. * A renderable array.
  303. */
  304. function _block_get_renderable_array($list = array()) {
  305. $weight = 0;
  306. $build = array();
  307. foreach ($list as $key => $block) {
  308. $build[$key] = $block->content;
  309. unset($block->content);
  310. // Add contextual links for this block; skip the main content block, since
  311. // contextual links are basically output as tabs/local tasks already. Also
  312. // skip the help block, since we assume that most users do not need or want
  313. // to perform contextual actions on the help block, and the links needlessly
  314. // draw attention on it.
  315. if ($key != 'system_main' && $key != 'system_help') {
  316. $build[$key]['#contextual_links']['block'] = array('admin/structure/block/manage', array($block->module, $block->delta));
  317. }
  318. $build[$key] += array(
  319. '#block' => $block,
  320. '#weight' => ++$weight,
  321. );
  322. $build[$key]['#theme_wrappers'][] ='block';
  323. }
  324. $build['#sorted'] = TRUE;
  325. return $build;
  326. }
  327. /**
  328. * Update the 'block' DB table with the blocks currently exported by modules.
  329. *
  330. * @param $theme
  331. * The theme to rehash blocks for. If not provided, defaults to the currently
  332. * used theme.
  333. *
  334. * @return
  335. * Blocks currently exported by modules.
  336. */
  337. function _block_rehash($theme = NULL) {
  338. global $theme_key;
  339. drupal_theme_initialize();
  340. if (!isset($theme)) {
  341. // If theme is not specifically set, rehash for the current theme.
  342. $theme = $theme_key;
  343. }
  344. $regions = system_region_list($theme);
  345. // These are the blocks the function will return.
  346. $blocks = array();
  347. // These are the blocks defined by code and modified by the database.
  348. $current_blocks = array();
  349. // These are {block}.bid values to be kept.
  350. $bids = array();
  351. $or = db_or();
  352. // Gather the blocks defined by modules.
  353. foreach (module_implements('block_info') as $module) {
  354. $module_blocks = module_invoke($module, 'block_info');
  355. foreach ($module_blocks as $delta => $block) {
  356. // Compile a condition to retrieve this block from the database.
  357. $condition = db_and()
  358. ->condition('module', $module)
  359. ->condition('delta', $delta);
  360. $or->condition($condition);
  361. // Add identifiers.
  362. $block['module'] = $module;
  363. $block['delta'] = $delta;
  364. $block['theme'] = $theme;
  365. $current_blocks[$module][$delta] = $block;
  366. }
  367. }
  368. // Save the blocks defined in code for alter context.
  369. $code_blocks = $current_blocks;
  370. $database_blocks = db_select('block', 'b')
  371. ->fields('b')
  372. ->condition($or)
  373. ->condition('theme', $theme)
  374. ->execute();
  375. foreach ($database_blocks as $block) {
  376. // Preserve info which is not in the database.
  377. $block->info = $current_blocks[$block->module][$block->delta]['info'];
  378. // The cache mode can only by set from hook_block_info(), so that has
  379. // precedence over the database's value.
  380. if (isset($current_blocks[$block->module][$block->delta]['cache'])) {
  381. $block->cache = $current_blocks[$block->module][$block->delta]['cache'];
  382. }
  383. // Blocks stored in the database override the blocks defined in code.
  384. $current_blocks[$block->module][$block->delta] = get_object_vars($block);
  385. // Preserve this block.
  386. $bids[$block->bid] = $block->bid;
  387. }
  388. drupal_alter('block_info', $current_blocks, $theme, $code_blocks);
  389. foreach ($current_blocks as $module => $module_blocks) {
  390. foreach ($module_blocks as $delta => $block) {
  391. if (!isset($block['pages'])) {
  392. // {block}.pages is type 'text', so it cannot have a
  393. // default value, and not null, so we need to provide
  394. // value if the module did not.
  395. $block['pages'] = '';
  396. }
  397. // Make sure weight is set.
  398. if (!isset($block['weight'])) {
  399. $block['weight'] = 0;
  400. }
  401. if (!empty($block['region']) && $block['region'] != BLOCK_REGION_NONE && !isset($regions[$block['region']])) {
  402. 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');
  403. // Disabled modules are moved into the BLOCK_REGION_NONE later so no
  404. // need to move the bock to another region.
  405. $block['status'] = 0;
  406. }
  407. // Set region to none if not enabled and make sure status is set.
  408. if (empty($block['status'])) {
  409. $block['status'] = 0;
  410. $block['region'] = BLOCK_REGION_NONE;
  411. }
  412. // There is no point saving disabled blocks. Still, we need to save them
  413. // because the 'title' attribute is saved to the {blocks} table.
  414. if (isset($block['bid'])) {
  415. // If the block has a bid property, it comes from the database and
  416. // the record needs to be updated, so set the primary key to 'bid'
  417. // before passing to drupal_write_record().
  418. $primary_keys = array('bid');
  419. // Remove a block from the list of blocks to keep if it became disabled.
  420. unset($bids[$block['bid']]);
  421. }
  422. else {
  423. $primary_keys = array();
  424. }
  425. drupal_write_record('block', $block, $primary_keys);
  426. // Add to the list of blocks we return.
  427. $blocks[] = $block;
  428. }
  429. }
  430. if ($bids) {
  431. // Remove disabled that are no longer defined by the code from the
  432. // database.
  433. db_delete('block')
  434. ->condition('bid', $bids, 'NOT IN')
  435. ->condition('theme', $theme)
  436. ->execute();
  437. }
  438. return $blocks;
  439. }
  440. /**
  441. * Returns information from database about a user-created (custom) block.
  442. *
  443. * @param $bid
  444. * ID of the block to get information for.
  445. * @return
  446. * Associative array of information stored in the database for this block.
  447. * Array keys:
  448. * - bid: Block ID.
  449. * - info: Block description.
  450. * - body: Block contents.
  451. * - format: Filter ID of the filter format for the body.
  452. */
  453. function block_custom_block_get($bid) {
  454. return db_query("SELECT * FROM {block_custom} WHERE bid = :bid", array(':bid' => $bid))->fetchAssoc();
  455. }
  456. /**
  457. * Define the custom block form.
  458. */
  459. function block_custom_block_form($edit = array()) {
  460. $edit += array(
  461. 'info' => '',
  462. 'body' => '',
  463. );
  464. $form['info'] = array(
  465. '#type' => 'textfield',
  466. '#title' => t('Block description'),
  467. '#default_value' => $edit['info'],
  468. '#maxlength' => 64,
  469. '#description' => t('A brief description of your block. Used on the <a href="@overview">Blocks administration page</a>.', array('@overview' => url('admin/structure/block'))),
  470. '#required' => TRUE,
  471. '#weight' => -19,
  472. );
  473. $form['body_field']['#weight'] = -17;
  474. $form['body_field']['body'] = array(
  475. '#type' => 'text_format',
  476. '#title' => t('Block body'),
  477. '#default_value' => $edit['body'],
  478. '#format' => isset($edit['format']) ? $edit['format'] : NULL,
  479. '#rows' => 15,
  480. '#description' => t('The content of the block as shown to the user.'),
  481. '#required' => TRUE,
  482. '#weight' => -17,
  483. );
  484. return $form;
  485. }
  486. /**
  487. * Saves a user-created block in the database.
  488. *
  489. * @param $edit
  490. * Associative array of fields to save. Array keys:
  491. * - info: Block description.
  492. * - body: Associative array of body value and format. Array keys:
  493. * - value: Block contents.
  494. * - format: Filter ID of the filter format for the body.
  495. * @param $delta
  496. * Block ID of the block to save.
  497. * @return
  498. * Always returns TRUE.
  499. */
  500. function block_custom_block_save($edit, $delta) {
  501. db_update('block_custom')
  502. ->fields(array(
  503. 'body' => $edit['body']['value'],
  504. 'info' => $edit['info'],
  505. 'format' => $edit['body']['format'],
  506. ))
  507. ->condition('bid', $delta)
  508. ->execute();
  509. return TRUE;
  510. }
  511. /**
  512. * Implements hook_form_FORM_ID_alter().
  513. */
  514. function block_form_user_profile_form_alter(&$form, &$form_state) {
  515. if ($form['#user_category'] == 'account') {
  516. $account = $form['#user'];
  517. $rids = array_keys($account->roles);
  518. $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));
  519. $blocks = array();
  520. foreach ($result as $block) {
  521. $data = module_invoke($block->module, 'block_info');
  522. if ($data[$block->delta]['info']) {
  523. $blocks[$block->module][$block->delta] = array(
  524. '#type' => 'checkbox',
  525. '#title' => check_plain($data[$block->delta]['info']),
  526. '#default_value' => isset($account->data['block'][$block->module][$block->delta]) ? $account->data['block'][$block->module][$block->delta] : ($block->custom == 1),
  527. );
  528. }
  529. }
  530. // Only display the fieldset if there are any personalizable blocks.
  531. if ($blocks) {
  532. $form['block'] = array(
  533. '#type' => 'fieldset',
  534. '#title' => t('Personalize blocks'),
  535. '#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.'),
  536. '#weight' => 3,
  537. '#collapsible' => TRUE,
  538. '#tree' => TRUE,
  539. );
  540. $form['block'] += $blocks;
  541. }
  542. }
  543. }
  544. /**
  545. * Implements hook_user_presave().
  546. */
  547. function block_user_presave(&$edit, $account, $category) {
  548. if (isset($edit['block'])) {
  549. $edit['data']['block'] = $edit['block'];
  550. }
  551. }
  552. /**
  553. * Initialize blocks for enabled themes.
  554. */
  555. function block_themes_enabled($theme_list) {
  556. foreach ($theme_list as $theme) {
  557. block_theme_initialize($theme);
  558. }
  559. }
  560. /**
  561. * Assign an initial, default set of blocks for a theme.
  562. *
  563. * This function is called the first time a new theme is enabled. The new theme
  564. * gets a copy of the default theme's blocks, with the difference that if a
  565. * particular region isn't available in the new theme, the block is assigned
  566. * to the new theme's default region.
  567. *
  568. * @param $theme
  569. * The name of a theme.
  570. */
  571. function block_theme_initialize($theme) {
  572. // Initialize theme's blocks if none already registered.
  573. $has_blocks = (bool) db_query_range('SELECT 1 FROM {block} WHERE theme = :theme', 0, 1, array(':theme' => $theme))->fetchField();
  574. if (!$has_blocks) {
  575. $default_theme = variable_get('theme_default', 'bartik');
  576. // Apply only to new theme's visible regions.
  577. $regions = system_region_list($theme, REGIONS_VISIBLE);
  578. $result = db_query("SELECT * FROM {block} WHERE theme = :theme", array(':theme' => $default_theme), array('fetch' => PDO::FETCH_ASSOC));
  579. foreach ($result as $block) {
  580. // If the region isn't supported by the theme, assign the block to the theme's default region.
  581. if ($block['status'] && !isset($regions[$block['region']])) {
  582. $block['region'] = system_default_region($theme);
  583. }
  584. $block['theme'] = $theme;
  585. unset($block['bid']);
  586. drupal_write_record('block', $block);
  587. }
  588. }
  589. }
  590. /**
  591. * Return all blocks in the specified region for the current user.
  592. *
  593. * @param $region
  594. * The name of a region.
  595. *
  596. * @return
  597. * An array of block objects, indexed with the module name and block delta
  598. * concatenated with an underscore, thus: MODULE_DELTA. If you are displaying
  599. * your blocks in one or two sidebars, you may check whether this array is
  600. * empty to see how many columns are going to be displayed.
  601. *
  602. * @todo
  603. * Now that the blocks table has a primary key, we should use that as the
  604. * array key instead of MODULE_DELTA.
  605. */
  606. function block_list($region) {
  607. $blocks = &drupal_static(__FUNCTION__);
  608. if (!isset($blocks)) {
  609. $blocks = _block_load_blocks();
  610. }
  611. // Create an empty array if there are no entries.
  612. if (!isset($blocks[$region])) {
  613. $blocks[$region] = array();
  614. }
  615. else {
  616. $blocks[$region] = _block_render_blocks($blocks[$region]);
  617. }
  618. return $blocks[$region];
  619. }
  620. /**
  621. * Load a block object from the database.
  622. *
  623. * @param $module
  624. * Name of the module that implements the block to load.
  625. * @param $delta
  626. * Unique ID of the block within the context of $module. Pass NULL to return
  627. * an empty $block object for $module.
  628. *
  629. * @return
  630. * A block object.
  631. */
  632. function block_load($module, $delta) {
  633. if (isset($delta)) {
  634. $block = db_query('SELECT * FROM {block} WHERE module = :module AND delta = :delta', array(':module' => $module, ':delta' => $delta))->fetchObject();
  635. }
  636. // If the block does not exist in the database yet return a stub block
  637. // object.
  638. if (empty($block)) {
  639. $block = new stdClass();
  640. $block->module = $module;
  641. $block->delta = $delta;
  642. }
  643. return $block;
  644. }
  645. /**
  646. * Load blocks information from the database.
  647. */
  648. function _block_load_blocks() {
  649. global $theme_key;
  650. $query = db_select('block', 'b');
  651. $result = $query
  652. ->fields('b')
  653. ->condition('b.theme', $theme_key)
  654. ->condition('b.status', 1)
  655. ->orderBy('b.region')
  656. ->orderBy('b.weight')
  657. ->orderBy('b.module')
  658. ->addTag('block_load')
  659. ->addTag('translatable')
  660. ->execute();
  661. $block_info = $result->fetchAllAssoc('bid');
  662. // Allow modules to modify the block list.
  663. drupal_alter('block_list', $block_info);
  664. $blocks = array();
  665. foreach ($block_info as $block) {
  666. $blocks[$block->region]["{$block->module}_{$block->delta}"] = $block;
  667. }
  668. return $blocks;
  669. }
  670. /**
  671. * Implements hook_block_list_alter().
  672. *
  673. * Check the page, user role and user specific visibilty settings.
  674. * Remove the block if the visibility conditions are not met.
  675. */
  676. function block_block_list_alter(&$blocks) {
  677. global $user, $theme_key;
  678. // Build an array of roles for each block.
  679. $block_roles = array();
  680. $result = db_query('SELECT module, delta, rid FROM {block_role}');
  681. foreach ($result as $record) {
  682. $block_roles[$record->module][$record->delta][] = $record->rid;
  683. }
  684. foreach ($blocks as $key => $block) {
  685. if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
  686. // This block was added by a contrib module, leave it in the list.
  687. continue;
  688. }
  689. // If a block has no roles associated, it is displayed for every role.
  690. // For blocks with roles associated, if none of the user's roles matches
  691. // the settings from this block, remove it from the block list.
  692. if (isset($block_roles[$block->module][$block->delta]) && !array_intersect($block_roles[$block->module][$block->delta], array_keys($user->roles))) {
  693. // No match.
  694. unset($blocks[$key]);
  695. continue;
  696. }
  697. // Use the user's block visibility setting, if necessary.
  698. if ($block->custom != BLOCK_CUSTOM_FIXED) {
  699. if ($user->uid && isset($user->data['block'][$block->module][$block->delta])) {
  700. $enabled = $user->data['block'][$block->module][$block->delta];
  701. }
  702. else {
  703. $enabled = ($block->custom == BLOCK_CUSTOM_ENABLED);
  704. }
  705. }
  706. else {
  707. $enabled = TRUE;
  708. }
  709. if (!$enabled) {
  710. unset($blocks[$key]);
  711. continue;
  712. }
  713. // Match path if necessary.
  714. if ($block->pages) {
  715. // Convert path to lowercase. This allows comparison of the same path
  716. // with different case. Ex: /Page, /page, /PAGE.
  717. $pages = drupal_strtolower($block->pages);
  718. if ($block->visibility < BLOCK_VISIBILITY_PHP) {
  719. // Convert the Drupal path to lowercase
  720. $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
  721. // Compare the lowercase internal and lowercase path alias (if any).
  722. $page_match = drupal_match_path($path, $pages);
  723. if ($path != $_GET['q']) {
  724. $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
  725. }
  726. // When $block->visibility has a value of 0 (BLOCK_VISIBILITY_NOTLISTED),
  727. // the block is displayed on all pages except those listed in $block->pages.
  728. // When set to 1 (BLOCK_VISIBILITY_LISTED), it is displayed only on those
  729. // pages listed in $block->pages.
  730. $page_match = !($block->visibility xor $page_match);
  731. }
  732. elseif (module_exists('php')) {
  733. $page_match = php_eval($block->pages);
  734. }
  735. else {
  736. $page_match = FALSE;
  737. }
  738. }
  739. else {
  740. $page_match = TRUE;
  741. }
  742. if (!$page_match) {
  743. unset($blocks[$key]);
  744. }
  745. }
  746. }
  747. /**
  748. * Render the content and subject for a set of blocks.
  749. *
  750. * @param $region_blocks
  751. * An array of block objects such as returned for one region by _block_load_blocks().
  752. *
  753. * @return
  754. * An array of visible blocks as expected by drupal_render().
  755. */
  756. function _block_render_blocks($region_blocks) {
  757. foreach ($region_blocks as $key => $block) {
  758. // Render the block content if it has not been created already.
  759. if (!isset($block->content)) {
  760. // Erase the block from the static array - we'll put it back if it has
  761. // content.
  762. unset($region_blocks[$key]);
  763. // Try fetching the block from cache. Block caching is not compatible
  764. // with node_access modules. We also preserve the submission of forms in
  765. // blocks, by fetching from cache only if the request method is 'GET'
  766. // (or 'HEAD').
  767. if (!count(module_implements('node_grants')) && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD') && ($cid = _block_get_cache_id($block)) && ($cache = cache_get($cid, 'cache_block'))) {
  768. $array = $cache->data;
  769. }
  770. else {
  771. $array = module_invoke($block->module, 'block_view', $block->delta);
  772. // Allow modules to modify the block before it is viewed, via either
  773. // hook_block_view_alter() or hook_block_view_MODULE_DELTA_alter().
  774. drupal_alter(array('block_view', "block_view_{$block->module}_{$block->delta}"), $array, $block);
  775. if (isset($cid)) {
  776. cache_set($cid, $array, 'cache_block', CACHE_TEMPORARY);
  777. }
  778. }
  779. if (isset($array) && is_array($array)) {
  780. foreach ($array as $k => $v) {
  781. $block->$k = $v;
  782. }
  783. }
  784. if (isset($block->content) && $block->content) {
  785. // Normalize to the drupal_render() structure.
  786. if (is_string($block->content)) {
  787. $block->content = array('#markup' => $block->content);
  788. }
  789. // Override default block title if a custom display title is present.
  790. if ($block->title) {
  791. // Check plain here to allow module generated titles to keep any
  792. // markup.
  793. $block->subject = $block->title == '<none>' ? '' : check_plain($block->title);
  794. }
  795. if (!isset($block->subject)) {
  796. $block->subject = '';
  797. }
  798. $region_blocks["{$block->module}_{$block->delta}"] = $block;
  799. }
  800. }
  801. }
  802. return $region_blocks;
  803. }
  804. /**
  805. * Assemble the cache_id to use for a given block.
  806. *
  807. * The cache_id string reflects the viewing context for the current block
  808. * instance, obtained by concatenating the relevant context information
  809. * (user, page, ...) according to the block's cache settings (BLOCK_CACHE_*
  810. * constants). Two block instances can use the same cached content when
  811. * they share the same cache_id.
  812. *
  813. * Theme and language contexts are automatically differentiated.
  814. *
  815. * @param $block
  816. * @return
  817. * The string used as cache_id for the block.
  818. */
  819. function _block_get_cache_id($block) {
  820. global $user;
  821. // User 1 being out of the regular 'roles define permissions' schema,
  822. // it brings too many chances of having unwanted output get in the cache
  823. // and later be served to other users. We therefore exclude user 1 from
  824. // block caching.
  825. if (variable_get('block_cache', FALSE) && !in_array($block->cache, array(DRUPAL_NO_CACHE, DRUPAL_CACHE_CUSTOM)) && $user->uid != 1) {
  826. // Start with common sub-patterns: block identification, theme, language.
  827. $cid_parts[] = $block->module;
  828. $cid_parts[] = $block->delta;
  829. $cid_parts = array_merge($cid_parts, drupal_render_cid_parts($block->cache));
  830. return implode(':', $cid_parts);
  831. }
  832. }
  833. /**
  834. * Implements hook_flush_caches().
  835. */
  836. function block_flush_caches() {
  837. // Rehash blocks for active themes. We don't use list_themes() here,
  838. // because if MAINTENANCE_MODE is defined it skips reading the database,
  839. // and we can't tell which themes are active.
  840. $themes = db_query("SELECT name FROM {system} WHERE type = 'theme' AND status = 1");
  841. foreach ($themes as $theme) {
  842. _block_rehash($theme->name);
  843. }
  844. return array('cache_block');
  845. }
  846. /**
  847. * Process variables for block.tpl.php
  848. *
  849. * Prepare the values passed to the theme_block function to be passed
  850. * into a pluggable template engine. Uses block properties to generate a
  851. * series of template file suggestions. If none are found, the default
  852. * block.tpl.php is used.
  853. *
  854. * Most themes utilize their own copy of block.tpl.php. The default is located
  855. * inside "modules/block/block.tpl.php". Look in there for the full list of
  856. * variables.
  857. *
  858. * The $variables array contains the following arguments:
  859. * - $block
  860. *
  861. * @see block.tpl.php
  862. */
  863. function template_preprocess_block(&$variables) {
  864. $block_counter = &drupal_static(__FUNCTION__, array());
  865. $variables['block'] = $variables['elements']['#block'];
  866. // All blocks get an independent counter for each region.
  867. if (!isset($block_counter[$variables['block']->region])) {
  868. $block_counter[$variables['block']->region] = 1;
  869. }
  870. // Same with zebra striping.
  871. $variables['block_zebra'] = ($block_counter[$variables['block']->region] % 2) ? 'odd' : 'even';
  872. $variables['block_id'] = $block_counter[$variables['block']->region]++;
  873. // Create the $content variable that templates expect.
  874. $variables['content'] = $variables['elements']['#children'];
  875. $variables['classes_array'][] = drupal_html_class('block-' . $variables['block']->module);
  876. $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->region;
  877. $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->module;
  878. // Hyphens (-) and underscores (_) play a special role in theme suggestions.
  879. // Theme suggestions should only contain underscores, because within
  880. // drupal_find_theme_templates(), underscores are converted to hyphens to
  881. // match template file names, and then converted back to underscores to match
  882. // pre-processing and other function names. So if your theme suggestion
  883. // contains a hyphen, it will end up as an underscore after this conversion,
  884. // and your function names won't be recognized. So, we need to convert
  885. // hyphens to underscores in block deltas for the theme suggestions.
  886. $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->module . '__' . strtr($variables['block']->delta, '-', '_');
  887. // Create a valid HTML ID and make sure it is unique.
  888. $variables['block_html_id'] = drupal_html_id('block-' . $variables['block']->module . '-' . $variables['block']->delta);
  889. }
  890. /**
  891. * Implements hook_user_role_delete().
  892. *
  893. * Remove deleted role from blocks that use it.
  894. */
  895. function block_user_role_delete($role) {
  896. db_delete('block_role')
  897. ->condition('rid', $role->rid)
  898. ->execute();
  899. }
  900. /**
  901. * Implements hook_menu_delete().
  902. */
  903. function block_menu_delete($menu) {
  904. db_delete('block')
  905. ->condition('module', 'menu')
  906. ->condition('delta', $menu['menu_name'])
  907. ->execute();
  908. db_delete('block_role')
  909. ->condition('module', 'menu')
  910. ->condition('delta', $menu['menu_name'])
  911. ->execute();
  912. }
  913. /**
  914. * Implements hook_form_FORM_ID_alter().
  915. */
  916. function block_form_system_performance_settings_alter(&$form, &$form_state) {
  917. $disabled = count(module_implements('node_grants'));
  918. $form['caching']['block_cache'] = array(
  919. '#type' => 'checkbox',
  920. '#title' => t('Cache blocks'),
  921. '#default_value' => variable_get('block_cache', FALSE),
  922. '#disabled' => $disabled,
  923. '#description' => $disabled ? t('Block caching is inactive because you have enabled modules defining content access restrictions.') : NULL,
  924. '#weight' => -1,
  925. );
  926. }
  927. /**
  928. * Implements hook_admin_paths().
  929. */
  930. function block_admin_paths() {
  931. $paths = array(
  932. // Exclude the block demonstration page from admin (overlay) treatment.
  933. // This allows us to present this page in its true form, full page.
  934. 'admin/structure/block/demo/*' => FALSE,
  935. );
  936. return $paths;
  937. }
  938. /**
  939. * Implements hook_modules_uninstalled().
  940. *
  941. * Cleanup {block} and {block_role} tables from modules' blocks.
  942. */
  943. function block_modules_uninstalled($modules) {
  944. db_delete('block')
  945. ->condition('module', $modules, 'IN')
  946. ->execute();
  947. db_delete('block_role')
  948. ->condition('module', $modules, 'IN')
  949. ->execute();
  950. }