Projet

Général

Profil

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

root / drupal7 / modules / block / block.module @ b0dc3a2e

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
      foreach (system_region_list($theme, REGIONS_VISIBLE, FALSE) as $region) {
289
        $description = '<div class="block-region">' . $all_regions[$region] . '</div>';
290
        $page[$region]['block_description'] = array(
291
          '#markup' => $description,
292
          '#weight' => 15,
293
        );
294
      }
295
      $page['page_top']['backlink'] = array(
296
        '#type' => 'link',
297
        '#title' => t('Exit block region demonstration'),
298
        '#href' => 'admin/structure/block' . (variable_get('theme_default', 'bartik') == $theme ? '' : '/list/' . $theme),
299
        // Add the "overlay-restore" class to indicate this link should restore
300
        // the context in which the region demonstration page was opened.
301
        '#options' => array('attributes' => array('class' => array('block-demo-backlink', 'overlay-restore'))),
302
        '#weight' => -10,
303
      );
304
    }
305
  }
306
}
307

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

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

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

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

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

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

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

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

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

    
547
  return $form;
548
}
549

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

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

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

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

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

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

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

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

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

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

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

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

    
727
  return $block;
728
}
729

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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