block.module 33 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
33
    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
34
  }
35
36
37
38
39
40
41
  if ($arg[0] == 'admin' && $arg[1] == 'structure' && $arg['2'] == 'block' && (empty($arg[3]) || $arg[3] == 'list')) {  
    $demo_theme = !empty($arg[4]) ? $arg[4] : variable_get('theme_default', '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
42
43
}

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

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

Dries's avatar
   
Dries committed
73
/**
74
 * Implement 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/list/js'] = array(
92
    'title' => 'JavaScript List Form',
93
    'page callback' => 'block_admin_display_js',
94
    'access arguments' => array('administer blocks'),
95
    'type' => MENU_CALLBACK,
96
    'file' => 'block.admin.inc',
97
  );
98
  $items['admin/structure/block/manage/%block/%/configure'] = array(
99
    'title' => 'Configure block',
100
    'page callback' => 'drupal_get_form',
101
102
    'page arguments' => array('block_admin_configure', 4),
    'load arguments' => array(5),
103
    'access arguments' => array('administer blocks'),
104
    'type' => MENU_CALLBACK,
105
    'file' => 'block.admin.inc',
106
  );
107
  $items['admin/structure/block/manage/%block/%/delete'] = array(
108
    'title' => 'Delete block',
109
    'page callback' => 'drupal_get_form',
110
111
    'page arguments' => array('block_custom_block_delete', 4),
    'load arguments' => array(5),
112
    'access arguments' => array('administer blocks'),
113
    'type' => MENU_CALLBACK,
114
    'file' => 'block.admin.inc',
115
  );
116
  $items['admin/structure/block/add'] = array(
117
    'title' => 'Add block',
118
    'page callback' => 'drupal_get_form',
119
    'page arguments' => array('block_add_block_form'),
120
    'access arguments' => array('administer blocks'),
121
    'type' => MENU_LOCAL_ACTION,
122
    'file' => 'block.admin.inc',
123
124
  );
  foreach (list_themes() as $key => $theme) {
125
    $items['admin/structure/block/list/' . $key] = array(
126
127
      'title' => check_plain($theme->info['name']),
      'page arguments' => array($key),
128
129
130
131
132
133
134
135
136
137
138
      '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',
    );
    $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,
139
140
      'access callback' => '_block_themes_access',
      'access arguments' => array($theme),
141
142
      'theme callback' => '_block_custom_theme',
      'theme arguments' => array($key),
143
      'file' => 'block.admin.inc',
144
    );
Dries's avatar
   
Dries committed
145
  }
Dries's avatar
   
Dries committed
146
  return $items;
Dries's avatar
   
Dries committed
147
148
}

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

Dries's avatar
   
Dries committed
172
/**
173
 * Implement hook_block_info().
Dries's avatar
   
Dries committed
174
 */
175
function block_block_info() {
176
  $blocks = array();
177

178
  $result = db_query('SELECT bid, info FROM {block_custom} ORDER BY info');
179
  foreach ($result as $block) {
180
181
    $blocks[$block->bid]['info'] = $block->info;
    // Not worth caching.
182
    $blocks[$block->bid]['cache'] = DRUPAL_NO_CACHE;
183
184
185
  }
  return $blocks;
}
186

187
/**
188
 * Implement hook_block_configure().
189
 */
190
function block_block_configure($delta = 0) {
191
  $custom_block = array('format' => filter_default_format());
192
  if ($delta) {
193
    $custom_block = block_custom_block_get($delta);
194
  }
195
  return block_custom_block_form($custom_block);
196
197
}

198
/**
199
 * Implement hook_block_save().
200
201
 */
function block_block_save($delta = 0, $edit = array()) {
202
  block_custom_block_save($edit, $delta);
203
204
205
}

/**
206
 * Implement hook_block_view().
207
208
209
210
 *
 * Generates the administrator-defined blocks for display.
 */
function block_block_view($delta = 0, $edit = array()) {
211
  $block = db_query('SELECT body, format FROM {block_custom} WHERE bid = :bid', array(':bid' => $delta))->fetchObject();
212
  $data['content'] = check_markup($block->body, $block->format, '', TRUE);
213
214
215
  return $data;
}

216
/**
217
 * Implement hook_page_build().
218
219
220
 *
 * Render blocks into their regions.
 */
221
function block_page_build(&$page) {
222
223
224
  global $theme;

  // The theme system might not yet be initialized. We need $theme.
225
  drupal_theme_initialize();
226
227

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

230
231
232
233
234
235
236
237
238
  $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) {
      $page[$region] = array();
      // Assign blocks to region.
      if ($blocks = block_get_blocks_by_region($region)) {
        $page[$region] = $blocks;
      }
239
    }
240
241
242
  }
  else {
    // Append region description if we are rendering the regions demo page.
243
    $item = menu_get_item();
244
245
246
    if ($item['path'] == 'admin/structure/block/demo/' . $theme) {
      $visible_regions = array_keys(system_region_list($theme, REGIONS_VISIBLE));
      foreach ($visible_regions as $region) {
247
248
249
250
251
        $description = '<div class="block-region">' . $all_regions[$region] . '</div>';
        $page[$region]['block_description'] = array(
          '#markup' => $description,
          '#weight' => 15,
        );
252
253
254
255
256
257
258
259
260
261
262
263
264
265
      }
    }
  }
}

/**
 * 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)) {
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
    $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);
    $build[$key] += array(
      '#block' => $block,
      '#weight' => ++$weight,
    );
    $build[$key]['#theme_wrappers'][] ='block';
290
  }
291
  $build['#sorted'] = TRUE;
292
293
294
  return $build;
}

Dries's avatar
   
Dries committed
295
/**
296
 * Update the 'block' DB table with the blocks currently exported by modules.
Dries's avatar
   
Dries committed
297
 *
298
299
300
301
 * @param $theme
 *   The theme to rehash blocks for. If not provided, defaults to the currently
 *   used theme.
 * 
Dries's avatar
   
Dries committed
302
 * @return
303
 *   Blocks currently exported by modules.
Dries's avatar
   
Dries committed
304
 */
305
function _block_rehash($theme = NULL) {
306
  global $theme_key;
307
  
308
  drupal_theme_initialize();
309

310
311
312
313
314
  if (!isset($theme)) {
    // If theme is not specifically set, rehash for the current theme.
    $theme = $theme_key;
  }

315
  $old_blocks = array();
316
  $result = db_query("SELECT * FROM {block} WHERE theme = :theme", array(':theme' => $theme));
317
318
  foreach ($result as $old_block) {
    $old_block = is_object($old_block) ? get_object_vars($old_block) : $old_block;
319
    $old_blocks[$old_block['module']][$old_block['delta']] = $old_block;
Dries's avatar
   
Dries committed
320
321
  }

322
  $blocks = array();
323
  // Valid region names for the theme.
324
  $regions = system_region_list($theme);
Dries's avatar
   
Dries committed
325

326
327
  foreach (module_implements('block_info') as $module) {
    $module_blocks = module_invoke($module, 'block_info');
Dries's avatar
   
Dries committed
328
329
    if ($module_blocks) {
      foreach ($module_blocks as $delta => $block) {
330
331
332
333
        if (empty($old_blocks[$module][$delta])) {
          // If it's a new block, add identifiers.
          $block['module'] = $module;
          $block['delta']  = $delta;
334
          $block['theme']  = $theme;
335
336
337
338
339
340
          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']  = '';
          }
341
          // Add defaults and save it into the database.
342
          drupal_write_record('block', $block);
343
344
345
          // Set region to none if not enabled.
          $block['region'] = $block['status'] ? $block['region'] : BLOCK_REGION_NONE;
          // Add to the list of blocks we return.
346
          $blocks[] = $block;
Dries's avatar
   
Dries committed
347
348
        }
        else {
349
350
351
352
353
354
          // 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'];
355
356
357
358
359
360
361
362
363
          // 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;
          }
364
          // Add this block to the list of blocks we return.
365
366
367
          $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
368
369
370
371
372
        }
      }
    }
  }

373
374
375
  // 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) {
376
377
378
      db_delete('block')
        ->condition('module', $module)
        ->condition('delta', $delta)
379
        ->condition('theme', $theme)
380
        ->execute();
381
    }
382
  }
Dries's avatar
   
Dries committed
383
384
  return $blocks;
}
Dries's avatar
   
Dries committed
385

386
387
388
389
390
391
392
393
394
395
396
397
398
/**
 * 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.
 */
399
400
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
401
402
}

403
404
405
/**
 * Define the custom block form.
 */
406
function block_custom_block_form($edit = array()) {
407
408
409
410
  $edit += array(
    'info' => '',
    'body' => '',
  );
411
412
413
  $form['info'] = array(
    '#type' => 'textfield',
    '#title' => t('Block description'),
414
    '#default_value' => $edit['info'],
415
    '#maxlength' => 64,
416
    '#description' => t('A brief description of your block. Used on the <a href="@overview">blocks administration page</a>.', array('@overview' => url('admin/structure/block'))),
417
418
419
    '#required' => TRUE,
    '#weight' => -19,
  );
420
421
  $form['body_field']['#weight'] = -17;
  $form['body_field']['body'] = array(
422
423
    '#type' => 'textarea',
    '#title' => t('Block body'),
424
    '#default_value' => $edit['body'],
425
    '#text_format' => isset($edit['format']) ? $edit['format'] : filter_default_format(),
426
427
    '#rows' => 15,
    '#description' => t('The content of the block as shown to the user.'),
428
    '#required' => TRUE,
429
    '#weight' => -17,
430
    '#access' => filter_access(filter_format_load($edit['format'])),
431
  );
432

433
  return $form;
434
435
}

436
437
438
439
440
441
442
443
444
445
446
447
448
/**
 * 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.
 */
449
450
function block_custom_block_save($edit, $delta) {
  db_update('block_custom')
451
452
453
454
455
456
457
    ->fields(array(
      'body' => $edit['body'],
      'info' => $edit['info'],
      'format' => $edit['body_format'],
    ))
    ->condition('bid', $delta)
    ->execute();
458
  return TRUE;
459
460
}

Dries's avatar
   
Dries committed
461
/**
462
 * Implement hook_form_FORM_ID_alter().
Dries's avatar
   
Dries committed
463
 */
464
465
466
function block_form_user_profile_form_alter(&$form, &$form_state) {
  if ($form['#user_category'] == 'account') {
    $account = $form['#user'];
467
    $rids = array_keys($account->roles);
468
    $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));
469
470

    $blocks = array();
471
    foreach ($result as $block) {
472
      $data = module_invoke($block->module, 'block_info');
473
      if ($data[$block->delta]['info']) {
474
        $blocks[$block->module][$block->delta] = array(
475
476
477
478
          '#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),
        );
479
      }
480
    }
481
482
483
484
485
486
487
488
489
490
491
    // 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;
492
493
494
495
    }
  }
}

496
/**
497
 * Implement hook_form_FORM_ID_alter().
498
499
 */
function block_form_system_themes_form_alter(&$form, &$form_state) {
500
501
502
503
  // 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');
504
505
506
507
508
509
510
511
512
513
}

/**
 * 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) {
514
          block_theme_initialize($key);
515
516
517
        }
      }
    }
518
    if ($form_state['values']['admin_theme'] && $form_state['values']['admin_theme'] !== variable_get('admin_theme', 0)) {
519
      // If we're changing themes, make sure the theme has its blocks initialized.
520
      $has_blocks = (bool) db_query_range('SELECT 1 FROM {block} WHERE theme = :theme', 0, 1, array(':theme' => $form_state['values']['admin_theme']))->fetchField();
521
      if (!$has_blocks) {
522
        block_theme_initialize($form_state['values']['admin_theme']);
523
524
525
526
527
528
529
      }
    }
  }
}

/**
 * Assign an initial, default set of blocks for a theme.
530
 *
531
532
533
534
 * 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.
535
 *
536
537
538
 * @param $theme
 *   The name of a theme.
 */
539
function block_theme_initialize($theme) {
540
  // Initialize theme's blocks if none already registered.
541
  $has_blocks = (bool) db_query_range('SELECT 1 FROM {block} WHERE theme = :theme', 0, 1, array(':theme' => $theme))->fetchField();
542
  if (!$has_blocks) {
543
544
    $default_theme = variable_get('theme_default', 'garland');
    $regions = system_region_list($theme);
545
546
    $result = db_query("SELECT * FROM {block} WHERE theme = :theme", array(':theme' => $default_theme), array('fetch' => PDO::FETCH_ASSOC));
    foreach ($result as $block) {
547
548
549
550
      // 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);
      }
551
      $block['theme'] = $theme;
552
553
      unset($block['bid']);
      drupal_write_record('block', $block);
554
555
556
557
    }
  }
}

558
559
560
561
562
563
564
565
566
567
568
569
570
/**
 * 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
571
572
 *   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>.
573
574
 */
function block_list($region) {
575
  $blocks = &drupal_static(__FUNCTION__, array());
576

577
  if (empty($blocks)) {
578
579
580
    $blocks = _block_load_blocks();
  }

581
  // Create an empty array if there were no entries.
582
583
584
585
586
587
588
589
590
  if (!isset($blocks[$region])) {
    $blocks[$region] = array();
  }

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

  return $blocks[$region];
}

591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
/**
 * Load a block object from the database.
 *
 * @param $module
 *   Name of the module that implements the block to load.
 * @param $delta
 *   Unique ID of the block within the context of $module.
 *
 * @return
 *   A block object.
 */
function block_load($module, $delta) {
  $block = db_query('SELECT * FROM {block} WHERE module = :module AND delta = :delta',
    array(
      ':module' => $module,
      ':delta' => $delta
    ))
    ->fetchObject();

  // If the block does not exist in the database yet return a stub block
  // object.
  if (!$block) {
    $block = new stdClass;
    $block->module = $module;
    $block->delta = $delta;
  }

  return $block;
}

621
/**
622
 * Load blocks information from the database.
623
624
 */
function _block_load_blocks() {
625
  global $theme_key;
626

627
628
629
630
631
632
633
634
635
  $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')
636
    ->addTag('translatable')
637
    ->execute();
638

639
  $block_info = $result->fetchAllAssoc('bid');
640
  // Allow modules to modify the block list.
641
  drupal_alter('block_info', $block_info);
642
643

  $blocks = array();
644
  foreach ($block_info as $block) {
645
646
647
648
649
650
    $blocks[$block->region]["{$block->module}_{$block->delta}"] = $block;
  }
  return $blocks;
}

/**
651
 * Implement hook_block_info_alter().
652
 *
653
654
 * Check the page, user role, content type and user specific visibilty settings.
 * Remove the block if the visibility conditions are not met.
655
 */
656
function block_block_info_alter(&$blocks) {
657
658
659
660
661
662
663
664
665
  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;
  }

666
667
668
669
670
671
672
  // 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;
  }

673
674
675
676
  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;
677
    }
678
679
680
681

    // 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.
682
    if (isset($block_roles[$block->module][$block->delta]) && !array_intersect($block_roles[$block->module][$block->delta], array_keys($user->roles))) {
683
684
685
      // No match.
      unset($blocks[$key]);
      continue;
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
    }

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

716
    // Use the user's block visibility setting, if necessary.
717
718
719
    if ($block->custom != 0) {
      if ($user->uid && isset($user->block[$block->module][$block->delta])) {
        $enabled = $user->block[$block->module][$block->delta];
720
721
      }
      else {
722
        $enabled = ($block->custom == 1);
723
      }
724
725
726
727
    }
    else {
      $enabled = TRUE;
    }
728
729
730
731
    if (!$enabled) {
      unset($blocks[$key]);
      continue;
    }
732

733
    // Match path if necessary.
734
735
736
737
738
739
740
    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);
741
        }
742
743
744
745
        // 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);
746
      }
747
748
749
      elseif (module_exists('php')) {
        $page_match = php_eval($block->pages);
      }
750
      else {
751
        $page_match = FALSE;
752
      }
753
754
755
756
    }
    else {
      $page_match = TRUE;
    }
757
758
759
    if (!$page_match) {
      unset($blocks[$key]);
    }
760
761
  }
}
762

763
764
765
766
/**
 * Render the content and subject for a set of blocks.
 *
 * @param $region_blocks
767
 *   An array of block objects such as returned for one region by _block_load_blocks().
768
769
 *
 * @return
770
 *   An array of visible blocks as expected by drupal_render().
771
772
773
774
775
 */
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)) {
776
777
      // Erase the block from the static array - we'll put it back if it has
      // content.
778
      unset($region_blocks[$key]);
779
780
781
782
783
784
785
786
787
788
789
      // 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);
790
        }
791
      }
792

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

/**
 * 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.
 *
828
 * Theme and language contexts are automatically differentiated.
829
830
831
832
833
834
 *
 * @param $block
 * @return
 *   The string used as cache_id for the block.
 */
function _block_get_cache_id($block) {
835
836
  global $user;
  
837
838
839
840
  // 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.
841
  if (variable_get('block_cache', 0) && !in_array($block->cache, array(DRUPAL_NO_CACHE, DRUPAL_CACHE_CUSTOM)) && $user->uid != 1) {
842
843
844
    // Start with common sub-patterns: block identification, theme, language.
    $cid_parts[] = $block->module;
    $cid_parts[] = $block->delta;
845
    $cid_parts += drupal_render_cid_parts($block->cache);
846
847
848

    return implode(':', $cid_parts);
  }
849
}
850
851

/**
852
 * Implement hook_flush_caches().
853
854
855
856
 */
function block_flush_caches() {
  return array('cache_block');
}
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875

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

886
887
  // Create the $content variable that templates expect.
  $variables['content'] = $variables['elements']['#children'];
888

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

891
892
893
  $variables['template_files'][] = 'block-' . $variables['block']->region;
  $variables['template_files'][] = 'block-' . $variables['block']->module;
  $variables['template_files'][] = 'block-' . $variables['block']->module . '-' . $variables['block']->delta;
894
}
895

896
897
898
899
900
901
902
903
904
905
906
/**
 * 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();
}

907
908
909
/**
 * Implement hook_filter_format_delete().
 */
910
function block_filter_format_delete($format, $fallback) {
911
  db_update('block_custom')
912
    ->fields(array('format' => $fallback->format))
913
914
915
916
    ->condition('format', $format->format)
    ->execute();
}

917
918
919
920
921
922
923
924
925
926
927
928
929
930
/**
 * 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();
}

931
932
933
934
935
936
937
938
939
940
941
942
943
944
/**
 * 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,
  );
}