block.module 29.7 KB
Newer Older
Dries's avatar
 
Dries committed
1
<?php
2
// $Id$
Dries's avatar
 
Dries committed
3

Dries's avatar
 
Dries committed
4 5 6 7 8
/**
 * @file
 * Controls the boxes that are displayed around the main content.
 */

9 10 11
/**
 * Denotes that a block is not enabled in any region and should not be shown.
 */
12 13
define('BLOCK_REGION_NONE', -1);

14 15 16 17
/**
 * Constants defining cache granularity for blocks.
 *
 * Modules specify the caching patterns for their blocks using binary
18
 * combinations of these constants in their hook_block_list():
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
 *   $block[delta]['cache'] = BLOCK_CACHE_PER_ROLE | BLOCK_CACHE_PER_PAGE;
 * BLOCK_CACHE_PER_ROLE is used as a default when no caching pattern is
 * specified.
 *
 * The block cache is cleared in cache_clear_all(), and uses the same clearing
 * policy than page cache (node, comment, user, taxonomy added or updated...).
 * Blocks requiring more fine-grained clearing might consider disabling the
 * built-in block cache (BLOCK_NO_CACHE) and roll their own.
 *
 * Note that user 1 is excluded from block caching.
 */

/**
 * The block should not get cached. This setting should be used:
 * - for simple blocks (notably those that do not perform any db query),
 * where querying the db cache would be more expensive than directly generating
 * the content.
 * - for blocks that change too frequently.
 */
define('BLOCK_NO_CACHE', -1);

/**
41 42 43
 * The block can change depending on the roles the user viewing the page belongs to.
 * This is the default setting, used when the block does not specify anything.
 */
44 45 46
define('BLOCK_CACHE_PER_ROLE', 0x0001);

/**
47 48 49 50
 * The block can change depending on the user viewing the page.
 * This setting can be resource-consuming for sites with large number of users,
 * and thus should only be used when BLOCK_CACHE_PER_ROLE is not sufficient.
 */
51 52 53
define('BLOCK_CACHE_PER_USER', 0x0002);

/**
54 55
 * The block can change depending on the page being viewed.
 */
56 57 58 59 60 61 62
define('BLOCK_CACHE_PER_PAGE', 0x0004);

/**
 * The block is the same for every user on every page where it is visible.
 */
define('BLOCK_CACHE_GLOBAL', 0x0008);

Dries's avatar
 
Dries committed
63
/**
64
 * Implement hook_help().
Dries's avatar
 
Dries committed
65
 */
66 67
function block_help($path, $arg) {
  switch ($path) {
Dries's avatar
 
Dries committed
68
    case 'admin/help#block':
69
      $output = '<p>' . t('Blocks are boxes of content rendered into an area, or region, of a web page. The default theme Garland, for example, implements the regions "left sidebar", "right sidebar", "content", "header", and "footer", and a block may appear in any one of these areas. 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.', array('@blocks' => url('admin/build/block'))) . '</p>';
70
      $output .= '<p>' . t('Although blocks are usually generated automatically by modules (like the <em>User login</em> block, for example), administrators can also define custom blocks. Custom blocks have a title, description, and body. The body of the block can be as long as necessary, and can contain content supported by any available <a href="@text-format">text format</a>.', array('@text-format' => url('admin/settings/filter'))) . '</p>';
71 72 73 74 75 76 77 78 79
      $output .= '<p>' . t('When working with blocks, remember that:') . '</p>';
      $output .= '<ul><li>' . t('since not all themes implement the same regions, or display regions in the same way, blocks are positioned on a per-theme basis.') . '</li>';
      $output .= '<li>' . t('disabled blocks, or blocks not in a region, are never shown.') . '</li>';
      $output .= '<li>' . t('blocks can be configured to be visible only on certain pages.') . '</li>';
      $output .= '<li>' . t('blocks can be configured to be visible only when specific conditions are true.') . '</li>';
      $output .= '<li>' . t('blocks can be configured to be visible only for certain user roles.') . '</li>';
      $output .= '<li>' . t('when allowed by an administrator, specific blocks may be enabled or disabled on a per-user basis using the <em>My account</em> page.') . '</li>';
      $output .= '<li>' . t('some dynamic blocks, such as those generated by modules, will be displayed only on certain pages.') . '</li></ul>';
      $output .= '<p>' . t('For more information, see the online handbook entry for <a href="@block">Block module</a>.', array('@block' => 'http://drupal.org/handbook/modules/block/')) . '</p>';
80
      return $output;
81
    case 'admin/build/block':
82 83
      $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. To change the region or order of a block, grab a drag-and-drop handle under the <em>Block</em> column and drag the block to a new location in the list. (Grab a handle by clicking and holding the mouse while hovering over a handle icon.) 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.') . '</p>';
      $output .= '<p>' . t('Click the <em>configure</em> link next to each block to configure its specific title and visibility settings. Use the <a href="@add-block">add block page</a> to create a custom block.', array('@add-block' => url('admin/build/block/add'))) . '</p>';
84
      return $output;
85
    case 'admin/build/block/add':
86
      return '<p>' . t('Use this page to create a new custom block. New blocks are disabled by default, and must be moved to a region on the <a href="@blocks">blocks administration page</a> to be visible.', array('@blocks' => url('admin/build/block'))) . '</p>';
Dries's avatar
 
Dries committed
87
  }
Dries's avatar
 
Dries committed
88 89
}

90
/**
91
 * Implement hook_theme().
92 93 94
 */
function block_theme() {
  return array(
95 96 97
    'block' => array(
      'arguments' => array('block' => NULL),
      'template' => 'block',
98
    ),
99 100
    'block_admin_display_form' => array(
      'template' => 'block-admin-display-form',
101
      'file' => 'block.admin.inc',
102 103 104 105 106
      'arguments' => array('form' => NULL),
    ),
  );
}

Dries's avatar
 
Dries committed
107
/**
108
 * Implement hook_perm().
Dries's avatar
 
Dries committed
109
 */
Dries's avatar
 
Dries committed
110
function block_perm() {
111
  return array(
112 113 114 115
    'administer blocks' => array(
      'title' => t('Administer blocks'),
      'description' => t('Select which blocks are displayed, and arrange them on the page.'),
    ),
116
  );
Dries's avatar
 
Dries committed
117 118
}

Dries's avatar
 
Dries committed
119
/**
120
 * Implement hook_menu().
Dries's avatar
 
Dries committed
121
 */
122 123
function block_menu() {
  $items['admin/build/block'] = array(
124 125
    'title' => 'Blocks',
    'description' => 'Configure what block content appears in your site\'s sidebars and other regions.',
126
    'page callback' => 'block_admin_display',
127 128 129
    'access arguments' => array('administer blocks'),
  );
  $items['admin/build/block/list'] = array(
130
    'title' => 'List',
131 132 133
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
134
  $items['admin/build/block/list/js'] = array(
135
    'title' => 'JavaScript List Form',
136
    'page callback' => 'block_admin_display_js',
137
    'access arguments' => array('administer blocks'),
138 139
    'type' => MENU_CALLBACK,
  );
140
  $items['admin/build/block/configure'] = array(
141
    'title' => 'Configure block',
142
    'page callback' => 'drupal_get_form',
143
    'page arguments' => array('block_admin_configure'),
144
    'access arguments' => array('administer blocks'),
145 146 147
    'type' => MENU_CALLBACK,
  );
  $items['admin/build/block/delete'] = array(
148
    'title' => 'Delete block',
149
    'page callback' => 'drupal_get_form',
150
    'page arguments' => array('block_box_delete'),
151
    'access arguments' => array('administer blocks'),
152 153 154
    'type' => MENU_CALLBACK,
  );
  $items['admin/build/block/add'] = array(
155
    'title' => 'Add block',
156
    'page callback' => 'drupal_get_form',
157
    'page arguments' => array('block_add_block_form'),
158
    'access arguments' => array('administer blocks'),
159 160 161 162
    'type' => MENU_LOCAL_TASK,
  );
  $default = variable_get('theme_default', 'garland');
  foreach (list_themes() as $key => $theme) {
163
    $items['admin/build/block/list/' . $key] = array(
164 165 166 167 168 169 170
      'title' => check_plain($theme->info['name']),
      'page arguments' => array($key),
      'type' => $key == $default ? MENU_DEFAULT_LOCAL_TASK : MENU_LOCAL_TASK,
      'weight' => $key == $default ? -10 : 0,
      'access callback' => '_block_themes_access',
      'access arguments' => array($theme),
    );
Dries's avatar
 
Dries committed
171
  }
Dries's avatar
 
Dries committed
172
  return $items;
Dries's avatar
 
Dries committed
173 174
}

175
/**
176
 * Menu item access callback - only admin or enabled themes can be accessed.
177 178
 */
function _block_themes_access($theme) {
179 180
  $admin_theme = variable_get('admin_theme');
  return user_access('administer blocks') && ($theme->status || ($admin_theme && ($theme->name == $admin_theme)));
181 182
}

Dries's avatar
 
Dries committed
183
/**
184
 * Implement hook_block_list().
Dries's avatar
 
Dries committed
185
 */
186 187
function block_block_list() {
  $blocks = array();
188

189
  $result = db_query('SELECT bid, info FROM {box} ORDER BY info');
190
  foreach ($result as $block) {
191 192 193 194 195 196
    $blocks[$block->bid]['info'] = $block->info;
    // Not worth caching.
    $blocks[$block->bid]['cache'] = BLOCK_NO_CACHE;
  }
  return $blocks;
}
197

198
/**
199
 * Implement hook_block_configure().
200 201 202 203 204 205
 */
function block_block_configure($delta = 0, $edit = array()) {
  $box = array('format' => FILTER_FORMAT_DEFAULT);
  if ($delta) {
    $box = block_box_get($delta);
  }
206
  return block_box_form($box);
207 208
}

209
/**
210
 * Implement hook_block_save().
211 212 213 214 215 216
 */
function block_block_save($delta = 0, $edit = array()) {
  block_box_save($edit, $delta);
}

/**
217
 * Implement hook_block_view().
218 219 220 221
 *
 * Generates the administrator-defined blocks for display.
 */
function block_block_view($delta = 0, $edit = array()) {
222
  $block = db_query('SELECT body, format FROM {box} WHERE bid = :bid', array(':bid' => $delta))->fetchObject();
223 224 225 226
  $data['content'] = check_markup($block->body, $block->format, '', FALSE);
  return $data;
}

227
/**
228
 * Implement hook_page_alter().
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
 *
 * Render blocks into their regions.
 */
function block_page_alter($page) {
  global $theme;

  // The theme system might not yet be initialized. We need $theme.
  init_theme();

  // Populate all block regions
  $regions = system_region_list($theme);

  // Load all region content assigned via blocks.
  foreach (array_keys($regions) as $region) {
    // Prevent left and right regions from rendering blocks when 'show_blocks' == FALSE.
244
    if (!empty($page['#show_blocks']) || ($region != 'left' && $region != 'right')) {
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
      // Assign blocks to region.
      if ($blocks = block_get_blocks_by_region($region)) {
        $page[$region]['blocks'] = $blocks;
      }

      // Append region description if we are rendering the block admin page.
      $item = menu_get_item();
      if ($item['path'] == 'admin/build/block') {
        $description = '<div class="block-region">' . $regions[$region] . '</div>';
        $page[$region]['blocks']['block_description'] = array('#markup' => $description);
      }
    }
  }
}

/**
 * Get a renderable array of a region containing all enabled blocks.
 *
 * @param $region
 *   The requested region.
 */
function block_get_blocks_by_region($region) {
  $weight = 0;
  $build = array();
  if ($list = block_list($region)) {
    foreach ($list as $key => $block) {
      $build[$key] = array(
        '#theme' => 'block',
        '#block' => $block,
        '#weight' => ++$weight,
      );
    }
    $build['#sorted'] = TRUE;
  }
  return $build;
}

Dries's avatar
 
Dries committed
282
/**
283
 * Update the 'block' DB table with the blocks currently exported by modules.
Dries's avatar
 
Dries committed
284
 *
Dries's avatar
 
Dries committed
285
 * @return
286
 *   Blocks currently exported by modules.
Dries's avatar
 
Dries committed
287
 */
288
function _block_rehash() {
289 290
  global $theme_key;

291
  init_theme();
292

293
  $old_blocks = array();
294 295 296
  $result = db_query("SELECT * FROM {block} WHERE theme = :theme", array(':theme' => $theme_key));
  foreach ($result as $old_block) {
    $old_block = is_object($old_block) ? get_object_vars($old_block) : $old_block;
297
    $old_blocks[$old_block['module']][$old_block['delta']] = $old_block;
Dries's avatar
 
Dries committed
298 299
  }

300
  $blocks = array();
301 302
  // Valid region names for the theme.
  $regions = system_region_list($theme_key);
Dries's avatar
 
Dries committed
303

304 305
  foreach (module_implements('block_list') as $module) {
    $module_blocks = module_invoke($module, 'block_list');
Dries's avatar
 
Dries committed
306 307
    if ($module_blocks) {
      foreach ($module_blocks as $delta => $block) {
308 309 310 311 312
        if (empty($old_blocks[$module][$delta])) {
          // If it's a new block, add identifiers.
          $block['module'] = $module;
          $block['delta']  = $delta;
          $block['theme']  = $theme_key;
313 314 315 316 317 318
          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']  = '';
          }
319
          // Add defaults and save it into the database.
320
          drupal_write_record('block', $block);
321 322 323
          // Set region to none if not enabled.
          $block['region'] = $block['status'] ? $block['region'] : BLOCK_REGION_NONE;
          // Add to the list of blocks we return.
324
          $blocks[] = $block;
Dries's avatar
 
Dries committed
325 326
        }
        else {
327 328 329 330 331 332
          // If it's an existing block, database settings should overwrite
          // the code. But aside from 'info' everything that's definable in
          // code is stored in the database and we do not store 'info', so we
          // do not need to update the database here.
          // Add 'info' to this block.
          $old_blocks[$module][$delta]['info'] = $block['info'];
333 334 335 336 337 338 339 340 341
          // If the region name does not exist, disable the block and assign it to none.
          if (!empty($old_blocks[$module][$delta]['region']) && !isset($regions[$old_blocks[$module][$delta]['region']])) {
            drupal_set_message(t('The block %info was assigned to the invalid region %region and has been disabled.', array('%info' => $old_blocks[$module][$delta]['info'], '%region' => $old_blocks[$module][$delta]['region'])), 'warning');
            $old_blocks[$module][$delta]['status'] = 0;
            $old_blocks[$module][$delta]['region'] = BLOCK_REGION_NONE;
          }
          else {
            $old_blocks[$module][$delta]['region'] = $old_blocks[$module][$delta]['status'] ? $old_blocks[$module][$delta]['region'] : BLOCK_REGION_NONE;
          }
342
          // Add this block to the list of blocks we return.
343 344 345
          $blocks[] = $old_blocks[$module][$delta];
          // Remove this block from the list of blocks to be deleted.
          unset($old_blocks[$module][$delta]);
Dries's avatar
 
Dries committed
346 347 348 349 350
        }
      }
    }
  }

351 352 353
  // Remove blocks that are no longer defined by the code from the database.
  foreach ($old_blocks as $module => $old_module_blocks) {
    foreach ($old_module_blocks as $delta => $block) {
354 355 356 357 358
      db_delete('block')
        ->condition('module', $module)
        ->condition('delta', $delta)
        ->condition('theme', $theme_key)
        ->execute();
359
    }
360
  }
Dries's avatar
 
Dries committed
361 362
  return $blocks;
}
Dries's avatar
 
Dries committed
363

364
function block_box_get($bid) {
365
  return db_query("SELECT * FROM {box} WHERE bid = :bid", array(':bid' => $bid))->fetchAssoc();
Dries's avatar
 
Dries committed
366 367
}

368 369 370
/**
 * Define the custom block form.
 */
371
function block_box_form($edit = array()) {
372 373 374 375
  $edit += array(
    'info' => '',
    'body' => '',
  );
376 377 378
  $form['info'] = array(
    '#type' => 'textfield',
    '#title' => t('Block description'),
379
    '#default_value' => $edit['info'],
380
    '#maxlength' => 64,
381
    '#description' => t('A brief description of your block. Used on the <a href="@overview">block overview page</a>.', array('@overview' => url('admin/build/block'))),
382 383 384
    '#required' => TRUE,
    '#weight' => -19,
  );
385 386
  $form['body_field']['#weight'] = -17;
  $form['body_field']['body'] = array(
387 388
    '#type' => 'textarea',
    '#title' => t('Block body'),
389
    '#default_value' => $edit['body'],
390
    '#text_format' => isset($edit['format']) ? $edit['format'] : FILTER_FORMAT_DEFAULT,
391 392
    '#rows' => 15,
    '#description' => t('The content of the block as shown to the user.'),
393
    '#required' => TRUE,
394
    '#weight' => -17,
395
    '#access' => filter_access($edit['format']),
396
  );
397

398
  return $form;
399 400
}

401
function block_box_save($edit, $delta) {
402 403 404 405 406 407 408 409
  db_update('box')
    ->fields(array(
      'body' => $edit['body'],
      'info' => $edit['info'],
      'format' => $edit['body_format'],
    ))
    ->condition('bid', $delta)
    ->execute();
410
  return TRUE;
411 412
}

Dries's avatar
 
Dries committed
413
/**
414
 * Implement hook_user_form().
Dries's avatar
 
Dries committed
415
 */
416 417 418
function block_user_form(&$edit, &$account, $category = NULL) {
  if ($category == 'account') {
    $rids = array_keys($account->roles);
419
    $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));
420
    $form['block'] = array('#type' => 'fieldset', '#title' => t('Block configuration'), '#weight' => 3, '#collapsible' => TRUE, '#tree' => TRUE);
421
    foreach ($result as $block) {
422
      $data = module_invoke($block->module, 'block_list');
423 424
      if ($data[$block->delta]['info']) {
        $return = TRUE;
425 426 427 428 429
        $form['block'][$block->module][$block->delta] = array(
          '#type' => 'checkbox',
          '#title' => check_plain($data[$block->delta]['info']),
          '#default_value' => isset($account->block[$block->module][$block->delta]) ? $account->block[$block->module][$block->delta] : ($block->custom == 1),
        );
430
      }
431
    }
Dries's avatar
 
Dries committed
432

433 434 435 436 437 438 439
    if (!empty($return)) {
      return $form;
    }
  }
}

/**
440
 * Implement hook_user_validate().
441 442 443 444
 */
function block_user_validate(&$edit, &$account, $category = NULL) {
  if (empty($edit['block'])) {
    $edit['block'] = array();
445
  }
446
  return $edit;
447 448
}

449
/**
450
 * Implement hook_form_FORM_ID_alter().
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
 */
function block_form_system_performance_settings_alter(&$form, &$form_state) {

  // Add the block cache fieldset on the performance settings page.
  $form['block_cache'] = array(
    '#type' => 'fieldset',
    '#title' => t('Block cache'),
    '#description' => t('Enabling the block cache can offer a performance increase for all users by preventing blocks from being reconstructed on each page load. If the page cache is also enabled, performance increases from enabling the block cache will mainly benefit authenticated users.'),
    '#weight' => 0,
  );

  $form['block_cache']['block_cache'] = array(
    '#type' => 'radios',
    '#title' => t('Block cache'),
    '#default_value' => variable_get('block_cache', CACHE_DISABLED),
    '#options' => array(CACHE_DISABLED => t('Disabled'), CACHE_NORMAL => t('Enabled (recommended)')),
    '#disabled' => count(module_implements('node_grants')),
    '#description' => t('Note that block caching is inactive when modules defining content access restrictions are enabled.'),
  );
470

471
  // Check if the "Who's online" block is enabled.
472
  $online_block_enabled = db_query_range("SELECT 1 FROM {block} b WHERE module = 'user' AND delta = 'online' AND status = 1", array(), 0, 1)->fetchField();
473

474 475 476 477 478
  // If the "Who's online" block is enabled, append some descriptive text to
  // the end of the form description.
  if ($online_block_enabled) {
    $form['page_cache']['cache']['#description'] .=  '<p>' . t('When caching is enabled, anonymous user sessions are only saved to the database when needed, so the "Who\'s online" block does not display the number of anonymous users.') . '</p>';
  }
479

480 481
}

482
/**
483
 * Implement hook_form_FORM_ID_alter().
484 485
 */
function block_form_system_themes_form_alter(&$form, &$form_state) {
486 487 488 489
  // This function needs to fire before the theme changes are recorded in the
  // database, otherwise it will populate the default list of blocks from the
  // new theme, which is empty.
  array_unshift($form['#submit'], 'block_system_themes_form_submit');
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
}

/**
 * Initialize blocks for enabled themes.
 */
function block_system_themes_form_submit(&$form, &$form_state) {
  if ($form_state['values']['op'] == t('Save configuration')) {
    if (is_array($form_state['values']['status'])) {
      foreach ($form_state['values']['status'] as $key => $choice) {
        if ($choice || $form_state['values']['theme_default'] == $key) {
          block_initialize_theme_blocks($key);
        }
      }
    }
    if ($form_state['values']['admin_theme'] && $form_state['values']['admin_theme'] != variable_get('admin_theme', 0)) {
      // If we're changing themes, make sure the theme has its blocks initialized.
506 507
      $has_blocks = (bool) db_query_range('SELECT 1 FROM {block} WHERE theme = :theme', array(':theme' => $form_state['values']['admin_theme']), 0, 1)->fetchField();
      if (!$has_blocks) {
508 509 510 511 512 513 514 515
        block_initialize_theme_blocks($form_state['values']['admin_theme']);
      }
    }
  }
}

/**
 * Assign an initial, default set of blocks for a theme.
516
 *
517 518 519 520
 * 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.
521
 *
522 523 524 525 526
 * @param $theme
 *   The name of a theme.
 */
function block_initialize_theme_blocks($theme) {
  // Initialize theme's blocks if none already registered.
527 528
  $has_blocks = (bool) db_query_range('SELECT 1 FROM {block} WHERE theme = :theme', array(':theme' => $theme), 0, 1)->fetchField();
  if (!$has_blocks) {
529 530
    $default_theme = variable_get('theme_default', 'garland');
    $regions = system_region_list($theme);
531 532 533
    $result = db_query("SELECT * FROM {block} WHERE theme = :theme", array(':theme' => $default_theme), array('fetch' => PDO::FETCH_ASSOC));
    $query = db_insert('block')->fields(array('module', 'delta', 'theme', 'status', 'weight', 'region', 'visibility', 'pages', 'custom', 'cache'));
    foreach ($result as $block) {
534 535 536 537
      // If the region isn't supported by the theme, assign the block to the theme's default region.
      if (!array_key_exists($block['region'], $regions)) {
        $block['region'] = system_default_region($theme);
      }
538 539
      $block['theme'] = $theme;
      $query->values($block);
540
    }
541
    $query->execute();
542 543 544
  }
}

545 546 547 548 549 550 551 552 553 554 555 556 557
/**
 * Return all blocks in the specified region for the current user.
 *
 * @param $region
 *   The name of a region.
 *
 * @return
 *   An array of block objects, indexed with <i>module</i>_<i>delta</i>.
 *   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.
 *
 * @todo
558 559
 *   Now that the blocks table has a primary key, we should use that as the
 *   array key instead of <i>module</i>_<i>delta</i>.
560 561
 */
function block_list($region) {
562
  $blocks = &drupal_static(__FUNCTION__, array());
563

564
  if (empty($blocks)) {
565 566 567
    $blocks = _block_load_blocks();
  }

568
  // Create an empty array if there were no entries.
569 570 571 572 573 574 575 576 577 578
  if (!isset($blocks[$region])) {
    $blocks[$region] = array();
  }

  $blocks[$region] = _block_render_blocks($blocks[$region]);

  return $blocks[$region];
}

/**
579
 * Load blocks information from the database.
580 581 582 583 584 585
 */
function _block_load_blocks() {
  global $user, $theme_key;

  $blocks = array();
  $rids = array_keys($user->roles);
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
  $query = db_select('block', 'b');
  $query->leftJoin('block_role', 'r', 'b.module = r.module AND b.delta = r.delta');
  $result = $query
    ->distinct()
    ->fields('b')
    ->condition('b.theme', $theme_key)
    ->condition('b.status', 1)
    ->condition(db_or()
      ->condition('r.rid', $rids, 'IN')
      ->isNull('r.rid')
    )
    ->orderBy('b.region')
    ->orderBy('b.weight')
    ->orderBy('b.module')
    ->addTag('block_load')
    ->execute();
  foreach ($result as $block) {
603 604 605
    if (!isset($blocks[$block->region])) {
      $blocks[$block->region] = array();
    }
606
    // Use the user's block visibility setting, if necessary.
607 608 609
    if ($block->custom != 0) {
      if ($user->uid && isset($user->block[$block->module][$block->delta])) {
        $enabled = $user->block[$block->module][$block->delta];
610 611
      }
      else {
612
        $enabled = ($block->custom == 1);
613
      }
614 615 616 617
    }
    else {
      $enabled = TRUE;
    }
618

619
    // Match path if necessary.
620 621 622 623 624 625 626
    if ($block->pages) {
      if ($block->visibility < 2) {
        $path = drupal_get_path_alias($_GET['q']);
        // Compare with the internal and path alias (if any).
        $page_match = drupal_match_path($path, $block->pages);
        if ($path != $_GET['q']) {
          $page_match = $page_match || drupal_match_path($_GET['q'], $block->pages);
627
        }
628 629 630 631
        // When $block->visibility has a value of 0, the block is displayed on
        // all pages except those listed in $block->pages. When set to 1, it
        // is displayed only on those pages listed in $block->pages.
        $page_match = !($block->visibility xor $page_match);
632
      }
633 634 635
      elseif (module_exists('php')) {
        $page_match = php_eval($block->pages);
      }
636
      else {
637
        $page_match = FALSE;
638
      }
639 640 641 642 643 644 645 646
    }
    else {
      $page_match = TRUE;
    }
    $block->enabled = $enabled;
    $block->page_match = $page_match;
    $blocks[$block->region]["{$block->module}_{$block->delta}"] = $block;
  }
647

648 649
  return $blocks;
}
650

651 652 653 654
/**
 * Render the content and subject for a set of blocks.
 *
 * @param $region_blocks
655
 *   An array of block objects such as returned for one region by _block_load_blocks().
656 657
 *
 * @return
658
 *   An array of visible blocks with subject and content rendered.
659 660 661 662 663 664 665 666
 */
function _block_render_blocks($region_blocks) {
  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.
      unset($region_blocks[$key]);
      if ($block->enabled && $block->page_match) {
667 668
        // Try fetching the block from cache. Block caching is not compatible with
        // node_access modules. We also preserve the submission of forms in blocks,
669 670
        // by fetching from cache only if the request method is 'GET' (or 'HEAD').
        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'))) {
671 672 673
          $array = $cache->data;
        }
        else {
674
          $array = module_invoke($block->module, 'block_view', $block->delta);
675 676
          if (isset($cid)) {
            cache_set($cid, $array, 'cache_block', CACHE_TEMPORARY);
677
          }
678
        }
679

680 681 682
        if (isset($array) && is_array($array)) {
          foreach ($array as $k => $v) {
            $block->$k = $v;
683
          }
Dries's avatar
 
Dries committed
684
        }
685
        if (isset($block->content) && $block->content) {
686 687 688 689 690
          // 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);
          }
691 692 693
          if (!isset($block->subject)) {
            $block->subject = '';
          }
694
          $region_blocks["{$block->module}_{$block->delta}"] = $block;
695 696 697 698
        }
      }
    }
  }
699
  return $region_blocks;
700
}
701 702 703 704 705 706 707 708 709 710

/**
 * 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.
 *
711
 * Theme and language contexts are automatically differentiated.
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
 *
 * @param $block
 * @return
 *   The string used as cache_id for the block.
 */
function _block_get_cache_id($block) {
  global $theme, $base_root, $user;

  // 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.
  if (variable_get('block_cache', 0) && $block->cache != BLOCK_NO_CACHE && $user->uid != 1) {
    $cid_parts = array();

    // Start with common sub-patterns: block identification, theme, language.
    $cid_parts[] = $block->module;
    $cid_parts[] = $block->delta;
    $cid_parts[] = $theme;
    if (module_exists('locale')) {
      global $language;
      $cid_parts[] = $language->language;
    }

    // 'PER_ROLE' and 'PER_USER' are mutually exclusive. 'PER_USER' can be a
    // resource drag for sites with many users, so when a module is being
    // equivocal, we favor the less expensive 'PER_ROLE' pattern.
    if ($block->cache & BLOCK_CACHE_PER_ROLE) {
740
      $cid_parts[] = 'r.' . implode(',', array_keys($user->roles));
741 742 743 744 745 746 747 748 749 750 751
    }
    elseif ($block->cache & BLOCK_CACHE_PER_USER) {
      $cid_parts[] = "u.$user->uid";
    }

    if ($block->cache & BLOCK_CACHE_PER_PAGE) {
      $cid_parts[] = $base_root . request_uri();
    }

    return implode(':', $cid_parts);
  }
752
}
753 754

/**
755
 * Implement hook_flush_caches().
756 757 758 759
 */
function block_flush_caches() {
  return array('cache_block');
}
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778

/**
 * Process variables for block.tpl.php
 *
 * Prepare the values passed to the theme_block function to be passed
 * into a pluggable template engine. Uses block properties to generate a
 * series of template file suggestions. If none are found, the default
 * block.tpl.php is used.
 *
 * Most themes utilize their own copy of block.tpl.php. The default is located
 * inside "modules/block/block.tpl.php". Look in there for the full list of
 * variables.
 *
 * The $variables array contains the following arguments:
 * - $block
 *
 * @see block.tpl.php
 */
function template_preprocess_block(&$variables) {
779
  $block_counter = &drupal_static(__FUNCTION__, array());
780 781 782 783 784 785 786 787 788
  $variables['block'] = $variables['block']['#block'];
  // All blocks get an independent counter for each region.
  if (!isset($block_counter[$variables['block']->region])) {
    $block_counter[$variables['block']->region] = 1;
  }
  // Same with zebra striping.
  $variables['block_zebra'] = ($block_counter[$variables['block']->region] % 2) ? 'odd' : 'even';
  $variables['block_id'] = $block_counter[$variables['block']->region]++;

789 790 791 792 793
  if (is_array($variables['block']->content)) {
    // Render the block contents if it is not already rendered.
    $variables['block']->content = drupal_render($variables['block']->content);
  }

794 795
  $variables['classes_array'][] = 'block-' . $variables['block']->module;

796 797 798
  $variables['template_files'][] = 'block-' . $variables['block']->region;
  $variables['template_files'][] = 'block-' . $variables['block']->module;
  $variables['template_files'][] = 'block-' . $variables['block']->module . '-' . $variables['block']->delta;
799
}