block.module 31.6 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
/**
 * @file
6
 * Controls the visual building blocks a page is constructed with.
Dries's avatar
 
Dries committed
7 8
 */

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);

Dries's avatar
 
Dries committed
14
/**
15
 * Implement hook_help().
Dries's avatar
 
Dries committed
16
 */
17 18
function block_help($path, $arg) {
  switch ($path) {
Dries's avatar
 
Dries committed
19
    case 'admin/help#block':
20
      $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/structure/block'))) . '</p>';
21
      $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/config/content/formats'))) . '</p>';
22 23 24 25 26 27 28 29 30
      $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>';
31
      return $output;
32
    case 'admin/structure/block':
33
      $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.') . '</p>';
34
      $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/structure/block/add'))) . '</p>';
35
      return $output;
36 37
    case 'admin/structure/block/add':
      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/structure/block'))) . '</p>';
Dries's avatar
 
Dries committed
38
  }
Dries's avatar
 
Dries committed
39 40
}

41
/**
42
 * Implement hook_theme().
43 44 45
 */
function block_theme() {
  return array(
46
    'block' => array(
47
      'arguments' => array('elements' => NULL),
48
      'template' => 'block',
49
    ),
50 51
    'block_admin_display_form' => array(
      'template' => 'block-admin-display-form',
52
      'file' => 'block.admin.inc',
53 54 55 56 57
      'arguments' => array('form' => NULL),
    ),
  );
}

Dries's avatar
 
Dries committed
58
/**
59
 * Implement hook_permission().
Dries's avatar
 
Dries committed
60
 */
61
function block_permission() {
62
  return array(
63 64 65 66
    'administer blocks' => array(
      'title' => t('Administer blocks'),
      'description' => t('Select which blocks are displayed, and arrange them on the page.'),
    ),
67
  );
Dries's avatar
 
Dries committed
68 69
}

Dries's avatar
 
Dries committed
70
/**
71
 * Implement hook_menu().
Dries's avatar
 
Dries committed
72
 */
73
function block_menu() {
74
  $items['admin/structure/block'] = array(
75 76
    'title' => 'Blocks',
    'description' => 'Configure what block content appears in your site\'s sidebars and other regions.',
77
    'page callback' => 'block_admin_display',
78
    'access arguments' => array('administer blocks'),
79
    'theme callback' => '_block_custom_theme',
80
    'file' => 'block.admin.inc',
81
  );
82
  $items['admin/structure/block/list'] = array(
83
    'title' => 'List',
84 85 86
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
87
  $items['admin/structure/block/list/js'] = array(
88
    'title' => 'JavaScript List Form',
89
    'page callback' => 'block_admin_display_js',
90
    'access arguments' => array('administer blocks'),
91
    'type' => MENU_CALLBACK,
92
    'file' => 'block.admin.inc',
93
  );
94
  $items['admin/structure/block/configure'] = array(
95
    'title' => 'Configure block',
96
    'page callback' => 'drupal_get_form',
97
    'page arguments' => array('block_admin_configure'),
98
    'access arguments' => array('administer blocks'),
99
    'type' => MENU_CALLBACK,
100
    'file' => 'block.admin.inc',
101
  );
102
  $items['admin/structure/block/delete'] = array(
103
    'title' => 'Delete block',
104
    'page callback' => 'drupal_get_form',
105
    'page arguments' => array('block_custom_block_delete'),
106
    'access arguments' => array('administer blocks'),
107
    'type' => MENU_CALLBACK,
108
    'file' => 'block.admin.inc',
109
  );
110
  $items['admin/structure/block/add'] = array(
111
    'title' => 'Add block',
112
    'page callback' => 'drupal_get_form',
113
    'page arguments' => array('block_add_block_form'),
114
    'access arguments' => array('administer blocks'),
115
    'type' => MENU_LOCAL_ACTION,
116
    'file' => 'block.admin.inc',
117 118 119
  );
  $default = variable_get('theme_default', 'garland');
  foreach (list_themes() as $key => $theme) {
120
    $items['admin/structure/block/list/' . $key] = array(
121 122 123 124 125 126
      '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),
127 128
      'theme callback' => '_block_custom_theme',
      'theme arguments' => array($key),
129
      'file' => 'block.admin.inc',
130
    );
Dries's avatar
 
Dries committed
131
  }
Dries's avatar
 
Dries committed
132
  return $items;
Dries's avatar
 
Dries committed
133 134
}

135
/**
136
 * Menu item access callback - only admin or enabled themes can be accessed.
137 138
 */
function _block_themes_access($theme) {
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
  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.
 * @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;
156 157
}

Dries's avatar
 
Dries committed
158
/**
159
 * Implement hook_block_info().
Dries's avatar
 
Dries committed
160
 */
161
function block_block_info() {
162
  $blocks = array();
163

164
  $result = db_query('SELECT bid, info FROM {block_custom} ORDER BY info');
165
  foreach ($result as $block) {
166 167
    $blocks[$block->bid]['info'] = $block->info;
    // Not worth caching.
168
    $blocks[$block->bid]['cache'] = DRUPAL_NO_CACHE;
169 170 171
  }
  return $blocks;
}
172

173
/**
174
 * Implement hook_block_configure().
175
 */
176
function block_block_configure($delta = 0) {
177
  $custom_block = array('format' => filter_default_format());
178
  if ($delta) {
179
    $custom_block = block_custom_block_get($delta);
180
  }
181
  return block_custom_block_form($custom_block);
182 183
}

184
/**
185
 * Implement hook_block_save().
186 187
 */
function block_block_save($delta = 0, $edit = array()) {
188
  block_custom_block_save($edit, $delta);
189 190 191
}

/**
192
 * Implement hook_block_view().
193 194 195 196
 *
 * Generates the administrator-defined blocks for display.
 */
function block_block_view($delta = 0, $edit = array()) {
197
  $block = db_query('SELECT body, format FROM {block_custom} WHERE bid = :bid', array(':bid' => $delta))->fetchObject();
198
  $data['content'] = check_markup($block->body, $block->format);
199 200 201
  return $data;
}

202
/**
203
 * Implement hook_page_alter().
204 205 206
 *
 * Render blocks into their regions.
 */
207
function block_page_build(&$page) {
208 209 210
  global $theme;

  // The theme system might not yet be initialized. We need $theme.
211
  drupal_theme_initialize();
212 213

  // Populate all block regions
214
  $all_regions = system_region_list($theme);
215 216

  // Load all region content assigned via blocks.
217
  foreach (array_keys($all_regions) as $region) {
218
    $page[$region] = array();
219 220 221 222
    // Assign blocks to region.
    if ($blocks = block_get_blocks_by_region($region)) {
      $page[$region] = $blocks;
    }
223

224 225 226 227 228 229 230 231 232 233
    // Append region description if we are rendering the block admin page.
    $item = menu_get_item();
    if ($item['path'] == 'admin/structure/block') {
      $visible_regions = system_region_list($theme, REGIONS_VISIBLE);
      if (isset($visible_regions[$region])) {
        $description = '<div class="block-region">' . $all_regions[$region] . '</div>';
        $page[$region]['block_description'] = array(
          '#markup' => $description,
          '#weight' => 15,
        );
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
      }
    }
  }
}

/**
 * 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) {
250 251 252
      $build[$key] = $block->content;
      unset($block->content);
      $build[$key] += array(
253 254 255
        '#block' => $block,
        '#weight' => ++$weight,
      );
256
      $build[$key]['#theme_wrappers'][] ='block';
257 258 259 260 261 262
    }
    $build['#sorted'] = TRUE;
  }
  return $build;
}

Dries's avatar
 
Dries committed
263
/**
264
 * Update the 'block' DB table with the blocks currently exported by modules.
Dries's avatar
 
Dries committed
265
 *
Dries's avatar
 
Dries committed
266
 * @return
267
 *   Blocks currently exported by modules.
Dries's avatar
 
Dries committed
268
 */
269
function _block_rehash() {
270 271
  global $theme_key;

272
  drupal_theme_initialize();
273

274
  $old_blocks = array();
275 276 277
  $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;
278
    $old_blocks[$old_block['module']][$old_block['delta']] = $old_block;
Dries's avatar
 
Dries committed
279 280
  }

281
  $blocks = array();
282 283
  // Valid region names for the theme.
  $regions = system_region_list($theme_key);
Dries's avatar
 
Dries committed
284

285 286
  foreach (module_implements('block_info') as $module) {
    $module_blocks = module_invoke($module, 'block_info');
Dries's avatar
 
Dries committed
287 288
    if ($module_blocks) {
      foreach ($module_blocks as $delta => $block) {
289 290 291 292 293
        if (empty($old_blocks[$module][$delta])) {
          // If it's a new block, add identifiers.
          $block['module'] = $module;
          $block['delta']  = $delta;
          $block['theme']  = $theme_key;
294 295 296 297 298 299
          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']  = '';
          }
300
          // Add defaults and save it into the database.
301
          drupal_write_record('block', $block);
302 303 304
          // Set region to none if not enabled.
          $block['region'] = $block['status'] ? $block['region'] : BLOCK_REGION_NONE;
          // Add to the list of blocks we return.
305
          $blocks[] = $block;
Dries's avatar
 
Dries committed
306 307
        }
        else {
308 309 310 311 312 313
          // 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'];
314 315 316 317 318 319 320 321 322
          // 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;
          }
323
          // Add this block to the list of blocks we return.
324 325 326
          $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
327 328 329 330 331
        }
      }
    }
  }

332 333 334
  // 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) {
335 336 337 338 339
      db_delete('block')
        ->condition('module', $module)
        ->condition('delta', $delta)
        ->condition('theme', $theme_key)
        ->execute();
340
    }
341
  }
Dries's avatar
 
Dries committed
342 343
  return $blocks;
}
Dries's avatar
 
Dries committed
344

345 346 347 348 349 350 351 352 353 354 355 356 357
/**
 * Returns information from database about a user-created (custom) block.
 *
 * @param $bid
 *   ID of the block to get information for.
 * @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.
 */
358 359
function block_custom_block_get($bid) {
  return db_query("SELECT * FROM {block_custom} WHERE bid = :bid", array(':bid' => $bid))->fetchAssoc();
Dries's avatar
 
Dries committed
360 361
}

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

392
  return $form;
393 394
}

395 396 397 398 399 400 401 402 403 404 405 406 407
/**
 * Saves a user-created block in the database.
 *
 * @param $edit
 *   Associative array of fields to save. Array keys:
 *   - info: Block description.
 *   - body: Block contents.
 *   - format: Filter ID of the filter format for the body.
 * @param $delta
 *   Block ID of the block to save.
 * @return
 *   Always returns TRUE.
 */
408 409
function block_custom_block_save($edit, $delta) {
  db_update('block_custom')
410 411 412 413 414 415 416
    ->fields(array(
      'body' => $edit['body'],
      'info' => $edit['info'],
      'format' => $edit['body_format'],
    ))
    ->condition('bid', $delta)
    ->execute();
417
  return TRUE;
418 419
}

Dries's avatar
 
Dries committed
420
/**
421
 * Implement hook_form_FORM_ID_alter().
Dries's avatar
 
Dries committed
422
 */
423 424 425
function block_form_user_profile_form_alter(&$form, &$form_state) {
  if ($form['#user_category'] == 'account') {
    $account = $form['#user'];
426
    $rids = array_keys($account->roles);
427
    $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));
428 429

    $blocks = array();
430
    foreach ($result as $block) {
431
      $data = module_invoke($block->module, 'block_info');
432
      if ($data[$block->delta]['info']) {
433
        $blocks[$block->module][$block->delta] = array(
434 435 436 437
          '#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),
        );
438
      }
439
    }
440 441 442 443 444 445 446 447 448 449 450
    // 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;
451 452 453 454
    }
  }
}

455
/**
456
 * Implement hook_form_FORM_ID_alter().
457 458
 */
function block_form_system_themes_form_alter(&$form, &$form_state) {
459 460 461 462
  // 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');
463 464 465 466 467 468 469 470 471 472
}

/**
 * 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) {
473
          block_theme_initialize($key);
474 475 476
        }
      }
    }
477
    if ($form_state['values']['admin_theme'] && $form_state['values']['admin_theme'] !== variable_get('admin_theme', 0)) {
478
      // If we're changing themes, make sure the theme has its blocks initialized.
479
      $has_blocks = (bool) db_query_range('SELECT 1 FROM {block} WHERE theme = :theme', 0, 1, array(':theme' => $form_state['values']['admin_theme']))->fetchField();
480
      if (!$has_blocks) {
481
        block_theme_initialize($form_state['values']['admin_theme']);
482 483 484 485 486 487 488
      }
    }
  }
}

/**
 * Assign an initial, default set of blocks for a theme.
489
 *
490 491 492 493
 * 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.
494
 *
495 496 497
 * @param $theme
 *   The name of a theme.
 */
498
function block_theme_initialize($theme) {
499
  // Initialize theme's blocks if none already registered.
500
  $has_blocks = (bool) db_query_range('SELECT 1 FROM {block} WHERE theme = :theme', 0, 1, array(':theme' => $theme))->fetchField();
501
  if (!$has_blocks) {
502 503
    $default_theme = variable_get('theme_default', 'garland');
    $regions = system_region_list($theme);
504 505
    $result = db_query("SELECT * FROM {block} WHERE theme = :theme", array(':theme' => $default_theme), array('fetch' => PDO::FETCH_ASSOC));
    foreach ($result as $block) {
506 507 508 509
      // 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);
      }
510
      $block['theme'] = $theme;
511 512
      unset($block['bid']);
      drupal_write_record('block', $block);
513 514 515 516
    }
  }
}

517 518 519 520 521 522 523 524 525 526 527 528 529
/**
 * 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
530 531
 *   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>.
532 533
 */
function block_list($region) {
534
  $blocks = &drupal_static(__FUNCTION__, array());
535

536
  if (empty($blocks)) {
537 538 539
    $blocks = _block_load_blocks();
  }

540
  // Create an empty array if there were no entries.
541 542 543 544 545 546 547 548 549 550
  if (!isset($blocks[$region])) {
    $blocks[$region] = array();
  }

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

  return $blocks[$region];
}

/**
551
 * Load blocks information from the database.
552 553
 */
function _block_load_blocks() {
554
  global $theme_key;
555

556 557 558 559 560 561 562 563 564 565
  $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')
    ->execute();
566

567
  $block_info = $result->fetchAllAssoc('bid');
568
  // Allow modules to modify the block list.
569
  drupal_alter('block_info', $block_info);
570 571

  $blocks = array();
572
  foreach ($block_info as $block) {
573 574 575 576 577 578
    $blocks[$block->region]["{$block->module}_{$block->delta}"] = $block;
  }
  return $blocks;
}

/**
579
 * Implement hook_block_info_alter().
580
 *
581 582
 * Check the page, user role, content type and user specific visibilty settings.
 * Remove the block if the visibility conditions are not met.
583
 */
584
function block_block_info_alter(&$blocks) {
585 586 587 588 589 590 591 592 593
  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;
  }

594 595 596 597 598 599 600
  // Build an array of node types for each block.
  $block_node_types = array();
  $result = db_query('SELECT module, delta, type FROM {block_node_type}');
  foreach ($result as $record) {
    $block_node_types[$record->module][$record->delta][] = $record->type;
  }

601 602 603 604
  foreach ($blocks as $key => $block) {
    if ($block->theme != $theme_key || $block->status != 1) {
      // This block was added by a contrib module, leave it in the list.
      continue;
605
    }
606 607 608 609

    // 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.
610
    if (isset($block_roles[$block->module][$block->delta]) && !array_intersect($block_roles[$block->module][$block->delta], array_keys($user->roles))) {
611 612 613
      // No match.
      unset($blocks[$key]);
      continue;
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
    }

    // If a block has no node types associated, it is displayed for every type.
    // For blocks with node types associated, if the node type does not match
    // the settings from this block, remove it from the block list.
    if (isset($block_node_types[$block->module][$block->delta])) {
      $node = menu_get_object();
      if (!empty($node)) {
        // This is a node or node edit page.
        if (!in_array($node->type, $block_node_types[$block->module][$block->delta])) {
          // This block should not be displayed for this node type.
          unset($blocks[$key]);
          continue;
        }
      }
      elseif (arg(0) == 'node' && arg(1) == 'add' && in_array(arg(2), array_keys(node_type_get_types()))) {
        // This is a node creation page
        if (!in_array(arg(2), $block_node_types[$block->module][$block->delta])) {
          // This block should not be displayed for this node type.
          unset($blocks[$key]);
          continue;
        }
      }
      else {
        // This is not a node page, remove the block.
        unset($blocks[$key]);
        continue;
      }
    }
643

644
    // Use the user's block visibility setting, if necessary.
645 646 647
    if ($block->custom != 0) {
      if ($user->uid && isset($user->block[$block->module][$block->delta])) {
        $enabled = $user->block[$block->module][$block->delta];
648 649
      }
      else {
650
        $enabled = ($block->custom == 1);
651
      }
652 653 654 655
    }
    else {
      $enabled = TRUE;
    }
656 657 658 659
    if (!$enabled) {
      unset($blocks[$key]);
      continue;
    }
660

661
    // Match path if necessary.
662 663 664 665 666 667 668
    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);
669
        }
670 671 672 673
        // 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);
674
      }
675 676 677
      elseif (module_exists('php')) {
        $page_match = php_eval($block->pages);
      }
678
      else {
679
        $page_match = FALSE;
680
      }
681 682 683 684
    }
    else {
      $page_match = TRUE;
    }
685 686 687
    if (!$page_match) {
      unset($blocks[$key]);
    }
688 689
  }
}
690

691 692 693 694
/**
 * Render the content and subject for a set of blocks.
 *
 * @param $region_blocks
695
 *   An array of block objects such as returned for one region by _block_load_blocks().
696 697
 *
 * @return
698
 *   An array of visible blocks as expected by drupal_render().
699 700 701 702 703
 */
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)) {
704 705
      // Erase the block from the static array - we'll put it back if it has
      // content.
706
      unset($region_blocks[$key]);
707 708 709 710 711 712 713 714 715 716 717
      // Try fetching the block from cache. Block caching is not compatible
      // with node_access modules. We also preserve the submission of forms in
      // blocks, 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'))) {
        $array = $cache->data;
      }
      else {
        $array = module_invoke($block->module, 'block_view', $block->delta);
        if (isset($cid)) {
          cache_set($cid, $array, 'cache_block', CACHE_TEMPORARY);
718
        }
719
      }
720

721 722 723
      if (isset($array) && is_array($array)) {
        foreach ($array as $k => $v) {
          $block->$k = $v;
Dries's avatar
 
Dries committed
724
        }
725 726
      }
      if (isset($block->content) && $block->content) {
727
        // Normalize to the drupal_render() structure.
728 729 730
        if (is_string($block->content)) {
          $block->content = array('#markup' => $block->content);
        }
731 732 733 734 735 736 737 738
        // 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 = '';
739
        }
740
        $region_blocks["{$block->module}_{$block->delta}"] = $block;
741 742 743
      }
    }
  }
744
  return $region_blocks;
745
}
746 747 748 749 750 751 752 753 754 755

/**
 * 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.
 *
756
 * Theme and language contexts are automatically differentiated.
757 758 759 760 761 762
 *
 * @param $block
 * @return
 *   The string used as cache_id for the block.
 */
function _block_get_cache_id($block) {
763 764
  global $user;
  
765 766 767 768
  // 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.
769
  if (variable_get('block_cache', 0) && !in_array($block->cache, array(DRUPAL_NO_CACHE, DRUPAL_CACHE_CUSTOM)) && $user->uid != 1) {
770 771 772
    // Start with common sub-patterns: block identification, theme, language.
    $cid_parts[] = $block->module;
    $cid_parts[] = $block->delta;
773
    $cid_parts += drupal_render_cid_parts($block->cache);
774 775 776

    return implode(':', $cid_parts);
  }
777
}
778 779

/**
780
 * Implement hook_flush_caches().
781 782 783 784
 */
function block_flush_caches() {
  return array('cache_block');
}
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803

/**
 * 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) {
804
  $block_counter = &drupal_static(__FUNCTION__, array());
805
  $variables['block'] = $variables['elements']['#block'];
806 807 808 809 810 811 812 813
  // 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]++;

814 815
  // Create the $content variable that templates expect.
  $variables['content'] = $variables['elements']['#children'];
816

817
  $variables['classes_array'][] = drupal_html_class('block-' . $variables['block']->module);
818

819 820 821
  $variables['template_files'][] = 'block-' . $variables['block']->region;
  $variables['template_files'][] = 'block-' . $variables['block']->module;
  $variables['template_files'][] = 'block-' . $variables['block']->module . '-' . $variables['block']->delta;
822
}
823

824 825 826 827 828 829 830 831 832 833 834
/**
 * Implement hook_user_role_delete().
 *
 * Remove deleted role from blocks that use it. 
 */
function block_user_role_delete($role) {
  db_delete('block_role')
    ->condition('rid', $role->rid)
    ->execute();
}

835 836 837
/**
 * Implement hook_filter_format_delete().
 */
838
function block_filter_format_delete($format, $fallback) {
839
  db_update('block_custom')
840
    ->fields(array('format' => $fallback->format))
841 842 843 844
    ->condition('format', $format->format)
    ->execute();
}

845 846 847 848 849 850 851 852 853 854 855 856 857 858
/**
 * Implement hook_menu_delete().
 */
function block_menu_delete($menu) {
  db_delete('block')
    ->condition('module', 'menu')
    ->condition('delta', $menu['menu_name'])
    ->execute();
  db_delete('block_role')
    ->condition('module', 'menu')
    ->condition('delta', $menu['menu_name'])
    ->execute();
}

859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
/**
 * Implement hook_form_FORM_ID_alter().
 */
function block_form_system_performance_settings_alter(&$form, &$form_state) {
  $disabled = count(module_implements('node_grants'));
  $form['caching']['block_cache'] = array(
    '#type' => 'checkbox',
    '#title' => t('Cache blocks'),
    '#default_value' => variable_get('block_cache', FALSE),
    '#disabled' => $disabled,
    '#description' => $disabled ? t('Block caching is inactive because you have enabled modules defining content access restrictions.') : NULL,
    '#weight' => -1,
  );

  // Check if the "Who's online" block is enabled.
874
  $online_block_enabled = db_query_range("SELECT 1 FROM {block} b WHERE module = 'user' AND delta = 'online' AND status = 1", 0, 1)->fetchField();
875 876 877 878 879 880 881

  // 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>';
  }
}