Projet

Général

Profil

Paste
Télécharger (39,1 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / block / block.module @ 30d5b9c5

1
<?php
2

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

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

    
13
/**
14
 * Users cannot control whether or not they see this block.
15
 */
16
define('BLOCK_CUSTOM_FIXED', 0);
17

    
18
/**
19
 * Shows this block by default, but lets individual users hide it.
20
 */
21
define('BLOCK_CUSTOM_ENABLED', 1);
22

    
23
/**
24
 * Hides this block by default but lets individual users show it.
25
 */
26
define('BLOCK_CUSTOM_DISABLED', 2);
27

    
28
/**
29
 * Shows this block on every page except the listed pages.
30
 */
31
define('BLOCK_VISIBILITY_NOTLISTED', 0);
32

    
33
/**
34
 * Shows this block on only the listed pages.
35
 */
36
define('BLOCK_VISIBILITY_LISTED', 1);
37

    
38
/**
39
 * Shows this block if the associated PHP code returns TRUE.
40
 */
41
define('BLOCK_VISIBILITY_PHP', 2);
42

    
43
/**
44
 * Implements hook_help().
45
 */
46
function block_help($path, $arg) {
47
  switch ($path) {
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/documentation/modules/block/', '@blocks' => url('admin/structure/block'))) . '</p>';
52
      $output .= '<h3>' . t('Uses') . '</h3>';
53
      $output .= '<dl>';
54
      $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/documentation/modules/block/', '@blocks' => url('admin/structure/block'))) . '</dd>';
56
      $output .= '<dt>' . t('Controlling visibility') . '</dt>';
57
      $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>';
58
      $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

    
63
    case 'admin/structure/block/add':
64
      return '<p>' . t('Use this page to create a new custom block.') . '</p>';
65
  }
66
  if ($arg[0] == 'admin' && $arg[1] == 'structure' && $arg['2'] == 'block' && (empty($arg[3]) || $arg[3] == 'list')) {
67
    $demo_theme = !empty($arg[4]) ? $arg[4] : variable_get('theme_default', 'bartik');
68
    $themes = list_themes();
69
    $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>';
70
    $output .= '<p>' . l(t('Demonstrate block regions (!theme)', array('!theme' => $themes[$demo_theme]->info['name'])), 'admin/structure/block/demo/' . $demo_theme) . '</p>';
71
    return $output;
72
  }
73
}
74

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

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

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

    
180
/**
181
 * Menu item access callback - only admin or enabled themes can be accessed.
182
 */
183
function _block_themes_access($theme) {
184
  return user_access('administer blocks') && drupal_theme_access($theme);
185
}
186

    
187
/**
188
 * Theme callback for the block configuration pages.
189
 *
190
 * @param $theme
191
 *   The theme whose blocks are being configured. If not set, the default theme
192
 *   is assumed.
193
 *
194
 * @return
195
 *   The theme that should be used for the block configuration page, or NULL
196
 *   to indicate that the default theme should be used.
197
 */
198
function _block_custom_theme($theme = NULL) {
199
  // We return exactly what was passed in, to guarantee that the page will
200
  // always be displayed using the theme whose blocks are being configured.
201
  return $theme;
202
}
203

    
204
/**
205
 * Implements hook_block_info().
206
 */
207
function block_block_info() {
208
  $blocks = array();
209

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

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

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

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

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

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

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

    
265
  $item = menu_get_item();
266
  if ($item['path'] != 'admin/structure/block/demo/' . $theme) {
267
    // Load all region content assigned via blocks.
268
    foreach (array_keys($all_regions) as $region) {
269
      // Assign blocks to region.
270
      if ($blocks = block_get_blocks_by_region($region)) {
271
        $page[$region] = $blocks;
272
      }
273
    }
274
    // Once we've finished attaching all blocks to the page, clear the static
275
    // cache to allow modules to alter the block list differently in different
276
    // contexts. For example, any code that triggers hook_page_build() more
277
    // than once in the same page request may need to alter the block list
278
    // differently each time, so that only certain parts of the page are
279
    // actually built. We do not clear the cache any earlier than this, though,
280
    // because it is used each time block_get_blocks_by_region() gets called
281
    // above.
282
    drupal_static_reset('block_list');
283
  }
284
  else {
285
    // Append region description if we are rendering the regions demo page.
286
    $item = menu_get_item();
287
    if ($item['path'] == 'admin/structure/block/demo/' . $theme) {
288
      $visible_regions = array_keys(system_region_list($theme, REGIONS_VISIBLE));
289
      foreach ($visible_regions as $region) {
290
        $description = '<div class="block-region">' . $all_regions[$region] . '</div>';
291
        $page[$region]['block_description'] = array(
292
          '#markup' => $description,
293
          '#weight' => 15,
294
        );
295
      }
296
      $page['page_top']['backlink'] = array(
297
        '#type' => 'link',
298
        '#title' => t('Exit block region demonstration'),
299
        '#href' => 'admin/structure/block' . (variable_get('theme_default', 'bartik') == $theme ? '' : '/list/' . $theme),
300
        // Add the "overlay-restore" class to indicate this link should restore
301
        // the context in which the region demonstration page was opened.
302
        '#options' => array('attributes' => array('class' => array('block-demo-backlink', 'overlay-restore'))),
303
        '#weight' => -10,
304
      );
305
    }
306
  }
307
}
308

    
309
/**
310
 * Gets a renderable array of a region containing all enabled blocks.
311
 *
312
 * @param $region
313
 *   The requested region.
314
 *
315
 * @return
316
 *   A renderable array of a region containing all enabled blocks.
317
 */
318
function block_get_blocks_by_region($region) {
319
  $build = array();
320
  if ($list = block_list($region)) {
321
    $build = _block_get_renderable_array($list);
322
  }
323
  return $build;
324
}
325

    
326
/**
327
 * Gets an array of blocks suitable for drupal_render().
328
 *
329
 * @param $list
330
 *   A list of blocks such as that returned by block_list().
331
 *
332
 * @return
333
 *   A renderable array.
334
 */
335
function _block_get_renderable_array($list = array()) {
336
  $weight = 0;
337
  $build = array();
338
  foreach ($list as $key => $block) {
339
    $build[$key] = $block->content;
340
    unset($block->content);
341

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

    
354
    $build[$key] += array(
355
      '#block' => $block,
356
      '#weight' => ++$weight,
357
    );
358
    $build[$key]['#theme_wrappers'][] = 'block';
359
  }
360
  $build['#sorted'] = TRUE;
361
  return $build;
362
}
363

    
364
/**
365
 * Updates the 'block' DB table with the blocks currently exported by modules.
366
 *
367
 * @param $theme
368
 *   The theme to rehash blocks for. If not provided, defaults to the currently
369
 *   used theme.
370
 *
371
 * @return
372
 *   Blocks currently exported by modules.
373
 */
374
function _block_rehash($theme = NULL) {
375
  global $theme_key;
376

    
377
  drupal_theme_initialize();
378
  if (!isset($theme)) {
379
    // If theme is not specifically set, rehash for the current theme.
380
    $theme = $theme_key;
381
  }
382
  $regions = system_region_list($theme);
383

    
384
  // These are the blocks the function will return.
385
  $blocks = array();
386
  // These are the blocks defined by code and modified by the database.
387
  $current_blocks = array();
388
  // These are {block}.bid values to be kept.
389
  $bids = array();
390
  $or = db_or();
391
  // Gather the blocks defined by modules.
392
  foreach (module_implements('block_info') as $module) {
393
    $module_blocks = module_invoke($module, 'block_info');
394
    $delta_list = array();
395
    foreach ($module_blocks as $delta => $block) {
396
      // Compile a condition to retrieve this block from the database.
397
      // Add identifiers.
398
      $delta_list[] = $delta;
399
      $block['module'] = $module;
400
      $block['delta'] = $delta;
401
      $block['theme'] = $theme;
402
      $current_blocks[$module][$delta] = $block;
403
    }
404
    if (!empty($delta_list)) {
405
      $condition = db_and()->condition('module', $module)->condition('delta', $delta_list);
406
      $or->condition($condition);
407
    }
408
  }
409
  // Save the blocks defined in code for alter context.
410
  $code_blocks = $current_blocks;
411
  $database_blocks = db_select('block', 'b', array('fetch' => PDO::FETCH_ASSOC))
412
    ->fields('b')
413
    ->condition($or)
414
    ->condition('theme', $theme)
415
    ->execute();
416
  $original_database_blocks = array();
417
  foreach ($database_blocks as $block) {
418
    $module = $block['module'];
419
    $delta = $block['delta'];
420
    $original_database_blocks[$module][$delta] = $block;
421
    // The cache mode can only by set from hook_block_info(), so that has
422
    // precedence over the database's value.
423
    if (isset($current_blocks[$module][$delta]['cache'])) {
424
      $block['cache'] = $current_blocks[$module][$delta]['cache'];
425
    }
426
    // Preserve info which is not in the database.
427
    $block['info'] = $current_blocks[$module][$delta]['info'];
428
    // Blocks stored in the database override the blocks defined in code.
429
    $current_blocks[$module][$delta] = $block;
430
    // Preserve this block.
431
    $bids[$block['bid']] = $block['bid'];
432
  }
433
  drupal_alter('block_info', $current_blocks, $theme, $code_blocks);
434
  foreach ($current_blocks as $module => $module_blocks) {
435
    foreach ($module_blocks as $delta => $block) {
436
      if (!isset($block['pages'])) {
437
        // {block}.pages is type 'text', so it cannot have a
438
        // default value, and not null, so we need to provide
439
        // value if the module did not.
440
        $block['pages']  = '';
441
      }
442
      // Make sure weight is set.
443
      if (!isset($block['weight'])) {
444
        $block['weight'] = 0;
445
      }
446
      if (!empty($block['region']) && $block['region'] != BLOCK_REGION_NONE && !isset($regions[$block['region']]) && $block['status'] == 1) {
447
        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');
448
        // Disabled modules are moved into the BLOCK_REGION_NONE later so no
449
        // need to move the block to another region.
450
        $block['status'] = 0;
451
      }
452
      // Set region to none if not enabled and make sure status is set.
453
      if (empty($block['status'])) {
454
        $block['status'] = 0;
455
        $block['region'] = BLOCK_REGION_NONE;
456
      }
457
      // There is no point saving disabled blocks. Still, we need to save them
458
      // because the 'title' attribute is saved to the {blocks} table.
459
      if (isset($block['bid'])) {
460
        // If the block has a bid property, it comes from the database and
461
        // the record needs to be updated, so set the primary key to 'bid'
462
        // before passing to drupal_write_record().
463
        $primary_keys = array('bid');
464
        // Remove a block from the list of blocks to keep if it became disabled.
465
        unset($bids[$block['bid']]);
466
      }
467
      else {
468
        $primary_keys = array();
469
      }
470
      // If the block is new or differs from the original database block, save
471
      // it. To determine whether there was a change it is enough to examine
472
      // the values for the keys in the original database record as that
473
      // contained every database field.
474
      if (!$primary_keys || array_diff_assoc($original_database_blocks[$module][$delta], $block)) {
475
        drupal_write_record('block', $block, $primary_keys);
476
        // Make it possible to test this.
477
        $block['saved'] = TRUE;
478
      }
479
      // Add to the list of blocks we return.
480
      $blocks[] = $block;
481
    }
482
  }
483
  if ($bids) {
484
    // Remove disabled that are no longer defined by the code from the
485
    // database.
486
    db_delete('block')
487
      ->condition('bid', $bids, 'NOT IN')
488
      ->condition('theme', $theme)
489
      ->execute();
490
  }
491
  return $blocks;
492
}
493

    
494
/**
495
 * Returns information from database about a user-created (custom) block.
496
 *
497
 * @param $bid
498
 *   ID of the block to get information for.
499
 *
500
 * @return
501
 *   Associative array of information stored in the database for this block.
502
 *   Array keys:
503
 *   - bid: Block ID.
504
 *   - info: Block description.
505
 *   - body: Block contents.
506
 *   - format: Filter ID of the filter format for the body.
507
 */
508
function block_custom_block_get($bid) {
509
  return db_query("SELECT * FROM {block_custom} WHERE bid = :bid", array(':bid' => $bid))->fetchAssoc();
510
}
511

    
512
/**
513
 * Form constructor for the custom block form.
514
 *
515
 * @param $edit
516
 *   (optional) An associative array of information retrieved by
517
 *   block_custom_get_block() if an existing block is being edited, or an empty
518
 *   array otherwise. Defaults to array().
519
 *
520
 * @ingroup forms
521
 */
522
function block_custom_block_form($edit = array()) {
523
  $edit += array(
524
    'info' => '',
525
    'body' => '',
526
  );
527
  $form['info'] = array(
528
    '#type' => 'textfield',
529
    '#title' => t('Block description'),
530
    '#default_value' => $edit['info'],
531
    '#maxlength' => 64,
532
    '#description' => t('A brief description of your block. Used on the <a href="@overview">Blocks administration page</a>.', array('@overview' => url('admin/structure/block'))),
533
    '#required' => TRUE,
534
    '#weight' => -18,
535
  );
536
  $form['body_field']['#weight'] = -17;
537
  $form['body_field']['body'] = array(
538
    '#type' => 'text_format',
539
    '#title' => t('Block body'),
540
    '#default_value' => $edit['body'],
541
    '#format' => isset($edit['format']) ? $edit['format'] : NULL,
542
    '#rows' => 15,
543
    '#description' => t('The content of the block as shown to the user.'),
544
    '#required' => TRUE,
545
    '#weight' => -17,
546
  );
547

    
548
  return $form;
549
}
550

    
551
/**
552
 * Saves a user-created block in the database.
553
 *
554
 * @param $edit
555
 *   Associative array of fields to save. Array keys:
556
 *   - info: Block description.
557
 *   - body: Associative array of body value and format.  Array keys:
558
 *     - value: Block contents.
559
 *     - format: Filter ID of the filter format for the body.
560
 * @param $delta
561
 *   Block ID of the block to save.
562
 *
563
 * @return
564
 *   Always returns TRUE.
565
 */
566
function block_custom_block_save($edit, $delta) {
567
  db_update('block_custom')
568
    ->fields(array(
569
      'body' => $edit['body']['value'],
570
      'info' => $edit['info'],
571
      'format' => $edit['body']['format'],
572
    ))
573
    ->condition('bid', $delta)
574
    ->execute();
575
  return TRUE;
576
}
577

    
578
/**
579
 * Implements hook_form_FORM_ID_alter() for user_profile_form().
580
 */
581
function block_form_user_profile_form_alter(&$form, &$form_state) {
582
  if ($form['#user_category'] == 'account') {
583
    $account = $form['#user'];
584
    $rids = array_keys($account->roles);
585
    $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));
586

    
587
    $blocks = array();
588
    foreach ($result as $block) {
589
      $data = module_invoke($block->module, 'block_info');
590
      if ($data[$block->delta]['info']) {
591
        $blocks[$block->module][$block->delta] = array(
592
          '#type' => 'checkbox',
593
          '#title' => check_plain($data[$block->delta]['info']),
594
          '#default_value' => isset($account->data['block'][$block->module][$block->delta]) ? $account->data['block'][$block->module][$block->delta] : ($block->custom == 1),
595
        );
596
      }
597
    }
598
    // Only display the fieldset if there are any personalizable blocks.
599
    if ($blocks) {
600
      $form['block'] = array(
601
        '#type' => 'fieldset',
602
        '#title' => t('Personalize blocks'),
603
        '#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.'),
604
        '#weight' => 3,
605
        '#collapsible' => TRUE,
606
        '#tree' => TRUE,
607
      );
608
      $form['block'] += $blocks;
609
    }
610
  }
611
}
612

    
613
/**
614
 * Implements hook_user_presave().
615
 */
616
function block_user_presave(&$edit, $account, $category) {
617
  if (isset($edit['block'])) {
618
    $edit['data']['block'] = $edit['block'];
619
  }
620
}
621

    
622
/**
623
 * Initializes blocks for enabled themes.
624
 *
625
 * @param $theme_list
626
 *   An array of theme names.
627
 */
628
function block_themes_enabled($theme_list) {
629
  foreach ($theme_list as $theme) {
630
    block_theme_initialize($theme);
631
  }
632
}
633

    
634
/**
635
 * Assigns an initial, default set of blocks for a theme.
636
 *
637
 * This function is called the first time a new theme is enabled. The new theme
638
 * gets a copy of the default theme's blocks, with the difference that if a
639
 * particular region isn't available in the new theme, the block is assigned
640
 * to the new theme's default region.
641
 *
642
 * @param $theme
643
 *   The name of a theme.
644
 */
645
function block_theme_initialize($theme) {
646
  // Initialize theme's blocks if none already registered.
647
  $has_blocks = (bool) db_query_range('SELECT 1 FROM {block} WHERE theme = :theme', 0, 1, array(':theme' => $theme))->fetchField();
648
  if (!$has_blocks) {
649
    $default_theme = variable_get('theme_default', 'bartik');
650
    // Apply only to new theme's visible regions.
651
    $regions = system_region_list($theme, REGIONS_VISIBLE);
652
    $result = db_query("SELECT * FROM {block} WHERE theme = :theme", array(':theme' => $default_theme), array('fetch' => PDO::FETCH_ASSOC));
653
    foreach ($result as $block) {
654
      // If the region isn't supported by the theme, assign the block to the
655
      // theme's default region.
656
      if ($block['status'] && !isset($regions[$block['region']])) {
657
        $block['region'] = system_default_region($theme);
658
      }
659
      $block['theme'] = $theme;
660
      unset($block['bid']);
661
      drupal_write_record('block', $block);
662
    }
663
  }
664
}
665

    
666
/**
667
 * Returns all blocks in the specified region for the current user.
668
 *
669
 * @param $region
670
 *   The name of a region.
671
 *
672
 * @return
673
 *   An array of block objects, indexed with the module name and block delta
674
 *   concatenated with an underscore, thus: MODULE_DELTA. If you are displaying
675
 *   your blocks in one or two sidebars, you may check whether this array is
676
 *   empty to see how many columns are going to be displayed.
677
 *
678
 * @todo
679
 *   Now that the block table has a primary key, we should use that as the
680
 *   array key instead of MODULE_DELTA.
681
 */
682
function block_list($region) {
683
  $blocks = &drupal_static(__FUNCTION__);
684

    
685
  if (!isset($blocks)) {
686
    $blocks = _block_load_blocks();
687
  }
688

    
689
  // Create an empty array if there are no entries.
690
  if (!isset($blocks[$region])) {
691
    $blocks[$region] = array();
692
  }
693
  else {
694
    $blocks[$region] = _block_render_blocks($blocks[$region]);
695
  }
696

    
697
  return $blocks[$region];
698
}
699

    
700
/**
701
 * Loads a block object from the database.
702
 *
703
 * This function returns the first block matching the module and delta
704
 * parameters, so it should not be used for theme-specific functionality.
705
 *
706
 * @param $module
707
 *   Name of the module that implements the block to load.
708
 * @param $delta
709
 *   Unique ID of the block within the context of $module. Pass NULL to return
710
 *   an empty block object for $module.
711
 *
712
 * @return
713
 *   A block object.
714
 */
715
function block_load($module, $delta) {
716
  if (isset($delta)) {
717
    $block = db_query('SELECT * FROM {block} WHERE module = :module AND delta = :delta', array(':module' => $module, ':delta' => $delta))->fetchObject();
718
  }
719

    
720
  // If the block does not exist in the database yet return a stub block
721
  // object.
722
  if (empty($block)) {
723
    $block = new stdClass();
724
    $block->module = $module;
725
    $block->delta = $delta;
726
  }
727

    
728
  return $block;
729
}
730

    
731
/**
732
 * Loads blocks' information from the database.
733
 *
734
 * @return
735
 *   An array of blocks grouped by region.
736
 */
737
function _block_load_blocks() {
738
  global $theme_key;
739

    
740
  $query = db_select('block', 'b');
741
  $result = $query
742
    ->fields('b')
743
    ->condition('b.theme', $theme_key)
744
    ->condition('b.status', 1)
745
    ->orderBy('b.region')
746
    ->orderBy('b.weight')
747
    ->orderBy('b.module')
748
    ->addTag('block_load')
749
    ->addTag('translatable')
750
    ->execute();
751

    
752
  $block_info = $result->fetchAllAssoc('bid');
753
  // Allow modules to modify the block list.
754
  drupal_alter('block_list', $block_info);
755

    
756
  $blocks = array();
757
  foreach ($block_info as $block) {
758
    $blocks[$block->region]["{$block->module}_{$block->delta}"] = $block;
759
  }
760
  return $blocks;
761
}
762

    
763
/**
764
 * Implements hook_block_list_alter().
765
 *
766
 * Checks the page, user role, and user-specific visibility settings.
767
 * Removes the block if the visibility conditions are not met.
768
 */
769
function block_block_list_alter(&$blocks) {
770
  global $user, $theme_key;
771

    
772
  // Build an array of roles for each block.
773
  $block_roles = array();
774
  $result = db_query('SELECT module, delta, rid FROM {block_role}');
775
  foreach ($result as $record) {
776
    $block_roles[$record->module][$record->delta][] = $record->rid;
777
  }
778

    
779
  foreach ($blocks as $key => $block) {
780
    if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
781
      // This block was added by a contrib module, leave it in the list.
782
      continue;
783
    }
784

    
785
    // If a block has no roles associated, it is displayed for every role.
786
    // For blocks with roles associated, if none of the user's roles matches
787
    // the settings from this block, remove it from the block list.
788
    if (isset($block_roles[$block->module][$block->delta]) && !array_intersect($block_roles[$block->module][$block->delta], array_keys($user->roles))) {
789
      // No match.
790
      unset($blocks[$key]);
791
      continue;
792
    }
793

    
794
    // Use the user's block visibility setting, if necessary.
795
    if ($block->custom != BLOCK_CUSTOM_FIXED) {
796
      if ($user->uid && isset($user->data['block'][$block->module][$block->delta])) {
797
        $enabled = $user->data['block'][$block->module][$block->delta];
798
      }
799
      else {
800
        $enabled = ($block->custom == BLOCK_CUSTOM_ENABLED);
801
      }
802
    }
803
    else {
804
      $enabled = TRUE;
805
    }
806

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

    
812
    if (!$enabled) {
813
      unset($blocks[$key]);
814
      continue;
815
    }
816

    
817
    // Match path if necessary.
818
    if ($block->pages) {
819
      // Convert path to lowercase. This allows comparison of the same path
820
      // with different case. Ex: /Page, /page, /PAGE.
821
      $pages = drupal_strtolower($block->pages);
822
      if ($block->visibility < BLOCK_VISIBILITY_PHP) {
823
        // Convert the Drupal path to lowercase.
824
        $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
825
        // Compare the lowercase internal and lowercase path alias (if any).
826
        $page_match = drupal_match_path($path, $pages);
827
        if ($path != $_GET['q']) {
828
          $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
829
        }
830
        // When $block->visibility has a value of 0
831
        // (BLOCK_VISIBILITY_NOTLISTED), the block is displayed on all pages
832
        // except those listed in $block->pages. When set to 1
833
        // (BLOCK_VISIBILITY_LISTED), it is displayed only on those pages
834
        // listed in $block->pages.
835
        $page_match = !($block->visibility xor $page_match);
836
      }
837
      elseif (module_exists('php')) {
838
        $page_match = php_eval($block->pages);
839
      }
840
      else {
841
        $page_match = FALSE;
842
      }
843
    }
844
    else {
845
      $page_match = TRUE;
846
    }
847
    if (!$page_match) {
848
      unset($blocks[$key]);
849
    }
850
  }
851
}
852

    
853
/**
854
 * Render the content and subject for a set of blocks.
855
 *
856
 * @param $region_blocks
857
 *   An array of block objects such as returned for one region by
858
 *   _block_load_blocks().
859
 *
860
 * @return
861
 *   An array of visible blocks as expected by drupal_render().
862
 */
863
function _block_render_blocks($region_blocks) {
864
  $cacheable = TRUE;
865

    
866
  // We preserve the submission of forms in blocks, by fetching from cache only
867
  // if the request method is 'GET' (or 'HEAD').
868
  if ($_SERVER['REQUEST_METHOD'] != 'GET' && $_SERVER['REQUEST_METHOD'] != 'HEAD') {
869
    $cacheable = FALSE;
870
  }
871
  // Block caching is not usually compatible with node access modules, so by
872
  // default it is disabled when node access modules exist. However, it can be
873
  // allowed by using the variable 'block_cache_bypass_node_grants'.
874
  elseif (!variable_get('block_cache_bypass_node_grants', FALSE) && count(module_implements('node_grants'))) {
875
    $cacheable = FALSE;
876
  }
877

    
878
  // Proceed to loop over all blocks in order to compute their respective cache
879
  // identifiers; this allows us to do one single cache_get_multiple() call
880
  // instead of doing one cache_get() call per block.
881
  $cached_blocks = array();
882
  $cids = array();
883

    
884
  if ($cacheable) {
885
    foreach ($region_blocks as $key => $block) {
886
      if (!isset($block->content)) {
887
        if (($cid = _block_get_cache_id($block))) {
888
          $cids[$key] = $cid;
889
        }
890
      }
891
    }
892

    
893
    if ($cids) {
894
      // We cannot pass $cids in directly because cache_get_multiple() will
895
      // modify it, and we need to use it later on in this function.
896
      $cid_values = array_values($cids);
897
      $cached_blocks = cache_get_multiple($cid_values, 'cache_block');
898
    }
899
  }
900

    
901
  foreach ($region_blocks as $key => $block) {
902
    // Render the block content if it has not been created already.
903
    if (!isset($block->content)) {
904
      // Erase the block from the static array - we'll put it back if it has
905
      // content.
906
      unset($region_blocks[$key]);
907

    
908
      $cid = empty($cids[$key]) ? NULL : $cids[$key];
909

    
910
      // Try fetching the block from the previously loaded cache entries.
911
      if (isset($cached_blocks[$cid])) {
912
        $array = $cached_blocks[$cid]->data;
913
      }
914
      else {
915
        $array = module_invoke($block->module, 'block_view', $block->delta);
916

    
917
        // Valid PHP function names cannot contain hyphens.
918
        $delta = str_replace('-', '_', $block->delta);
919
        // Allow modules to modify the block before it is viewed, via either
920
        // hook_block_view_alter() or hook_block_view_MODULE_DELTA_alter().
921
        drupal_alter(array('block_view', "block_view_{$block->module}_{$delta}"), $array, $block);
922

    
923
        if (isset($cid)) {
924
          cache_set($cid, $array, 'cache_block', CACHE_TEMPORARY);
925
        }
926
      }
927

    
928
      if (isset($array) && is_array($array)) {
929
        foreach ($array as $k => $v) {
930
          $block->$k = $v;
931
        }
932
      }
933
      if (isset($block->content) && $block->content) {
934
        // Normalize to the drupal_render() structure.
935
        if (is_string($block->content)) {
936
          $block->content = array('#markup' => $block->content);
937
        }
938
        // Override default block title if a custom display title is present.
939
        if ($block->title) {
940
          // Check plain here to allow module generated titles to keep any
941
          // markup.
942
          $block->subject = $block->title == '<none>' ? '' : check_plain($block->title);
943
        }
944
        if (!isset($block->subject)) {
945
          $block->subject = '';
946
        }
947
        $region_blocks["{$block->module}_{$block->delta}"] = $block;
948
      }
949
    }
950
  }
951
  return $region_blocks;
952
}
953

    
954
/**
955
 * Assemble the cache_id to use for a given block.
956
 *
957
 * The cache_id string reflects the viewing context for the current block
958
 * instance, obtained by concatenating the relevant context information
959
 * (user, page, ...) according to the block's cache settings (BLOCK_CACHE_*
960
 * constants). Two block instances can use the same cached content when
961
 * they share the same cache_id.
962
 *
963
 * Theme and language contexts are automatically differentiated.
964
 *
965
 * @param $block
966
 *   The block to get the cache_id from.
967
 *
968
 * @return
969
 *   The string used as cache_id for the block.
970
 */
971
function _block_get_cache_id($block) {
972
  global $user;
973

    
974
  // User 1 being out of the regular 'roles define permissions' schema,
975
  // it brings too many chances of having unwanted output get in the cache
976
  // and later be served to other users. We therefore exclude user 1 from
977
  // block caching.
978
  if (variable_get('block_cache', FALSE) && !in_array($block->cache, array(DRUPAL_NO_CACHE, DRUPAL_CACHE_CUSTOM)) && $user->uid != 1) {
979
    // Start with common sub-patterns: block identification, theme, language.
980
    $cid_parts[] = $block->module;
981
    $cid_parts[] = $block->delta;
982
    drupal_alter('block_cid_parts', $cid_parts, $block);
983
    $cid_parts = array_merge($cid_parts, drupal_render_cid_parts($block->cache));
984

    
985
    return implode(':', $cid_parts);
986
  }
987
}
988

    
989
/**
990
 * Implements hook_flush_caches().
991
 */
992
function block_flush_caches() {
993
  // Rehash blocks for active themes. We don't use list_themes() here,
994
  // because if MAINTENANCE_MODE is defined it skips reading the database,
995
  // and we can't tell which themes are active.
996
  $themes = db_query("SELECT name FROM {system} WHERE type = 'theme' AND status = 1");
997
  foreach ($themes as $theme) {
998
    _block_rehash($theme->name);
999
  }
1000

    
1001
  return array('cache_block');
1002
}
1003

    
1004
/**
1005
 * Processes variables for block.tpl.php.
1006
 *
1007
 * Prepares the values passed to the theme_block function to be passed
1008
 * into a pluggable template engine. Uses block properties to generate a
1009
 * series of template file suggestions. If none are found, the default
1010
 * block.tpl.php is used.
1011
 *
1012
 * Most themes utilize their own copy of block.tpl.php. The default is located
1013
 * inside "modules/block/block.tpl.php". Look in there for the full list of
1014
 * variables.
1015
 *
1016
 * The $variables array contains the following arguments:
1017
 * - $block
1018
 *
1019
 * @see block.tpl.php
1020
 */
1021
function template_preprocess_block(&$variables) {
1022
  $block_counter = &drupal_static(__FUNCTION__, array());
1023
  $variables['block'] = $variables['elements']['#block'];
1024
  // All blocks get an independent counter for each region.
1025
  if (!isset($block_counter[$variables['block']->region])) {
1026
    $block_counter[$variables['block']->region] = 1;
1027
  }
1028
  // Same with zebra striping.
1029
  $variables['block_zebra'] = ($block_counter[$variables['block']->region] % 2) ? 'odd' : 'even';
1030
  $variables['block_id'] = $block_counter[$variables['block']->region]++;
1031

    
1032
  // Create the $content variable that templates expect.
1033
  $variables['content'] = $variables['elements']['#children'];
1034

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

    
1037
  $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->region;
1038
  $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->module;
1039
  // Hyphens (-) and underscores (_) play a special role in theme suggestions.
1040
  // Theme suggestions should only contain underscores, because within
1041
  // drupal_find_theme_templates(), underscores are converted to hyphens to
1042
  // match template file names, and then converted back to underscores to match
1043
  // pre-processing and other function names. So if your theme suggestion
1044
  // contains a hyphen, it will end up as an underscore after this conversion,
1045
  // and your function names won't be recognized. So, we need to convert
1046
  // hyphens to underscores in block deltas for the theme suggestions.
1047
  $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->module . '__' . strtr($variables['block']->delta, '-', '_');
1048

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

    
1053
/**
1054
 * Implements hook_user_role_delete().
1055
 *
1056
 * Removes deleted role from blocks that use it.
1057
 */
1058
function block_user_role_delete($role) {
1059
  db_delete('block_role')
1060
    ->condition('rid', $role->rid)
1061
    ->execute();
1062
}
1063

    
1064
/**
1065
 * Implements hook_menu_delete().
1066
 */
1067
function block_menu_delete($menu) {
1068
  db_delete('block')
1069
    ->condition('module', 'menu')
1070
    ->condition('delta', $menu['menu_name'])
1071
    ->execute();
1072
  db_delete('block_role')
1073
    ->condition('module', 'menu')
1074
    ->condition('delta', $menu['menu_name'])
1075
    ->execute();
1076
}
1077

    
1078
/**
1079
 * Implements hook_form_FORM_ID_alter().
1080
 */
1081
function block_form_system_performance_settings_alter(&$form, &$form_state) {
1082
  $disabled = (!variable_get('block_cache_bypass_node_grants', FALSE) && count(module_implements('node_grants')));
1083
  $form['caching']['block_cache'] = array(
1084
    '#type' => 'checkbox',
1085
    '#title' => t('Cache blocks'),
1086
    '#default_value' => variable_get('block_cache', FALSE),
1087
    '#disabled' => $disabled,
1088
    '#description' => $disabled ? t('Block caching is inactive because you have enabled modules defining content access restrictions.') : NULL,
1089
    '#weight' => -1,
1090
  );
1091
}
1092

    
1093
/**
1094
 * Implements hook_admin_paths().
1095
 */
1096
function block_admin_paths() {
1097
  $paths = array(
1098
    // Exclude the block demonstration page from admin (overlay) treatment.
1099
    // This allows us to present this page in its true form, full page.
1100
    'admin/structure/block/demo/*' => FALSE,
1101
  );
1102
  return $paths;
1103
}
1104

    
1105
/**
1106
 * Implements hook_modules_uninstalled().
1107
 *
1108
 * Cleans up {block} and {block_role} tables from modules' blocks.
1109
 */
1110
function block_modules_uninstalled($modules) {
1111
  db_delete('block')
1112
    ->condition('module', $modules, 'IN')
1113
    ->execute();
1114
  db_delete('block_role')
1115
    ->condition('module', $modules, 'IN')
1116
    ->execute();
1117
}