block.module 33.9 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
 * Implements 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 = '';
21
      $output .= '<h3>' . t('About') . '</h3>';
22
      $output .= '<p>' . t('The Block module allows you to create boxes of content, which are rendered into an area, or region, of one or more pages of a website. The core Seven administration theme, for example, implements the regions "Content", "Help", "Dashboard main", and "Dashboard sidebar", and a block may appear in any one of these regions. The <a href="@blocks">Blocks administration page</a> provides a drag-and-drop interface for assigning a block to a region, and for controlling the order of blocks within regions. For more information, see the online handbook entry for <a href="@block">Block module</a>.', array('@block' => 'http://drupal.org/handbook/modules/block/', '@blocks' => url('admin/structure/block'))) . '</p>';
23
24
25
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Positioning content') . '</dt>';
26
      $output .= '<dd>' . t('When working with blocks, remember that all themes do <em>not</em> implement the same regions, or display regions in the same way. Blocks are positioned on a per-theme basis. Users with the <em>Administer blocks</em> permission can disable blocks. Disabled blocks are listed on the <a href="@blocks">Blocks administration page</a>, but are not displayed in any region.', array('@block' => 'http://drupal.org/handbook/modules/block/', '@blocks' => url('admin/structure/block'))) . '</dd>';
27
28
29
      $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>';
30
      $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>';
31
      $output .= '</dl>';
32
      return $output;
33
    case 'admin/structure/block/add':
34
      return '<p>' . t('Use this page to create a new custom block.') . '</p>';
Dries's avatar
   
Dries committed
35
  }
36
  if ($arg[0] == 'admin' && $arg[1] == 'structure' && $arg['2'] == 'block' && (empty($arg[3]) || $arg[3] == 'list')) {
37
38
39
40
41
42
    $demo_theme = !empty($arg[4]) ? $arg[4] : variable_get('theme_default', 'garland');
    $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>';
    $output .= '<p>' . l(t('Demonstrate block regions (@theme)', array('@theme' => $themes[$demo_theme]->info['name'])), 'admin/structure/block/demo/' . $demo_theme) . '</p>';
    return $output;
  }
Dries's avatar
   
Dries committed
43
44
}

45
/**
46
 * Implements hook_theme().
47
48
49
 */
function block_theme() {
  return array(
50
    'block' => array(
51
      'render element' => 'elements',
52
      'template' => 'block',
53
    ),
54
55
    'block_admin_display_form' => array(
      'template' => 'block-admin-display-form',
56
      'file' => 'block.admin.inc',
57
      'render element' => 'form',
58
59
60
61
    ),
  );
}

Dries's avatar
   
Dries committed
62
/**
63
 * Implements hook_permission().
Dries's avatar
   
Dries committed
64
 */
65
function block_permission() {
66
  return array(
67
68
69
    'administer blocks' => array(
      'title' => t('Administer blocks'),
    ),
70
  );
Dries's avatar
   
Dries committed
71
72
}

Dries's avatar
   
Dries committed
73
/**
74
 * Implements hook_menu().
Dries's avatar
   
Dries committed
75
 */
76
function block_menu() {
77
  $default_theme = variable_get('theme_default', 'garland');
78
  $items['admin/structure/block'] = array(
79
80
    'title' => 'Blocks',
    'description' => 'Configure what block content appears in your site\'s sidebars and other regions.',
81
    'page callback' => 'block_admin_display',
82
    'page arguments' => array($default_theme),
83
    'access arguments' => array('administer blocks'),
84
    'file' => 'block.admin.inc',
85
  );
86
  $items['admin/structure/block/list'] = array(
87
    'title' => 'List',
88
89
90
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
91
  $items['admin/structure/block/manage/%/%'] = array(
92
    'title' => 'Configure block',
93
    'page callback' => 'drupal_get_form',
94
    'page arguments' => array('block_admin_configure', 4, 5),
95
    'access arguments' => array('administer blocks'),
96
    'file' => 'block.admin.inc',
97
  );
98
  $items['admin/structure/block/manage/%/%/configure'] = array(
99
100
101
102
    'title' => 'Configure block',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'context' => MENU_CONTEXT_INLINE,
  );
103
  $items['admin/structure/block/manage/%/%/delete'] = array(
104
    'title' => 'Delete block',
105
    'page callback' => 'drupal_get_form',
106
    'page arguments' => array('block_custom_block_delete', 4, 5),
107
    'access arguments' => array('administer blocks'),
108
109
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_NONE,
110
    'file' => 'block.admin.inc',
111
  );
112
  $items['admin/structure/block/add'] = array(
113
    'title' => 'Add block',
114
    'page callback' => 'drupal_get_form',
115
    'page arguments' => array('block_add_block_form'),
116
    'access arguments' => array('administer blocks'),
117
    'type' => MENU_LOCAL_ACTION,
118
    'file' => 'block.admin.inc',
119
120
  );
  foreach (list_themes() as $key => $theme) {
121
    $items['admin/structure/block/list/' . $key] = array(
122
123
      'title' => check_plain($theme->info['name']),
      'page arguments' => array($key),
124
125
126
127
128
129
      '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',
    );
130
131
132
133
134
135
136
137
138
139
    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',
      );
    }
140
141
142
143
144
    $items['admin/structure/block/demo/' . $key] = array(
      'title' => check_plain($theme->info['name']),
      'page callback' => 'block_admin_demo',
      'page arguments' => array($key),
      'type' => MENU_CALLBACK,
145
146
      'access callback' => '_block_themes_access',
      'access arguments' => array($theme),
147
148
      'theme callback' => '_block_custom_theme',
      'theme arguments' => array($key),
149
      'file' => 'block.admin.inc',
150
    );
Dries's avatar
   
Dries committed
151
  }
Dries's avatar
   
Dries committed
152
  return $items;
Dries's avatar
   
Dries committed
153
154
}

155
/**
156
 * Menu item access callback - only admin or enabled themes can be accessed.
157
158
 */
function _block_themes_access($theme) {
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
  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;
176
177
}

Dries's avatar
   
Dries committed
178
/**
179
 * Implements hook_block_info().
Dries's avatar
   
Dries committed
180
 */
181
function block_block_info() {
182
  $blocks = array();
183

184
  $result = db_query('SELECT bid, info FROM {block_custom} ORDER BY info');
185
  foreach ($result as $block) {
186
187
    $blocks[$block->bid]['info'] = $block->info;
    // Not worth caching.
188
    $blocks[$block->bid]['cache'] = DRUPAL_NO_CACHE;
189
190
191
  }
  return $blocks;
}
192

193
/**
194
 * Implements hook_block_configure().
195
 */
196
function block_block_configure($delta = 0) {
197
  $custom_block = array('format' => filter_default_format());
198
  if ($delta) {
199
    $custom_block = block_custom_block_get($delta);
200
  }
201
  return block_custom_block_form($custom_block);
202
203
}

204
/**
205
 * Implements hook_block_save().
206
207
 */
function block_block_save($delta = 0, $edit = array()) {
208
  block_custom_block_save($edit, $delta);
209
210
211
}

/**
212
 * Implements hook_block_view().
213
214
215
216
 *
 * Generates the administrator-defined blocks for display.
 */
function block_block_view($delta = 0, $edit = array()) {
217
  $block = db_query('SELECT body, format FROM {block_custom} WHERE bid = :bid', array(':bid' => $delta))->fetchObject();
218
  $data['content'] = check_markup($block->body, $block->format, '', TRUE);
219
220
221
  return $data;
}

222
/**
223
 * Implements hook_page_build().
224
225
226
 *
 * Render blocks into their regions.
 */
227
function block_page_build(&$page) {
228
229
230
  global $theme;

  // The theme system might not yet be initialized. We need $theme.
231
  drupal_theme_initialize();
232
233

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

236
237
238
239
240
241
242
243
  $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;
      }
244
    }
245
246
247
248
249
250
251
252
253
    // 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');
254
255
256
  }
  else {
    // Append region description if we are rendering the regions demo page.
257
    $item = menu_get_item();
258
259
260
    if ($item['path'] == 'admin/structure/block/demo/' . $theme) {
      $visible_regions = array_keys(system_region_list($theme, REGIONS_VISIBLE));
      foreach ($visible_regions as $region) {
261
262
263
264
265
        $description = '<div class="block-region">' . $all_regions[$region] . '</div>';
        $page[$region]['block_description'] = array(
          '#markup' => $description,
          '#weight' => 15,
        );
266
267
268
269
270
271
272
273
274
275
276
277
278
279
      }
    }
  }
}

/**
 * Get a renderable array of a region containing all enabled blocks.
 *
 * @param $region
 *   The requested region.
 */
function block_get_blocks_by_region($region) {
  $build = array();
  if ($list = block_list($region)) {
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
    $build = _block_get_renderable_array($list);
  }
  return $build;
}

/**
 * Get an array of blocks suitable for drupal_render().
 *
 * @param $list
 *   A list of blocks such as that returned by block_list().
 * @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);
299
300
301

    // Add contextual links for this block; skipping the system main block.
    if ($key != 'system_main') {
302
      $build[$key]['#contextual_links']['block'] = array('admin/structure/block/manage', array($block->module, $block->delta));
303
304
    }

305
306
307
308
309
    $build[$key] += array(
      '#block' => $block,
      '#weight' => ++$weight,
    );
    $build[$key]['#theme_wrappers'][] ='block';
310
  }
311
  $build['#sorted'] = TRUE;
312
313
314
  return $build;
}

Dries's avatar
   
Dries committed
315
/**
316
 * Update the 'block' DB table with the blocks currently exported by modules.
Dries's avatar
   
Dries committed
317
 *
318
319
320
 * @param $theme
 *   The theme to rehash blocks for. If not provided, defaults to the currently
 *   used theme.
321
 *
Dries's avatar
   
Dries committed
322
 * @return
323
 *   Blocks currently exported by modules.
Dries's avatar
   
Dries committed
324
 */
325
function _block_rehash($theme = NULL) {
326
  global $theme_key;
327

328
  drupal_theme_initialize();
329
330
331
332
333
  if (!isset($theme)) {
    // If theme is not specifically set, rehash for the current theme.
    $theme = $theme_key;
  }
  $regions = system_region_list($theme);
Dries's avatar
   
Dries committed
334

335
336
337
338
339
340
341
342
  // 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.
343
344
  foreach (module_implements('block_info') as $module) {
    $module_blocks = module_invoke($module, 'block_info');
345
346
347
348
349
350
351
352
353
354
355
    foreach ($module_blocks as $delta => $block) {
      // Compile a condition to retrieve this block from the database.
      $condition = db_and()
        ->condition('module', $module)
        ->condition('delta', $delta);
      $or->condition($condition);
      // Add identifiers.
      $block['module'] = $module;
      $block['delta']  = $delta;
      $block['theme']  = $theme;
      $current_blocks[$module][$delta] = $block;
Dries's avatar
   
Dries committed
356
357
    }
  }
358
359
360
361
362
363
364
365
366
367
  // Save the blocks defined in code for alter context.
  $code_blocks = $current_blocks;
  $database_blocks = db_select('block', 'b')
    ->fields('b')
    ->condition($or)
    ->condition('theme', $theme)
    ->execute();
  foreach ($database_blocks as $block) {
    // Preserve info which is not in the database.
    $block->info = $current_blocks[$block->module][$block->delta]['info'];
368
369
370
371
372
    // The cache mode can only by set from hook_block_info(), so that has
    // precedence over the database's value.
    if (isset($current_blocks[$block->module][$block->delta]['cache'])) {
      $block->cache = $current_blocks[$block->module][$block->delta]['cache'];
    }
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
    // Blocks stored in the database override the blocks defined in code.
    $current_blocks[$block->module][$block->delta] = get_object_vars($block);
    // Preserve this block.
    $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;
      }
      if (!empty($block['region']) && $block['region'] != BLOCK_REGION_NONE && !isset($regions[$block['region']])) {
        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
        // need to move the bock 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
403
      // because the 'title' attribute is saved to the {blocks} table.
404
405
406
407
408
409
410
411
412
413
414
415
416
417
      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();
      }
      drupal_write_record('block', $block, $primary_keys);
      // Add to the list of blocks we return.
      $blocks[] = $block;
418
    }
419
  }
420
421
422
423
424
425
426
427
  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's avatar
   
Dries committed
428
429
  return $blocks;
}
Dries's avatar
   
Dries committed
430

431
432
433
434
435
436
437
438
439
440
441
442
443
/**
 * 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.
 */
444
445
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
446
447
}

448
449
450
/**
 * Define the custom block form.
 */
451
function block_custom_block_form($edit = array()) {
452
453
454
455
  $edit += array(
    'info' => '',
    'body' => '',
  );
456
457
458
  $form['info'] = array(
    '#type' => 'textfield',
    '#title' => t('Block description'),
459
    '#default_value' => $edit['info'],
460
    '#maxlength' => 64,
461
    '#description' => t('A brief description of your block. Used on the <a href="@overview">Blocks administration page</a>.', array('@overview' => url('admin/structure/block'))),
462
463
464
    '#required' => TRUE,
    '#weight' => -19,
  );
465
466
  $form['body_field']['#weight'] = -17;
  $form['body_field']['body'] = array(
467
    '#type' => 'text_format',
468
    '#title' => t('Block body'),
469
    '#default_value' => $edit['body'],
470
    '#format' => isset($edit['format']) ? $edit['format'] : NULL,
471
472
    '#rows' => 15,
    '#description' => t('The content of the block as shown to the user.'),
473
    '#required' => TRUE,
474
475
    '#weight' => -17,
  );
476

477
  return $form;
478
479
}

480
481
482
483
484
485
/**
 * Saves a user-created block in the database.
 *
 * @param $edit
 *   Associative array of fields to save. Array keys:
 *   - info: Block description.
486
487
488
 *   - body: Associative array of body value and format.  Array keys:
 *     - value: Block contents.
 *     - format: Filter ID of the filter format for the body.
489
490
491
492
493
 * @param $delta
 *   Block ID of the block to save.
 * @return
 *   Always returns TRUE.
 */
494
495
function block_custom_block_save($edit, $delta) {
  db_update('block_custom')
496
    ->fields(array(
497
      'body' => $edit['body']['value'],
498
      'info' => $edit['info'],
499
      'format' => $edit['body']['format'],
500
501
502
    ))
    ->condition('bid', $delta)
    ->execute();
503
  return TRUE;
504
505
}

Dries's avatar
   
Dries committed
506
/**
507
 * Implements hook_form_FORM_ID_alter().
Dries's avatar
   
Dries committed
508
 */
509
510
511
function block_form_user_profile_form_alter(&$form, &$form_state) {
  if ($form['#user_category'] == 'account') {
    $account = $form['#user'];
512
    $rids = array_keys($account->roles);
513
    $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));
514
515

    $blocks = array();
516
    foreach ($result as $block) {
517
      $data = module_invoke($block->module, 'block_info');
518
      if ($data[$block->delta]['info']) {
519
        $blocks[$block->module][$block->delta] = array(
520
521
522
523
          '#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),
        );
524
      }
525
    }
526
527
528
529
530
531
532
533
534
535
536
    // 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;
537
538
539
540
    }
  }
}

541
542
543
/**
 * Initialize blocks for enabled themes.
 */
544
545
546
function block_themes_enabled($theme_list) {
  foreach ($theme_list as $theme) {
    block_theme_initialize($theme);
547
548
549
550
551
  }
}

/**
 * Assign an initial, default set of blocks for a theme.
552
 *
553
554
555
556
 * 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.
557
 *
558
559
560
 * @param $theme
 *   The name of a theme.
 */
561
function block_theme_initialize($theme) {
562
  // Initialize theme's blocks if none already registered.
563
  $has_blocks = (bool) db_query_range('SELECT 1 FROM {block} WHERE theme = :theme', 0, 1, array(':theme' => $theme))->fetchField();
564
  if (!$has_blocks) {
565
566
    $default_theme = variable_get('theme_default', 'garland');
    $regions = system_region_list($theme);
567
568
    $result = db_query("SELECT * FROM {block} WHERE theme = :theme", array(':theme' => $default_theme), array('fetch' => PDO::FETCH_ASSOC));
    foreach ($result as $block) {
569
      // If the region isn't supported by the theme, assign the block to the theme's default region.
570
      if ($block['status'] && !array_key_exists($block['region'], $regions)) {
571
572
        $block['region'] = system_default_region($theme);
      }
573
      $block['theme'] = $theme;
574
575
      unset($block['bid']);
      drupal_write_record('block', $block);
576
577
578
579
    }
  }
}

580
581
582
583
584
585
586
587
588
589
590
591
592
/**
 * 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
593
594
 *   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>.
595
596
 */
function block_list($region) {
597
  $blocks = &drupal_static(__FUNCTION__);
598

599
  if (!isset($blocks)) {
600
601
602
    $blocks = _block_load_blocks();
  }

603
  // Create an empty array if there are no entries.
604
605
606
  if (!isset($blocks[$region])) {
    $blocks[$region] = array();
  }
607
608
609
  else {
    $blocks[$region] = _block_render_blocks($blocks[$region]);
  }
610
611
612
613

  return $blocks[$region];
}

614
615
616
617
618
619
/**
 * Load a block object from the database.
 *
 * @param $module
 *   Name of the module that implements the block to load.
 * @param $delta
620
621
 *   Unique ID of the block within the context of $module. Pass NULL to return
 *   an empty $block object for $module.
622
623
624
625
626
 *
 * @return
 *   A block object.
 */
function block_load($module, $delta) {
627
628
629
  if (isset($delta)) {
    $block = db_query('SELECT * FROM {block} WHERE module = :module AND delta = :delta', array(':module' => $module, ':delta' => $delta))->fetchObject();
  }
630
631
632

  // If the block does not exist in the database yet return a stub block
  // object.
633
  if (empty($block)) {
634
635
636
637
638
639
640
641
    $block = new stdClass;
    $block->module = $module;
    $block->delta = $delta;
  }

  return $block;
}

642
/**
643
 * Load blocks information from the database.
644
645
 */
function _block_load_blocks() {
646
  global $theme_key;
647

648
649
650
651
652
653
654
655
656
  $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')
657
    ->addTag('translatable')
658
    ->execute();
659

660
  $block_info = $result->fetchAllAssoc('bid');
661
  // Allow modules to modify the block list.
662
  drupal_alter('block_list', $block_info);
663
664

  $blocks = array();
665
  foreach ($block_info as $block) {
666
667
668
669
670
671
    $blocks[$block->region]["{$block->module}_{$block->delta}"] = $block;
  }
  return $blocks;
}

/**
672
 * Implements hook_block_list_alter().
673
 *
674
 * Check the page, user role and user specific visibilty settings.
675
 * Remove the block if the visibility conditions are not met.
676
 */
677
function block_block_list_alter(&$blocks) {
678
679
680
681
682
683
684
685
686
687
  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) {
688
    if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
689
690
      // This block was added by a contrib module, leave it in the list.
      continue;
691
    }
692
693
694
695

    // 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.
696
    if (isset($block_roles[$block->module][$block->delta]) && !array_intersect($block_roles[$block->module][$block->delta], array_keys($user->roles))) {
697
698
699
      // No match.
      unset($blocks[$key]);
      continue;
700
701
    }

702
    // Use the user's block visibility setting, if necessary.
703
704
705
    if ($block->custom != 0) {
      if ($user->uid && isset($user->block[$block->module][$block->delta])) {
        $enabled = $user->block[$block->module][$block->delta];
706
707
      }
      else {
708
        $enabled = ($block->custom == 1);
709
      }
710
711
712
713
    }
    else {
      $enabled = TRUE;
    }
714
715
716
717
    if (!$enabled) {
      unset($blocks[$key]);
      continue;
    }
718

719
    // Match path if necessary.
720
    if ($block->pages) {
721
722
723
      // Convert path to lowercase. This allows comparison of the same path
      // with different case. Ex: /Page, /page, /PAGE.
      $pages = drupal_strtolower($block->pages);
724
      if ($block->visibility < 2) {
725
726
727
728
        // Convert the Drupal path to lowercase
        $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);
729
        if ($path != $_GET['q']) {
730
          $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
731
        }
732
733
734
735
        // 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);
736
      }
737
738
739
      elseif (module_exists('php')) {
        $page_match = php_eval($block->pages);
      }
740
      else {
741
        $page_match = FALSE;
742
      }
743
744
745
746
    }
    else {
      $page_match = TRUE;
    }
747
748
749
    if (!$page_match) {
      unset($blocks[$key]);
    }
750
751
  }
}
752

753
754
755
756
/**
 * Render the content and subject for a set of blocks.
 *
 * @param $region_blocks
757
 *   An array of block objects such as returned for one region by _block_load_blocks().
758
759
 *
 * @return
760
 *   An array of visible blocks as expected by drupal_render().
761
762
763
764
765
 */
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)) {
766
767
      // Erase the block from the static array - we'll put it back if it has
      // content.
768
      unset($region_blocks[$key]);
769
770
771
772
773
774
775
776
777
      // 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);
778
779

        // Allow modules to modify the block before it is viewed, via either
780
781
        // hook_block_view_alter() or hook_block_view_MODULE_DELTA_alter().
        drupal_alter(array('block_view', "block_view_{$block->module}_{$block->delta}"), $array, $block);
782

783
784
        if (isset($cid)) {
          cache_set($cid, $array, 'cache_block', CACHE_TEMPORARY);
785
        }
786
      }
787

788
789
790
      if (isset($array) && is_array($array)) {
        foreach ($array as $k => $v) {
          $block->$k = $v;
Dries's avatar
   
Dries committed
791
        }
792
793
      }
      if (isset($block->content) && $block->content) {
794
        // Normalize to the drupal_render() structure.
795
796
797
        if (is_string($block->content)) {
          $block->content = array('#markup' => $block->content);
        }
798
799
800
801
802
803
804
805
        // 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 = '';
806
        }
807
        $region_blocks["{$block->module}_{$block->delta}"] = $block;
808
809
810
      }
    }
  }
811
  return $region_blocks;
812
}
813
814
815
816
817
818
819
820
821
822

/**
 * 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.
 *
823
 * Theme and language contexts are automatically differentiated.
824
825
826
827
828
829
 *
 * @param $block
 * @return
 *   The string used as cache_id for the block.
 */
function _block_get_cache_id($block) {
830
  global $user;
831

832
833
834
835
  // 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.
836
  if (variable_get('block_cache', FALSE) && !in_array($block->cache, array(DRUPAL_NO_CACHE, DRUPAL_CACHE_CUSTOM)) && $user->uid != 1) {
837
838
839
    // Start with common sub-patterns: block identification, theme, language.
    $cid_parts[] = $block->module;
    $cid_parts[] = $block->delta;
840
    $cid_parts = array_merge($cid_parts, drupal_render_cid_parts($block->cache));
841
842
843

    return implode(':', $cid_parts);
  }
844
}
845
846

/**
847
 * Implements hook_flush_caches().
848
849
 */
function block_flush_caches() {
850
851
852
853
854
855
856
857
  // 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);
  }

858
859
  return array('cache_block');
}
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878

/**
 * 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) {
879
  $block_counter = &drupal_static(__FUNCTION__, array());
880
  $variables['block'] = $variables['elements']['#block'];
881
882
883
884
885
886
887
888
  // 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]++;

889
890
  // Create the $content variable that templates expect.
  $variables['content'] = $variables['elements']['#children'];
891

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

894
895
896
  $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->region;
  $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->module;
  $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->module . '__' . $variables['block']->delta;
897
898
899

  // Create a valid HTML ID and make sure it is unique.
  $variables['block_html_id'] = drupal_html_id('block-' . $variables['block']->module . '-' . $variables['block']->delta);
900
}
901

902
/**
903
 * Implements hook_user_role_delete().
904
 *
905
 * Remove deleted role from blocks that use it.
906
907
908
909
910
911
912
 */
function block_user_role_delete($role) {
  db_delete('block_role')
    ->condition('rid', $role->rid)
    ->execute();
}

913
/**
914
 * Implements hook_filter_format_delete().
915
 */
916
function block_filter_format_delete($format, $fallback) {
917
  db_update('block_custom')
918
    ->fields(array('format' => $fallback->format))
919
920
921
922
    ->condition('format', $format->format)
    ->execute();
}

923
/**
924
 * Implements hook_menu_delete().
925
926
927
928
929
930
931
932
933
934
935
936
 */
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();
}

937
/**
938
 * Implements hook_form_FORM_ID_alter().
939
940
941
942
943
944
945
946
947
948
949
950
 */
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,
  );
}
951
952
953
954
955
956
957
958
959
960
961
962
963
964

/**
 * Implements hook_modules_uninstalled().
 *
 * Cleanup {block} and {block_role} tables from modules' blocks.
 */
function block_modules_uninstalled($modules) {
  db_delete('block')
    ->condition('module', $modules, 'IN')
    ->execute();
  db_delete('block_role')
    ->condition('module', $modules, 'IN')
    ->execute();
}