block.module 36.5 KB
Newer Older
Dries's avatar
   
Dries committed
1
<?php
Dries's avatar
   
Dries committed
2

Dries's avatar
   
Dries committed
3
4
/**
 * @file
5
 * Controls the visual building blocks a page is constructed with.
Dries's avatar
   
Dries committed
6
7
 */

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

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
 * Users cannot control whether or not they see this block.
 */
define('BLOCK_CUSTOM_FIXED', 0);

/**
 *  Show this block by default, but let individual users hide it.
 */
define('BLOCK_CUSTOM_ENABLED', 1);

/**
 * Hide this block by default but let individual users show it.
 */
define('BLOCK_CUSTOM_DISABLED', 2);

/**
 * Show this block on every page except the listed pages.
 */
define('BLOCK_VISIBILITY_NOTLISTED', 0);

/**
 * Show this block on only the listed pages.
 */
define('BLOCK_VISIBILITY_LISTED', 1);

/**
 * Show this block if the associated PHP code returns TRUE.
 */
define('BLOCK_VISIBILITY_PHP', 2);

Dries's avatar
   
Dries committed
43
/**
44
 * Implements hook_help().
Dries's avatar
   
Dries committed
45
 */
46
47
function block_help($path, $arg) {
  switch ($path) {
Dries's avatar
   
Dries committed
48
    case 'admin/help#block':
49
      $output = '';
50
      $output .= '<h3>' . t('About') . '</h3>';
51
      $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>';
52
53
54
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Positioning content') . '</dt>';
55
      $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>';
56
57
58
      $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>';
59
      $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>';
60
      $output .= '</dl>';
61
      return $output;
62
    case 'admin/structure/block/add':
63
      return '<p>' . t('Use this page to create a new custom block.') . '</p>';
Dries's avatar
   
Dries committed
64
  }
65
  if ($arg[0] == 'admin' && $arg[1] == 'structure' && $arg['2'] == 'block' && (empty($arg[3]) || $arg[3] == 'list')) {
66
    $demo_theme = !empty($arg[4]) ? $arg[4] : variable_get('theme_default', 'bartik');
67
68
69
70
71
    $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
72
73
}

74
/**
75
 * Implements hook_theme().
76
77
78
 */
function block_theme() {
  return array(
79
    'block' => array(
80
      'render element' => 'elements',
81
      'template' => 'block',
82
    ),
83
84
    'block_admin_display_form' => array(
      'template' => 'block-admin-display-form',
85
      'file' => 'block.admin.inc',
86
      'render element' => 'form',
87
88
89
90
    ),
  );
}

Dries's avatar
   
Dries committed
91
/**
92
 * Implements hook_permission().
Dries's avatar
   
Dries committed
93
 */
94
function block_permission() {
95
  return array(
96
97
98
    'administer blocks' => array(
      'title' => t('Administer blocks'),
    ),
99
  );
Dries's avatar
   
Dries committed
100
101
}

Dries's avatar
   
Dries committed
102
/**
103
 * Implements hook_menu().
Dries's avatar
   
Dries committed
104
 */
105
function block_menu() {
106
  $default_theme = variable_get('theme_default', 'bartik');
107
  $items['admin/structure/block'] = array(
108
109
    'title' => 'Blocks',
    'description' => 'Configure what block content appears in your site\'s sidebars and other regions.',
110
    'page callback' => 'block_admin_display',
111
    'page arguments' => array($default_theme),
112
    'access arguments' => array('administer blocks'),
113
    'file' => 'block.admin.inc',
114
  );
115
  $items['admin/structure/block/manage/%/%'] = array(
116
    'title' => 'Configure block',
117
    'page callback' => 'drupal_get_form',
118
    'page arguments' => array('block_admin_configure', 4, 5),
119
    'access arguments' => array('administer blocks'),
120
    'file' => 'block.admin.inc',
121
  );
122
  $items['admin/structure/block/manage/%/%/configure'] = array(
123
124
125
126
    'title' => 'Configure block',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'context' => MENU_CONTEXT_INLINE,
  );
127
  $items['admin/structure/block/manage/%/%/delete'] = array(
128
    'title' => 'Delete block',
129
    'page callback' => 'drupal_get_form',
130
    'page arguments' => array('block_custom_block_delete', 4, 5),
131
    'access arguments' => array('administer blocks'),
132
133
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_NONE,
134
    'file' => 'block.admin.inc',
135
  );
136
  $items['admin/structure/block/add'] = array(
137
    'title' => 'Add block',
138
    'page callback' => 'drupal_get_form',
139
    'page arguments' => array('block_add_block_form'),
140
    'access arguments' => array('administer blocks'),
141
    'type' => MENU_LOCAL_ACTION,
142
    'file' => 'block.admin.inc',
143
144
  );
  foreach (list_themes() as $key => $theme) {
145
    $items['admin/structure/block/list/' . $key] = array(
146
147
      'title' => check_plain($theme->info['name']),
      'page arguments' => array($key),
148
149
150
      'type' => $key == $default_theme ? MENU_DEFAULT_LOCAL_TASK : MENU_LOCAL_TASK,
      'weight' => $key == $default_theme ? -10 : 0,
      'access callback' => '_block_themes_access',
151
      'access arguments' => array($key),
152
153
      'file' => 'block.admin.inc',
    );
154
155
156
157
158
159
160
161
162
163
    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',
      );
    }
164
165
166
167
168
    $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,
169
      'access callback' => '_block_themes_access',
170
      'access arguments' => array($key),
171
172
      'theme callback' => '_block_custom_theme',
      'theme arguments' => array($key),
173
      'file' => 'block.admin.inc',
174
    );
Dries's avatar
   
Dries committed
175
  }
Dries's avatar
   
Dries committed
176
  return $items;
Dries's avatar
   
Dries committed
177
178
}

179
/**
180
 * Menu item access callback - only admin or enabled themes can be accessed.
181
182
 */
function _block_themes_access($theme) {
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
  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;
200
201
}

Dries's avatar
   
Dries committed
202
/**
203
 * Implements hook_block_info().
Dries's avatar
   
Dries committed
204
 */
205
function block_block_info() {
206
  $blocks = array();
207

208
  $result = db_query('SELECT bid, info FROM {block_custom} ORDER BY info');
209
  foreach ($result as $block) {
210
211
    $blocks[$block->bid]['info'] = $block->info;
    // Not worth caching.
212
    $blocks[$block->bid]['cache'] = DRUPAL_NO_CACHE;
213
214
215
  }
  return $blocks;
}
216

217
/**
218
 * Implements hook_block_configure().
219
 */
220
function block_block_configure($delta = 0) {
221
  if ($delta) {
222
    $custom_block = block_custom_block_get($delta);
223
  }
224
225
226
  else {
    $custom_block = array();
  }
227
  return block_custom_block_form($custom_block);
228
229
}

230
/**
231
 * Implements hook_block_save().
232
233
 */
function block_block_save($delta = 0, $edit = array()) {
234
  block_custom_block_save($edit, $delta);
235
236
237
}

/**
238
 * Implements hook_block_view().
239
240
241
 *
 * Generates the administrator-defined blocks for display.
 */
242
function block_block_view($delta = '') {
243
244
245
  $block = db_query('SELECT body, format FROM {block_custom} WHERE bid = :bid', array(':bid' => $delta))->fetchObject();
  $data['subject'] = NULL;
  $data['content'] = check_markup($block->body, $block->format, '', TRUE);
246
247
248
  return $data;
}

249
/**
250
 * Implements hook_page_build().
251
252
253
 *
 * Render blocks into their regions.
 */
254
function block_page_build(&$page) {
255
256
257
  global $theme;

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

260
  // Fetch a list of regions for the current theme.
261
  $all_regions = system_region_list($theme);
262

263
264
265
266
267
268
269
270
  $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;
      }
271
    }
272
273
274
275
276
277
278
279
280
    // 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');
281
282
283
  }
  else {
    // Append region description if we are rendering the regions demo page.
284
    $item = menu_get_item();
285
286
287
    if ($item['path'] == 'admin/structure/block/demo/' . $theme) {
      $visible_regions = array_keys(system_region_list($theme, REGIONS_VISIBLE));
      foreach ($visible_regions as $region) {
288
289
290
291
292
        $description = '<div class="block-region">' . $all_regions[$region] . '</div>';
        $page[$region]['block_description'] = array(
          '#markup' => $description,
          '#weight' => 15,
        );
293
      }
294
295
296
      $page['page_top']['backlink'] = array(
        '#type' => 'link',
        '#title' => t('Exit block region demonstration'),
297
        '#href' => 'admin/structure/block' . (variable_get('theme_default', 'bartik') == $theme ? '' : '/list/' . $theme),
298
299
300
301
302
        // Add the "overlay-restore" class to indicate this link should restore
        // the context in which the region demonstration page was opened.
        '#options' => array('attributes' => array('class' => array('block-demo-backlink', 'overlay-restore'))),
        '#weight' => -10,
      );
303
304
305
306
307
308
309
310
311
312
313
314
315
    }
  }
}

/**
 * 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)) {
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
    $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);
335

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

345
346
347
348
349
    $build[$key] += array(
      '#block' => $block,
      '#weight' => ++$weight,
    );
    $build[$key]['#theme_wrappers'][] ='block';
350
  }
351
  $build['#sorted'] = TRUE;
352
353
354
  return $build;
}

Dries's avatar
   
Dries committed
355
/**
356
 * Update the 'block' DB table with the blocks currently exported by modules.
Dries's avatar
   
Dries committed
357
 *
358
 * @param $theme
359
360
 *   The theme to rehash blocks for. If not provided, defaults to the currently
 *   used theme.
361
 *
Dries's avatar
   
Dries committed
362
 * @return
363
 *   Blocks currently exported by modules.
Dries's avatar
   
Dries committed
364
 */
365
function _block_rehash($theme = NULL) {
366
  global $theme_key;
367

368
  drupal_theme_initialize();
369
370
371
372
373
  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
374

375
376
377
378
379
380
381
382
  // 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.
383
384
  foreach (module_implements('block_info') as $module) {
    $module_blocks = module_invoke($module, 'block_info');
385
386
387
388
389
390
391
392
393
394
395
    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
396
397
    }
  }
398
399
400
401
402
403
404
405
406
407
  // 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'];
408
409
410
411
412
    // 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'];
    }
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
    // 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
443
      // because the 'title' attribute is saved to the {blocks} table.
444
445
446
447
448
449
450
451
452
453
454
455
456
457
      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;
458
    }
459
  }
460
461
462
463
464
465
466
467
  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
468
469
  return $blocks;
}
Dries's avatar
   
Dries committed
470

471
472
473
474
475
476
477
478
479
480
481
482
483
/**
 * 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.
 */
484
485
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
486
487
}

488
489
490
/**
 * Define the custom block form.
 */
491
function block_custom_block_form($edit = array()) {
492
493
494
495
  $edit += array(
    'info' => '',
    'body' => '',
  );
496
497
498
  $form['info'] = array(
    '#type' => 'textfield',
    '#title' => t('Block description'),
499
    '#default_value' => $edit['info'],
500
    '#maxlength' => 64,
501
    '#description' => t('A brief description of your block. Used on the <a href="@overview">Blocks administration page</a>.', array('@overview' => url('admin/structure/block'))),
502
    '#required' => TRUE,
503
    '#weight' => -18,
504
  );
505
506
  $form['body_field']['#weight'] = -17;
  $form['body_field']['body'] = array(
507
    '#type' => 'text_format',
508
    '#title' => t('Block body'),
509
    '#default_value' => $edit['body'],
510
    '#format' => isset($edit['format']) ? $edit['format'] : NULL,
511
512
    '#rows' => 15,
    '#description' => t('The content of the block as shown to the user.'),
513
    '#required' => TRUE,
514
515
    '#weight' => -17,
  );
516

517
  return $form;
518
519
}

520
521
522
523
524
525
/**
 * Saves a user-created block in the database.
 *
 * @param $edit
 *   Associative array of fields to save. Array keys:
 *   - info: Block description.
526
527
528
 *   - body: Associative array of body value and format.  Array keys:
 *     - value: Block contents.
 *     - format: Filter ID of the filter format for the body.
529
530
531
532
533
 * @param $delta
 *   Block ID of the block to save.
 * @return
 *   Always returns TRUE.
 */
534
535
function block_custom_block_save($edit, $delta) {
  db_update('block_custom')
536
    ->fields(array(
537
      'body' => $edit['body']['value'],
538
      'info' => $edit['info'],
539
      'format' => $edit['body']['format'],
540
541
542
    ))
    ->condition('bid', $delta)
    ->execute();
543
  return TRUE;
544
545
}

Dries's avatar
   
Dries committed
546
/**
547
 * Implements hook_form_FORM_ID_alter().
Dries's avatar
   
Dries committed
548
 */
549
550
551
function block_form_user_profile_form_alter(&$form, &$form_state) {
  if ($form['#user_category'] == 'account') {
    $account = $form['#user'];
552
    $rids = array_keys($account->roles);
553
    $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));
554
555

    $blocks = array();
556
    foreach ($result as $block) {
557
      $data = module_invoke($block->module, 'block_info');
558
      if ($data[$block->delta]['info']) {
559
        $blocks[$block->module][$block->delta] = array(
560
561
          '#type' => 'checkbox',
          '#title' => check_plain($data[$block->delta]['info']),
562
          '#default_value' => isset($account->data['block'][$block->module][$block->delta]) ? $account->data['block'][$block->module][$block->delta] : ($block->custom == 1),
563
        );
564
      }
565
    }
566
567
568
569
570
571
572
573
574
575
576
    // 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;
577
578
579
580
    }
  }
}

581
582
583
584
585
586
587
588
589
/**
 * Implements hook_user_presave().
 */
function block_user_presave(&$edit, $account, $category) {
  if (isset($edit['block'])) {
    $edit['data']['block'] = $edit['block'];
  }
}

590
591
592
/**
 * Initialize blocks for enabled themes.
 */
593
594
595
function block_themes_enabled($theme_list) {
  foreach ($theme_list as $theme) {
    block_theme_initialize($theme);
596
597
598
599
600
  }
}

/**
 * Assign an initial, default set of blocks for a theme.
601
 *
602
603
604
605
 * 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.
606
 *
607
608
609
 * @param $theme
 *   The name of a theme.
 */
610
function block_theme_initialize($theme) {
611
  // Initialize theme's blocks if none already registered.
612
  $has_blocks = (bool) db_query_range('SELECT 1 FROM {block} WHERE theme = :theme', 0, 1, array(':theme' => $theme))->fetchField();
613
  if (!$has_blocks) {
614
    $default_theme = variable_get('theme_default', 'bartik');
615
616
    // Apply only to new theme's visible regions.
    $regions = system_region_list($theme, REGIONS_VISIBLE);
617
618
    $result = db_query("SELECT * FROM {block} WHERE theme = :theme", array(':theme' => $default_theme), array('fetch' => PDO::FETCH_ASSOC));
    foreach ($result as $block) {
619
      // If the region isn't supported by the theme, assign the block to the theme's default region.
620
      if ($block['status'] && !isset($regions[$block['region']])) {
621
622
        $block['region'] = system_default_region($theme);
      }
623
      $block['theme'] = $theme;
624
625
      unset($block['bid']);
      drupal_write_record('block', $block);
626
627
628
629
    }
  }
}

630
631
632
633
634
635
636
/**
 * Return all blocks in the specified region for the current user.
 *
 * @param $region
 *   The name of a region.
 *
 * @return
637
638
639
640
 *   An array of block objects, indexed with the module name and block delta
 *   concatenated with an underscore, thus: MODULE_DELTA. If you are displaying
 *   your blocks in one or two sidebars, you may check whether this array is
 *   empty to see how many columns are going to be displayed.
641
642
 *
 * @todo
643
 *   Now that the blocks table has a primary key, we should use that as the
644
 *   array key instead of MODULE_DELTA.
645
646
 */
function block_list($region) {
647
  $blocks = &drupal_static(__FUNCTION__);
648

649
  if (!isset($blocks)) {
650
651
652
    $blocks = _block_load_blocks();
  }

653
  // Create an empty array if there are no entries.
654
655
656
  if (!isset($blocks[$region])) {
    $blocks[$region] = array();
  }
657
658
659
  else {
    $blocks[$region] = _block_render_blocks($blocks[$region]);
  }
660
661
662
663

  return $blocks[$region];
}

664
665
666
667
668
669
/**
 * Load a block object from the database.
 *
 * @param $module
 *   Name of the module that implements the block to load.
 * @param $delta
670
671
 *   Unique ID of the block within the context of $module. Pass NULL to return
 *   an empty $block object for $module.
672
673
674
675
676
 *
 * @return
 *   A block object.
 */
function block_load($module, $delta) {
677
678
679
  if (isset($delta)) {
    $block = db_query('SELECT * FROM {block} WHERE module = :module AND delta = :delta', array(':module' => $module, ':delta' => $delta))->fetchObject();
  }
680
681
682

  // If the block does not exist in the database yet return a stub block
  // object.
683
  if (empty($block)) {
684
    $block = new stdClass();
685
686
687
688
689
690
691
    $block->module = $module;
    $block->delta = $delta;
  }

  return $block;
}

692
/**
693
 * Load blocks information from the database.
694
695
 */
function _block_load_blocks() {
696
  global $theme_key;
697

698
699
700
701
702
703
704
705
706
  $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')
707
    ->addTag('translatable')
708
    ->execute();
709

710
  $block_info = $result->fetchAllAssoc('bid');
711
  // Allow modules to modify the block list.
712
  drupal_alter('block_list', $block_info);
713
714

  $blocks = array();
715
  foreach ($block_info as $block) {
716
717
718
719
720
721
    $blocks[$block->region]["{$block->module}_{$block->delta}"] = $block;
  }
  return $blocks;
}

/**
722
 * Implements hook_block_list_alter().
723
 *
724
 * Check the page, user role and user specific visibilty settings.
725
 * Remove the block if the visibility conditions are not met.
726
 */
727
function block_block_list_alter(&$blocks) {
728
729
730
731
732
733
734
735
736
737
  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) {
738
    if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
739
740
      // This block was added by a contrib module, leave it in the list.
      continue;
741
    }
742
743
744
745

    // 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.
746
    if (isset($block_roles[$block->module][$block->delta]) && !array_intersect($block_roles[$block->module][$block->delta], array_keys($user->roles))) {
747
748
749
      // No match.
      unset($blocks[$key]);
      continue;
750
751
    }

752
    // Use the user's block visibility setting, if necessary.
753
    if ($block->custom != BLOCK_CUSTOM_FIXED) {
754
755
      if ($user->uid && isset($user->data['block'][$block->module][$block->delta])) {
        $enabled = $user->data['block'][$block->module][$block->delta];
756
757
      }
      else {
758
        $enabled = ($block->custom == BLOCK_CUSTOM_ENABLED);
759
      }
760
761
762
763
    }
    else {
      $enabled = TRUE;
    }
764
765
766
767
768
769

    // Limited visibility blocks must list at least one page.
    if ($block->visibility == BLOCK_VISIBILITY_LISTED && empty($block->pages)) {
      $enabled = FALSE;
    }

770
771
772
773
    if (!$enabled) {
      unset($blocks[$key]);
      continue;
    }
774

775
    // Match path if necessary.
776
    if ($block->pages) {
777
778
779
      // Convert path to lowercase. This allows comparison of the same path
      // with different case. Ex: /Page, /page, /PAGE.
      $pages = drupal_strtolower($block->pages);
780
      if ($block->visibility < BLOCK_VISIBILITY_PHP) {
781
782
783
784
        // 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);
785
        if ($path != $_GET['q']) {
786
          $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
787
        }
788
789
790
791
        // When $block->visibility has a value of 0 (BLOCK_VISIBILITY_NOTLISTED),
        // the block is displayed on all pages except those listed in $block->pages.
        // When set to 1 (BLOCK_VISIBILITY_LISTED), it is displayed only on those
        // pages listed in $block->pages.
792
        $page_match = !($block->visibility xor $page_match);
793
      }
794
795
796
      elseif (module_exists('php')) {
        $page_match = php_eval($block->pages);
      }
797
      else {
798
        $page_match = FALSE;
799
      }
800
801
802
803
    }
    else {
      $page_match = TRUE;
    }
804
805
806
    if (!$page_match) {
      unset($blocks[$key]);
    }
807
808
  }
}
809

810
811
812
813
/**
 * Render the content and subject for a set of blocks.
 *
 * @param $region_blocks
814
 *   An array of block objects such as returned for one region by _block_load_blocks().
815
816
 *
 * @return
817
 *   An array of visible blocks as expected by drupal_render().
818
819
820
821
822
 */
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)) {
823
824
      // Erase the block from the static array - we'll put it back if it has
      // content.
825
      unset($region_blocks[$key]);
826
827
828
829
      // 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').
830
      if (!count(module_implements('node_grants')) && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD') && ($cid = _block_get_cache_id($block)) && ($cache = cache('block')->get($cid))) {
831
832
833
834
        $array = $cache->data;
      }
      else {
        $array = module_invoke($block->module, 'block_view', $block->delta);
835
836

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

840
        if (isset($cid)) {
841
          cache('block')->set($cid, $array, CACHE_TEMPORARY);
842
        }
843
      }
844

845
846
847
      if (isset($array) && is_array($array)) {
        foreach ($array as $k => $v) {
          $block->$k = $v;
Dries's avatar
   
Dries committed
848
        }
849
850
      }
      if (isset($block->content) && $block->content) {
851
        // Normalize to the drupal_render() structure.
852
853
854
        if (is_string($block->content)) {
          $block->content = array('#markup' => $block->content);
        }
855
856
857
858
859
860
861
862
        // 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 = '';
863
        }
864
        $region_blocks["{$block->module}_{$block->delta}"] = $block;
865
866
867
      }
    }
  }
868
  return $region_blocks;
869
}
870
871
872
873
874
875
876
877
878
879

/**
 * 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.
 *
880
 * Theme and language contexts are automatically differentiated.
881
882
883
884
885
886
 *
 * @param $block
 * @return
 *   The string used as cache_id for the block.
 */
function _block_get_cache_id($block) {
887
  global $user;
888

889
890
891
892
  // 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.
893
  if (variable_get('block_cache', FALSE) && !in_array($block->cache, array(DRUPAL_NO_CACHE, DRUPAL_CACHE_CUSTOM)) && $user->uid != 1) {
894
895
896
    // Start with common sub-patterns: block identification, theme, language.
    $cid_parts[] = $block->module;
    $cid_parts[] = $block->delta;
897
    $cid_parts = array_merge($cid_parts, drupal_render_cid_parts($block->cache));
898
899
900

    return implode(':', $cid_parts);
  }
901
}
902
903

/**
904
 * Implements hook_flush_caches().
905
906
 */
function block_flush_caches() {
907
908
909
910
911
912
913
914
  // 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);
  }

915
  return array('block');
916
}
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935

/**
 * 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) {
936
  $block_counter = &drupal_static(__FUNCTION__, array());
937
  $variables['block'] = $variables['elements']['#block'];
938
939
940
941
942
943
944
945
  // 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]++;

946
947
  // Create the $content variable that templates expect.
  $variables['content'] = $variables['elements']['#children'];
948

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

951
952
  $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->region;
  $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->module;
953
954
955
  // Hyphens (-) and underscores (_) play a special role in theme suggestions.
  // Theme suggestions should only contain underscores, because within
  // drupal_find_theme_templates(), underscores are converted to hyphens to
956
  // match template file names, and then converted back to underscores to match
957
958
959
960
961
  // pre-processing and other function names. So if your theme suggestion
  // contains a hyphen, it will end up as an underscore after this conversion,
  // and your function names won't be recognized. So, we need to convert
  // hyphens to underscores in block deltas for the theme suggestions.
  $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->module . '__' . strtr($variables['block']->delta, '-', '_');
962
963
964

  // 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);
965
}
966

967
/**
968
 * Implements hook_user_role_delete().
969
 *
970
 * Remove deleted role from blocks that use it.
971
972
973
974
975
976
977
 */
function block_user_role_delete($role) {
  db_delete('block_role')
    ->condition('rid', $role->rid)
    ->execute();
}

978
/**
979
 * Implements hook_menu_delete().
980
981
982
983
984
985
986
987
988
989
990
991
 */
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();
}

992
/**
993
 * Implements hook_form_FORM_ID_alter().
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
 */
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,
  );
}
1006

1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
/**