Newer
Older
* Controls the visual building blocks a page is constructed with.
/**
* Denotes that a block is not enabled in any region and should not be shown.
*/

Dries Buytaert
committed
define('BLOCK_REGION_NONE', -1);
/**
* Users cannot control whether or not they see this block.
*/
define('BLOCK_CUSTOM_FIXED', 0);
/**
* Shows this block by default, but lets individual users hide it.
*/
define('BLOCK_CUSTOM_ENABLED', 1);
/**
* Hides this block by default but lets individual users show it.
*/
define('BLOCK_CUSTOM_DISABLED', 2);
/**
* Shows this block on every page except the listed pages.
*/
define('BLOCK_VISIBILITY_NOTLISTED', 0);
/**
* Shows this block on only the listed pages.
*/
define('BLOCK_VISIBILITY_LISTED', 1);
/**
* Shows this block if the associated PHP code returns TRUE.
*/
define('BLOCK_VISIBILITY_PHP', 2);

Dries Buytaert
committed
* Implements hook_help().

Gábor Hojtsy
committed
function block_help($path, $arg) {
switch ($path) {
$output = '';
$output .= '<h3>' . t('About') . '</h3>';

Jennifer Hodgdon
committed
$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>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Positioning content') . '</dt>';

Jennifer Hodgdon
committed
$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>';
$output .= '<dt>' . t('Controlling visibility') . '</dt>';
$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>';
$output .= '<dt>' . t('Creating custom blocks') . '</dt>';
$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>';
$output .= '</dl>';

Dries Buytaert
committed
return $output;

Dries Buytaert
committed
case 'admin/structure/block/add':

Dries Buytaert
committed
return '<p>' . t('Use this page to create a new custom block.') . '</p>';

Angie Byron
committed
if ($arg[0] == 'admin' && $arg[1] == 'structure' && $arg['2'] == 'block' && (empty($arg[3]) || $arg[3] == 'list')) {
$demo_theme = !empty($arg[4]) ? $arg[4] : variable_get('theme_default', 'bartik');

Dries Buytaert
committed
$themes = list_themes();
$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>';

David Rothstein
committed
$output .= '<p>' . l(t('Demonstrate block regions (!theme)', array('!theme' => $themes[$demo_theme]->info['name'])), 'admin/structure/block/demo/' . $demo_theme) . '</p>';

Dries Buytaert
committed
return $output;
}

Dries Buytaert
committed
/**

Dries Buytaert
committed
* Implements hook_theme().

Dries Buytaert
committed
*/
function block_theme() {
return array(

Angie Byron
committed
'block' => array(
'render element' => 'elements',

Angie Byron
committed
'template' => 'block',
'block_admin_display_form' => array(
'template' => 'block-admin-display-form',
'file' => 'block.admin.inc',
'render element' => 'form',

Dries Buytaert
committed
),
);
}

Dries Buytaert
committed
* Implements hook_permission().
function block_permission() {
return array(

Angie Byron
committed
'administer blocks' => array(
'title' => t('Administer blocks'),
),
);

Dries Buytaert
committed
* Implements hook_menu().

Dries Buytaert
committed
function block_menu() {
$default_theme = variable_get('theme_default', 'bartik');

Dries Buytaert
committed
$items['admin/structure/block'] = array(
'title' => 'Blocks',
'description' => 'Configure what block content appears in your site\'s sidebars and other regions.',
'page callback' => 'block_admin_display',

Dries Buytaert
committed
'page arguments' => array($default_theme),

Dries Buytaert
committed
'access arguments' => array('administer blocks'),
'file' => 'block.admin.inc',

Dries Buytaert
committed
);

Dries Buytaert
committed
$items['admin/structure/block/manage/%/%'] = array(
'title' => 'Configure block',
'page callback' => 'drupal_get_form',

Dries Buytaert
committed
'page arguments' => array('block_admin_configure', 4, 5),

Dries Buytaert
committed
'access arguments' => array('administer blocks'),
'file' => 'block.admin.inc',

Dries Buytaert
committed
);

Dries Buytaert
committed
$items['admin/structure/block/manage/%/%/configure'] = array(

Angie Byron
committed
'title' => 'Configure block',
'type' => MENU_DEFAULT_LOCAL_TASK,
'context' => MENU_CONTEXT_INLINE,
);

Dries Buytaert
committed
$items['admin/structure/block/manage/%/%/delete'] = array(
'title' => 'Delete block',
'page callback' => 'drupal_get_form',

Dries Buytaert
committed
'page arguments' => array('block_custom_block_delete', 4, 5),

Dries Buytaert
committed
'access arguments' => array('administer blocks'),

Dries Buytaert
committed
'type' => MENU_LOCAL_TASK,
'context' => MENU_CONTEXT_NONE,
'file' => 'block.admin.inc',

Dries Buytaert
committed
);

Dries Buytaert
committed
$items['admin/structure/block/add'] = array(
'title' => 'Add block',
'page callback' => 'drupal_get_form',

Dries Buytaert
committed
'page arguments' => array('block_add_block_form'),

Dries Buytaert
committed
'access arguments' => array('administer blocks'),

Angie Byron
committed
'type' => MENU_LOCAL_ACTION,
'file' => 'block.admin.inc',

Dries Buytaert
committed
);
foreach (list_themes() as $key => $theme) {

Dries Buytaert
committed
$items['admin/structure/block/list/' . $key] = array(

David Rothstein
committed
'title' => $theme->info['name'],

Gábor Hojtsy
committed
'page arguments' => array($key),

Dries Buytaert
committed
'type' => $key == $default_theme ? MENU_DEFAULT_LOCAL_TASK : MENU_LOCAL_TASK,
'weight' => $key == $default_theme ? -10 : 0,
'access callback' => '_block_themes_access',
'access arguments' => array($theme),
'file' => 'block.admin.inc',
);

Angie Byron
committed
if ($key != $default_theme) {
$items['admin/structure/block/list/' . $key . '/add'] = array(
'title' => 'Add block',
'page callback' => 'drupal_get_form',
'page arguments' => array('block_add_block_form'),
'access arguments' => array('administer blocks'),
'type' => MENU_LOCAL_ACTION,
'file' => 'block.admin.inc',
);
}

Dries Buytaert
committed
$items['admin/structure/block/demo/' . $key] = array(

David Rothstein
committed
'title' => $theme->info['name'],

Dries Buytaert
committed
'page callback' => 'block_admin_demo',
'page arguments' => array($key),
'type' => MENU_CALLBACK,

Gábor Hojtsy
committed
'access callback' => '_block_themes_access',
'access arguments' => array($theme),

Dries Buytaert
committed
'theme callback' => '_block_custom_theme',
'theme arguments' => array($key),
'file' => 'block.admin.inc',

Gábor Hojtsy
committed
);

Gábor Hojtsy
committed
/**
* Menu item access callback - only admin or enabled themes can be accessed.

Gábor Hojtsy
committed
*/
function _block_themes_access($theme) {

Dries Buytaert
committed
return user_access('administer blocks') && drupal_theme_access($theme);
}
/**
* Theme callback for the block configuration pages.
*
* @param $theme
* The theme whose blocks are being configured. If not set, the default theme
* is assumed.
*

Dries Buytaert
committed
* @return
* The theme that should be used for the block configuration page, or NULL
* to indicate that the default theme should be used.
*/
function _block_custom_theme($theme = NULL) {
// We return exactly what was passed in, to guarantee that the page will
// always be displayed using the theme whose blocks are being configured.
return $theme;

Gábor Hojtsy
committed
}

Dries Buytaert
committed
* Implements hook_block_info().

Dries Buytaert
committed
function block_block_info() {

Dries Buytaert
committed
$blocks = array();
$result = db_query('SELECT bid, info FROM {block_custom} ORDER BY info');

Dries Buytaert
committed
foreach ($result as $block) {

Dries Buytaert
committed
$blocks[$block->bid]['info'] = $block->info;
// Not worth caching.
$blocks[$block->bid]['cache'] = DRUPAL_NO_CACHE;

Dries Buytaert
committed
}
return $blocks;
}

Dries Buytaert
committed
/**

Dries Buytaert
committed
* Implements hook_block_configure().

Dries Buytaert
committed
*/
function block_block_configure($delta = 0) {

Dries Buytaert
committed
if ($delta) {
$custom_block = block_custom_block_get($delta);

Dries Buytaert
committed
}

Angie Byron
committed
else {
$custom_block = array();
}
return block_custom_block_form($custom_block);
}

Dries Buytaert
committed
/**

Dries Buytaert
committed
* Implements hook_block_save().

Dries Buytaert
committed
*/
function block_block_save($delta = 0, $edit = array()) {
block_custom_block_save($edit, $delta);

Dries Buytaert
committed
}
/**

Dries Buytaert
committed
* Implements hook_block_view().

Dries Buytaert
committed
*
* Generates the administrator-defined blocks for display.
*/
function block_block_view($delta = '') {
$block = db_query('SELECT body, format FROM {block_custom} WHERE bid = :bid', array(':bid' => $delta))->fetchObject();
$data['subject'] = NULL;
$data['content'] = check_markup($block->body, $block->format, '', TRUE);

Dries Buytaert
committed
return $data;
}
/**

Dries Buytaert
committed
* Implements hook_page_build().
*
* Renders blocks into their regions.
*/

Angie Byron
committed
function block_page_build(&$page) {
global $theme;
// The theme system might not yet be initialized. We need $theme.

Dries Buytaert
committed
drupal_theme_initialize();
// Fetch a list of regions for the current theme.

Dries Buytaert
committed
$all_regions = system_region_list($theme);

Dries Buytaert
committed
$item = menu_get_item();
if ($item['path'] != 'admin/structure/block/demo/' . $theme) {
// Load all region content assigned via blocks.
foreach (array_keys($all_regions) as $region) {
// Assign blocks to region.
if ($blocks = block_get_blocks_by_region($region)) {
$page[$region] = $blocks;
}

Dries Buytaert
committed
}

Angie Byron
committed
// Once we've finished attaching all blocks to the page, clear the static
// cache to allow modules to alter the block list differently in different
// contexts. For example, any code that triggers hook_page_build() more
// than once in the same page request may need to alter the block list
// differently each time, so that only certain parts of the page are
// actually built. We do not clear the cache any earlier than this, though,
// because it is used each time block_get_blocks_by_region() gets called
// above.
drupal_static_reset('block_list');

Dries Buytaert
committed
}
else {
// Append region description if we are rendering the regions demo page.

Dries Buytaert
committed
$item = menu_get_item();

Dries Buytaert
committed
if ($item['path'] == 'admin/structure/block/demo/' . $theme) {
$visible_regions = array_keys(system_region_list($theme, REGIONS_VISIBLE));
foreach ($visible_regions as $region) {

Dries Buytaert
committed
$description = '<div class="block-region">' . $all_regions[$region] . '</div>';
$page[$region]['block_description'] = array(
'#markup' => $description,
'#weight' => 15,
);
}

Angie Byron
committed
$page['page_top']['backlink'] = array(
'#type' => 'link',
'#title' => t('Exit block region demonstration'),

Dries Buytaert
committed
'#href' => 'admin/structure/block' . (variable_get('theme_default', 'bartik') == $theme ? '' : '/list/' . $theme),

Angie Byron
committed
// Add the "overlay-restore" class to indicate this link should restore
// the context in which the region demonstration page was opened.
'#options' => array('attributes' => array('class' => array('block-demo-backlink', 'overlay-restore'))),
'#weight' => -10,
);
}
}
}
/**
* Gets a renderable array of a region containing all enabled blocks.
*
* @param $region
* The requested region.
*
* @return
* A renderable array of a region containing all enabled blocks.
*/
function block_get_blocks_by_region($region) {
$build = array();
if ($list = block_list($region)) {

Dries Buytaert
committed
$build = _block_get_renderable_array($list);
}
return $build;
}
/**
* Gets an array of blocks suitable for drupal_render().

Dries Buytaert
committed
*
* @param $list
* A list of blocks such as that returned by block_list().

Dries Buytaert
committed
* @return
* A renderable array.
*/
function _block_get_renderable_array($list = array()) {
$weight = 0;
$build = array();
foreach ($list as $key => $block) {
$build[$key] = $block->content;
unset($block->content);

Angie Byron
committed

Dries Buytaert
committed
// Add contextual links for this block; skip the main content block, since
// contextual links are basically output as tabs/local tasks already. Also
// skip the help block, since we assume that most users do not need or want
// to perform contextual actions on the help block, and the links needlessly
// draw attention on it.
if ($key != 'system_main' && $key != 'system_help') {
$build[$key]['#contextual_links']['block'] = array(
'admin/structure/block/manage',
array($block->module, $block->delta),
);

Angie Byron
committed
}

Dries Buytaert
committed
$build[$key] += array(
'#block' => $block,
'#weight' => ++$weight,
);
$build[$key]['#theme_wrappers'][] = 'block';
}

Dries Buytaert
committed
$build['#sorted'] = TRUE;
return $build;
}
* Updates the 'block' DB table with the blocks currently exported by modules.
* @param $theme

Dries Buytaert
committed
* The theme to rehash blocks for. If not provided, defaults to the currently
* used theme.

Angie Byron
committed
*

Steven Wittens
committed
* Blocks currently exported by modules.

Dries Buytaert
committed
function _block_rehash($theme = NULL) {

Angie Byron
committed

Dries Buytaert
committed
drupal_theme_initialize();

Dries Buytaert
committed
if (!isset($theme)) {
// If theme is not specifically set, rehash for the current theme.
$theme = $theme_key;
}
$regions = system_region_list($theme);
// These are the blocks the function will return.
$blocks = array();
// These are the blocks defined by code and modified by the database.
$current_blocks = array();
// These are {block}.bid values to be kept.
$bids = array();
$or = db_or();
// Gather the blocks defined by modules.

Dries Buytaert
committed
foreach (module_implements('block_info') as $module) {
$module_blocks = module_invoke($module, 'block_info');
$delta_list = array();
foreach ($module_blocks as $delta => $block) {
// Compile a condition to retrieve this block from the database.
// Add identifiers.
$delta_list[] = $delta;
$block['module'] = $module;
$block['delta'] = $delta;
$block['theme'] = $theme;
$current_blocks[$module][$delta] = $block;
if (!empty($delta_list)) {
$condition = db_and()->condition('module', $module)->condition('delta', $delta_list);
$or->condition($condition);
}
// Save the blocks defined in code for alter context.
$code_blocks = $current_blocks;

David Rothstein
committed
$database_blocks = db_select('block', 'b', array('fetch' => PDO::FETCH_ASSOC))
->fields('b')
->condition($or)
->condition('theme', $theme)
->execute();

David Rothstein
committed
$original_database_blocks = array();
foreach ($database_blocks as $block) {

David Rothstein
committed
$module = $block['module'];
$delta = $block['delta'];
$original_database_blocks[$module][$delta] = $block;

Dries Buytaert
committed
// The cache mode can only by set from hook_block_info(), so that has
// precedence over the database's value.

David Rothstein
committed
if (isset($current_blocks[$module][$delta]['cache'])) {
$block['cache'] = $current_blocks[$module][$delta]['cache'];

Dries Buytaert
committed
}

David Rothstein
committed
// Preserve info which is not in the database.
$block['info'] = $current_blocks[$module][$delta]['info'];
// Blocks stored in the database override the blocks defined in code.

David Rothstein
committed
$current_blocks[$module][$delta] = $block;
// Preserve this block.

David Rothstein
committed
$bids[$block['bid']] = $block['bid'];
}
drupal_alter('block_info', $current_blocks, $theme, $code_blocks);
foreach ($current_blocks as $module => $module_blocks) {
foreach ($module_blocks as $delta => $block) {
if (!isset($block['pages'])) {
// {block}.pages is type 'text', so it cannot have a
// default value, and not null, so we need to provide
// value if the module did not.
$block['pages'] = '';
}
// Make sure weight is set.
if (!isset($block['weight'])) {
$block['weight'] = 0;
}

Angie Byron
committed
if (!empty($block['region']) && $block['region'] != BLOCK_REGION_NONE && !isset($regions[$block['region']]) && $block['status'] == 1) {
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');
// Disabled modules are moved into the BLOCK_REGION_NONE later so no

Angie Byron
committed
// need to move the block to another region.
$block['status'] = 0;
}
// Set region to none if not enabled and make sure status is set.
if (empty($block['status'])) {
$block['status'] = 0;
$block['region'] = BLOCK_REGION_NONE;
}
// There is no point saving disabled blocks. Still, we need to save them

Dries Buytaert
committed
// because the 'title' attribute is saved to the {blocks} table.
if (isset($block['bid'])) {
// If the block has a bid property, it comes from the database and
// the record needs to be updated, so set the primary key to 'bid'
// before passing to drupal_write_record().
$primary_keys = array('bid');
// Remove a block from the list of blocks to keep if it became disabled.
unset($bids[$block['bid']]);
}
else {
$primary_keys = array();
}

David Rothstein
committed
// If the block is new or differs from the original database block, save
// it. To determine whether there was a change it is enough to examine
// the values for the keys in the original database record as that
// contained every database field.
if (!$primary_keys || array_diff_assoc($original_database_blocks[$module][$delta], $block)) {
drupal_write_record('block', $block, $primary_keys);
// Make it possible to test this.
$block['saved'] = TRUE;
}
// Add to the list of blocks we return.
$blocks[] = $block;

Gábor Hojtsy
committed
}

Dries Buytaert
committed
}
if ($bids) {
// Remove disabled that are no longer defined by the code from the
// database.
db_delete('block')
->condition('bid', $bids, 'NOT IN')
->condition('theme', $theme)
->execute();
}

Dries Buytaert
committed
/**
* Returns information from database about a user-created (custom) block.
*
* @param $bid
* ID of the block to get information for.

Dries Buytaert
committed
* @return
* Associative array of information stored in the database for this block.
* Array keys:
* - bid: Block ID.
* - info: Block description.
* - body: Block contents.
* - format: Filter ID of the filter format for the body.
*/
function block_custom_block_get($bid) {
return db_query("SELECT * FROM {block_custom} WHERE bid = :bid", array(':bid' => $bid))->fetchAssoc();
* Form constructor for the custom block form.
*
* @param $edit
* (optional) An associative array of information retrieved by
* block_custom_get_block() if an existing block is being edited, or an empty
* array otherwise. Defaults to array().
*
* @ingroup forms
function block_custom_block_form($edit = array()) {

Steven Wittens
committed
$edit += array(
'info' => '',
'body' => '',
);

Dries Buytaert
committed
$form['info'] = array(
'#type' => 'textfield',
'#title' => t('Block description'),
'#default_value' => $edit['info'],

Dries Buytaert
committed
'#maxlength' => 64,

Dries Buytaert
committed
'#description' => t('A brief description of your block. Used on the <a href="@overview">Blocks administration page</a>.', array('@overview' => url('admin/structure/block'))),

Dries Buytaert
committed
'#required' => TRUE,
'#weight' => -18,

Dries Buytaert
committed
);
$form['body_field']['#weight'] = -17;
$form['body_field']['body'] = array(
'#type' => 'text_format',

Dries Buytaert
committed
'#title' => t('Block body'),
'#default_value' => $edit['body'],
'#format' => isset($edit['format']) ? $edit['format'] : NULL,

Dries Buytaert
committed
'#rows' => 15,
'#description' => t('The content of the block as shown to the user.'),
'#required' => TRUE,

Dries Buytaert
committed
'#weight' => -17,
);
}

Dries Buytaert
committed
/**
* Saves a user-created block in the database.
*
* @param $edit
* Associative array of fields to save. Array keys:
* - info: Block description.

Dries Buytaert
committed
* - body: Associative array of body value and format. Array keys:
* - value: Block contents.
* - format: Filter ID of the filter format for the body.

Dries Buytaert
committed
* @param $delta
* Block ID of the block to save.

Dries Buytaert
committed
* @return
* Always returns TRUE.
*/
function block_custom_block_save($edit, $delta) {
db_update('block_custom')

Dries Buytaert
committed
->fields(array(

Dries Buytaert
committed
'body' => $edit['body']['value'],

Dries Buytaert
committed
'info' => $edit['info'],

Dries Buytaert
committed
'format' => $edit['body']['format'],

Dries Buytaert
committed
))
->condition('bid', $delta)
->execute();

Dries Buytaert
committed
return TRUE;
}
* Implements hook_form_FORM_ID_alter() for user_profile_form().

Dries Buytaert
committed
function block_form_user_profile_form_alter(&$form, &$form_state) {
if ($form['#user_category'] == 'account') {
$account = $form['#user'];

Dries Buytaert
committed
$rids = array_keys($account->roles);
$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));
$blocks = array();

Dries Buytaert
committed
foreach ($result as $block) {

Dries Buytaert
committed
$data = module_invoke($block->module, 'block_info');

Dries Buytaert
committed
if ($data[$block->delta]['info']) {
$blocks[$block->module][$block->delta] = array(

Dries Buytaert
committed
'#type' => 'checkbox',
'#title' => check_plain($data[$block->delta]['info']),
'#default_value' => isset($account->data['block'][$block->module][$block->delta]) ? $account->data['block'][$block->module][$block->delta] : ($block->custom == 1),

Dries Buytaert
committed
);

Dries Buytaert
committed
}
// Only display the fieldset if there are any personalizable blocks.
if ($blocks) {
$form['block'] = array(
'#type' => 'fieldset',
'#title' => t('Personalize blocks'),
'#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.'),
'#weight' => 3,
'#collapsible' => TRUE,
'#tree' => TRUE,
);
$form['block'] += $blocks;

Dries Buytaert
committed
}
}
}
/**
* Implements hook_user_presave().
*/
function block_user_presave(&$edit, $account, $category) {
if (isset($edit['block'])) {
$edit['data']['block'] = $edit['block'];
}
}

Dries Buytaert
committed
/**
* Initializes blocks for enabled themes.
*
* @param $theme_list
* An array of theme names.

Dries Buytaert
committed
*/

Dries Buytaert
committed
function block_themes_enabled($theme_list) {
foreach ($theme_list as $theme) {
block_theme_initialize($theme);

Dries Buytaert
committed
}
}
/**
* Assigns an initial, default set of blocks for a theme.

Dries Buytaert
committed
* This function is called the first time a new theme is enabled. The new theme
* gets a copy of the default theme's blocks, with the difference that if a
* particular region isn't available in the new theme, the block is assigned
* to the new theme's default region.

Dries Buytaert
committed
* @param $theme
* The name of a theme.
*/

Dries Buytaert
committed
function block_theme_initialize($theme) {

Dries Buytaert
committed
// Initialize theme's blocks if none already registered.

Angie Byron
committed
$has_blocks = (bool) db_query_range('SELECT 1 FROM {block} WHERE theme = :theme', 0, 1, array(':theme' => $theme))->fetchField();

Angie Byron
committed
if (!$has_blocks) {
$default_theme = variable_get('theme_default', 'bartik');

Angie Byron
committed
// Apply only to new theme's visible regions.
$regions = system_region_list($theme, REGIONS_VISIBLE);

Dries Buytaert
committed
$result = db_query("SELECT * FROM {block} WHERE theme = :theme", array(':theme' => $default_theme), array('fetch' => PDO::FETCH_ASSOC));
foreach ($result as $block) {
// If the region isn't supported by the theme, assign the block to the
// theme's default region.

Dries Buytaert
committed
if ($block['status'] && !isset($regions[$block['region']])) {

Dries Buytaert
committed
$block['region'] = system_default_region($theme);
}

Dries Buytaert
committed
$block['theme'] = $theme;

Dries Buytaert
committed
unset($block['bid']);
drupal_write_record('block', $block);

Dries Buytaert
committed
}
}
}
* Returns all blocks in the specified region for the current user.
*
* @param $region
* The name of a region.
*
* @return

Angie Byron
committed
* An array of block objects, indexed with the module name and block delta
* concatenated with an underscore, thus: MODULE_DELTA. If you are displaying
* your blocks in one or two sidebars, you may check whether this array is
* empty to see how many columns are going to be displayed.
* Now that the block table has a primary key, we should use that as the

Angie Byron
committed
* array key instead of MODULE_DELTA.
*/
function block_list($region) {

Dries Buytaert
committed
$blocks = &drupal_static(__FUNCTION__);

Dries Buytaert
committed
if (!isset($blocks)) {

Dries Buytaert
committed
$blocks = _block_load_blocks();
}

Dries Buytaert
committed
// Create an empty array if there are no entries.

Dries Buytaert
committed
if (!isset($blocks[$region])) {
$blocks[$region] = array();
}

Dries Buytaert
committed
else {
$blocks[$region] = _block_render_blocks($blocks[$region]);
}

Dries Buytaert
committed
return $blocks[$region];
}

Angie Byron
committed
/**
* Loads a block object from the database.

Angie Byron
committed
*

David Rothstein
committed
* This function returns the first block matching the module and delta
* parameters, so it should not be used for theme-specific functionality.
*

Angie Byron
committed
* @param $module
* Name of the module that implements the block to load.
* @param $delta

Dries Buytaert
committed
* Unique ID of the block within the context of $module. Pass NULL to return
* an empty block object for $module.

Angie Byron
committed
*
* @return
* A block object.
*/
function block_load($module, $delta) {

Dries Buytaert
committed
if (isset($delta)) {
$block = db_query('SELECT * FROM {block} WHERE module = :module AND delta = :delta', array(':module' => $module, ':delta' => $delta))->fetchObject();
}

Angie Byron
committed
// If the block does not exist in the database yet return a stub block
// object.

Dries Buytaert
committed
if (empty($block)) {

Dries Buytaert
committed
$block = new stdClass();

Angie Byron
committed
$block->module = $module;
$block->delta = $delta;
}
return $block;
}

Dries Buytaert
committed
/**
* Loads blocks' information from the database.
*
* @return
* An array of blocks grouped by region.

Dries Buytaert
committed
*/
function _block_load_blocks() {
global $theme_key;

Dries Buytaert
committed

Dries Buytaert
committed
$query = db_select('block', 'b');
$result = $query
->fields('b')
->condition('b.theme', $theme_key)
->condition('b.status', 1)
->orderBy('b.region')
->orderBy('b.weight')
->orderBy('b.module')
->addTag('block_load')

Dries Buytaert
committed
->addTag('translatable')

Dries Buytaert
committed
->execute();

Dries Buytaert
committed
$block_info = $result->fetchAllAssoc('bid');
// Allow modules to modify the block list.
drupal_alter('block_list', $block_info);
$blocks = array();

Dries Buytaert
committed
foreach ($block_info as $block) {
$blocks[$block->region]["{$block->module}_{$block->delta}"] = $block;
}
return $blocks;
}
/**
* Implements hook_block_list_alter().
*

David Rothstein
committed
* Checks the page, user role, and user-specific visibility settings.
* Removes the block if the visibility conditions are not met.
*/
function block_block_list_alter(&$blocks) {
global $user, $theme_key;
// Build an array of roles for each block.
$block_roles = array();
$result = db_query('SELECT module, delta, rid FROM {block_role}');
foreach ($result as $record) {
$block_roles[$record->module][$record->delta][] = $record->rid;
}
foreach ($blocks as $key => $block) {

Dries Buytaert
committed
if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
// This block was added by a contrib module, leave it in the list.
continue;

Dries Buytaert
committed
}
// If a block has no roles associated, it is displayed for every role.
// For blocks with roles associated, if none of the user's roles matches
// the settings from this block, remove it from the block list.

Dries Buytaert
committed
if (isset($block_roles[$block->module][$block->delta]) && !array_intersect($block_roles[$block->module][$block->delta], array_keys($user->roles))) {
// No match.
unset($blocks[$key]);
continue;

Dries Buytaert
committed
}
// Use the user's block visibility setting, if necessary.
if ($block->custom != BLOCK_CUSTOM_FIXED) {
if ($user->uid && isset($user->data['block'][$block->module][$block->delta])) {
$enabled = $user->data['block'][$block->module][$block->delta];
}
else {
$enabled = ($block->custom == BLOCK_CUSTOM_ENABLED);

Steven Wittens
committed
}

Dries Buytaert
committed
}
else {
$enabled = TRUE;
}

Dries Buytaert
committed
// Limited visibility blocks must list at least one page.
if ($block->visibility == BLOCK_VISIBILITY_LISTED && empty($block->pages)) {
$enabled = FALSE;
}
if (!$enabled) {
unset($blocks[$key]);
continue;
}

Steven Wittens
committed
// Match path if necessary.

Dries Buytaert
committed
if ($block->pages) {

Angie Byron
committed
// Convert path to lowercase. This allows comparison of the same path
// with different case. Ex: /Page, /page, /PAGE.
$pages = drupal_strtolower($block->pages);
if ($block->visibility < BLOCK_VISIBILITY_PHP) {
// Convert the Drupal path to lowercase.

Angie Byron
committed
$path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
// Compare the lowercase internal and lowercase path alias (if any).
$page_match = drupal_match_path($path, $pages);

Dries Buytaert
committed
if ($path != $_GET['q']) {

Angie Byron
committed
$page_match = $page_match || drupal_match_path($_GET['q'], $pages);

Dries Buytaert
committed
}
// When $block->visibility has a value of 0
// (BLOCK_VISIBILITY_NOTLISTED), the block is displayed on all pages
// except those listed in $block->pages. When set to 1
// (BLOCK_VISIBILITY_LISTED), it is displayed only on those pages
// listed in $block->pages.

Dries Buytaert
committed
$page_match = !($block->visibility xor $page_match);

Steven Wittens
committed
}
elseif (module_exists('php')) {
$page_match = php_eval($block->pages);
}

Steven Wittens
committed
else {
$page_match = FALSE;

Steven Wittens
committed
}

Dries Buytaert
committed
}
else {
$page_match = TRUE;
}
if (!$page_match) {
unset($blocks[$key]);
}

Dries Buytaert
committed
}
}

Dries Buytaert
committed

Dries Buytaert
committed
/**
* Render the content and subject for a set of blocks.
*
* @param $region_blocks
* An array of block objects such as returned for one region by
* _block_load_blocks().

Dries Buytaert
committed
*
* @return
* An array of visible blocks as expected by drupal_render().

Dries Buytaert
committed
*/
function _block_render_blocks($region_blocks) {

David Rothstein
committed
$cacheable = TRUE;
// We preserve the submission of forms in blocks, by fetching from cache only

Angie Byron
committed
// if the request method is 'GET' (or 'HEAD').

David Rothstein
committed
if ($_SERVER['REQUEST_METHOD'] != 'GET' && $_SERVER['REQUEST_METHOD'] != 'HEAD') {
$cacheable = FALSE;
}
// Block caching is not usually compatible with node access modules, so by
// default it is disabled when node access modules exist. However, it can be
// allowed by using the variable 'block_cache_bypass_node_grants'.
elseif (!variable_get('block_cache_bypass_node_grants', FALSE) && count(module_implements('node_grants'))) {
$cacheable = FALSE;
}
// Proceed to loop over all blocks in order to compute their respective cache
// identifiers; this allows us to do one single cache_get_multiple() call
// instead of doing one cache_get() call per block.
$cached_blocks = array();
$cids = array();
if ($cacheable) {
foreach ($region_blocks as $key => $block) {
if (!isset($block->content)) {
if (($cid = _block_get_cache_id($block))) {
$cids[$key] = $cid;
}
}
}
if ($cids) {
// We cannot pass $cids in directly because cache_get_multiple() will
// modify it, and we need to use it later on in this function.
$cid_values = array_values($cids);
$cached_blocks = cache_get_multiple($cid_values, 'cache_block');
}
}

Dries Buytaert
committed
foreach ($region_blocks as $key => $block) {
// Render the block content if it has not been created already.
if (!isset($block->content)) {
// Erase the block from the static array - we'll put it back if it has
// content.

Dries Buytaert
committed
unset($region_blocks[$key]);
$cid = empty($cids[$key]) ? NULL : $cids[$key];
// Try fetching the block from the previously loaded cache entries.
if (isset($cached_blocks[$cid])) {
$array = $cached_blocks[$cid]->data;
}
else {
$array = module_invoke($block->module, 'block_view', $block->delta);

Angie Byron
committed

David Rothstein
committed
// Valid PHP function names cannot contain hyphens.
$delta = str_replace('-', '_', $block->delta);

Angie Byron
committed
// Allow modules to modify the block before it is viewed, via either
// hook_block_view_alter() or hook_block_view_MODULE_DELTA_alter().

David Rothstein
committed
drupal_alter(array('block_view', "block_view_{$block->module}_{$delta}"), $array, $block);

Angie Byron
committed
if (isset($cid)) {
cache_set($cid, $array, 'cache_block', CACHE_TEMPORARY);

Dries Buytaert
committed
}
}
if (isset($array) && is_array($array)) {
foreach ($array as $k => $v) {
$block->$k = $v;
}
if (isset($block->content) && $block->content) {
// Normalize to the drupal_render() structure.
if (is_string($block->content)) {
$block->content = array('#markup' => $block->content);
}
// Override default block title if a custom display title is present.
if ($block->title) {
// Check plain here to allow module generated titles to keep any
// markup.
$block->subject = $block->title == '<none>' ? '' : check_plain($block->title);
}
if (!isset($block->subject)) {
$block->subject = '';
$region_blocks["{$block->module}_{$block->delta}"] = $block;

Dries Buytaert
committed
return $region_blocks;
/**
* Assemble the cache_id to use for a given block.
*
* The cache_id string reflects the viewing context for the current block
* instance, obtained by concatenating the relevant context information
* (user, page, ...) according to the block's cache settings (BLOCK_CACHE_*
* constants). Two block instances can use the same cached content when
* they share the same cache_id.
*
* Theme and language contexts are automatically differentiated.
*
* @param $block
* The block to get the cache_id from.
*
* @return
* The string used as cache_id for the block.
*/
function _block_get_cache_id($block) {
global $user;

Angie Byron
committed
// User 1 being out of the regular 'roles define permissions' schema,
// it brings too many chances of having unwanted output get in the cache
// and later be served to other users. We therefore exclude user 1 from
// block caching.

Dries Buytaert
committed
if (variable_get('block_cache', FALSE) && !in_array($block->cache, array(DRUPAL_NO_CACHE, DRUPAL_CACHE_CUSTOM)) && $user->uid != 1) {
// Start with common sub-patterns: block identification, theme, language.
$cid_parts[] = $block->module;
$cid_parts[] = $block->delta;

David Rothstein
committed
drupal_alter('block_cid_parts', $cid_parts, $block);

Dries Buytaert
committed
$cid_parts = array_merge($cid_parts, drupal_render_cid_parts($block->cache));
return implode(':', $cid_parts);
}

Dries Buytaert
committed
}

Dries Buytaert
committed
* Implements hook_flush_caches().
*/
function block_flush_caches() {

Dries Buytaert
committed
// Rehash blocks for active themes. We don't use list_themes() here,
// because if MAINTENANCE_MODE is defined it skips reading the database,
// and we can't tell which themes are active.
$themes = db_query("SELECT name FROM {system} WHERE type = 'theme' AND status = 1");
foreach ($themes as $theme) {
_block_rehash($theme->name);
}