Projet

Général

Profil

Paste
Télécharger (38,9 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / block / block.module @ 41cc1b08

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
    case 'admin/structure/block/add':
63
      return '<p>' . t('Use this page to create a new custom block.') . '</p>';
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
    $themes = list_themes();
68
    $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>';
69
    $output .= '<p>' . l(t('Demonstrate block regions (!theme)', array('!theme' => $themes[$demo_theme]->info['name'])), 'admin/structure/block/demo/' . $demo_theme) . '</p>';
70
    return $output;
71
  }
72
}
73

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

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

    
102
/**
103
 * Implements hook_menu().
104
 */
105
function block_menu() {
106
  $default_theme = variable_get('theme_default', 'bartik');
107
  $items['admin/structure/block'] = array(
108
    'title' => 'Blocks',
109
    '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
    'title' => 'Configure block',
124
    'type' => MENU_DEFAULT_LOCAL_TASK,
125
    'context' => MENU_CONTEXT_INLINE,
126
  );
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
    'type' => MENU_LOCAL_TASK,
133
    '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
      'title' => $theme->info['name'],
147
      'page arguments' => array($key),
148
      'type' => $key == $default_theme ? MENU_DEFAULT_LOCAL_TASK : MENU_LOCAL_TASK,
149
      'weight' => $key == $default_theme ? -10 : 0,
150
      'access callback' => '_block_themes_access',
151
      'access arguments' => array($theme),
152
      'file' => 'block.admin.inc',
153
    );
154
    if ($key != $default_theme) {
155
      $items['admin/structure/block/list/' . $key . '/add'] = array(
156
        'title' => 'Add block',
157
        'page callback' => 'drupal_get_form',
158
        'page arguments' => array('block_add_block_form'),
159
        'access arguments' => array('administer blocks'),
160
        'type' => MENU_LOCAL_ACTION,
161
        'file' => 'block.admin.inc',
162
      );
163
    }
164
    $items['admin/structure/block/demo/' . $key] = array(
165
      'title' => $theme->info['name'],
166
      'page callback' => 'block_admin_demo',
167
      'page arguments' => array($key),
168
      'type' => MENU_CALLBACK,
169
      'access callback' => '_block_themes_access',
170
      'access arguments' => array($theme),
171
      'theme callback' => '_block_custom_theme',
172
      'theme arguments' => array($key),
173
      'file' => 'block.admin.inc',
174
    );
175
  }
176
  return $items;
177
}
178

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

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

    
202
/**
203
 * Implements hook_block_info().
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
    $blocks[$block->bid]['info'] = $block->info;
211
    // Not worth caching.
212
    $blocks[$block->bid]['cache'] = DRUPAL_NO_CACHE;
213
  }
214
  return $blocks;
215
}
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
  else {
225
    $custom_block = array();
226
  }
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
 * Generates the administrator-defined blocks for display.
241
 */
242
function block_block_view($delta = '') {
243
  $block = db_query('SELECT body, format FROM {block_custom} WHERE bid = :bid', array(':bid' => $delta))->fetchObject();
244
  $data['subject'] = NULL;
245
  $data['content'] = check_markup($block->body, $block->format, '', TRUE);
246
  return $data;
247
}
248

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

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

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

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

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

    
349
    $build[$key] += array(
350
      '#block' => $block,
351
      '#weight' => ++$weight,
352
    );
353
    $build[$key]['#theme_wrappers'][] ='block';
354
  }
355
  $build['#sorted'] = TRUE;
356
  return $build;
357
}
358

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

    
372
  drupal_theme_initialize();
373
  if (!isset($theme)) {
374
    // If theme is not specifically set, rehash for the current theme.
375
    $theme = $theme_key;
376
  }
377
  $regions = system_region_list($theme);
378

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

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

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

    
541
  return $form;
542
}
543

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

    
571
/**
572
 * Implements hook_form_FORM_ID_alter() for user_profile_form().
573
 */
574
function block_form_user_profile_form_alter(&$form, &$form_state) {
575
  if ($form['#user_category'] == 'account') {
576
    $account = $form['#user'];
577
    $rids = array_keys($account->roles);
578
    $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));
579

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

    
606
/**
607
 * Implements hook_user_presave().
608
 */
609
function block_user_presave(&$edit, $account, $category) {
610
  if (isset($edit['block'])) {
611
    $edit['data']['block'] = $edit['block'];
612
  }
613
}
614

    
615
/**
616
 * Initializes blocks for enabled themes.
617
 *
618
 * @param $theme_list
619
 *   An array of theme names.
620
 */
621
function block_themes_enabled($theme_list) {
622
  foreach ($theme_list as $theme) {
623
    block_theme_initialize($theme);
624
  }
625
}
626

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

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

    
677
  if (!isset($blocks)) {
678
    $blocks = _block_load_blocks();
679
  }
680

    
681
  // Create an empty array if there are no entries.
682
  if (!isset($blocks[$region])) {
683
    $blocks[$region] = array();
684
  }
685
  else {
686
    $blocks[$region] = _block_render_blocks($blocks[$region]);
687
  }
688

    
689
  return $blocks[$region];
690
}
691

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

    
712
  // If the block does not exist in the database yet return a stub block
713
  // object.
714
  if (empty($block)) {
715
    $block = new stdClass();
716
    $block->module = $module;
717
    $block->delta = $delta;
718
  }
719

    
720
  return $block;
721
}
722

    
723
/**
724
 * Loads blocks' information from the database.
725
 *
726
 * @return
727
 *   An array of blocks grouped by region.
728
 */
729
function _block_load_blocks() {
730
  global $theme_key;
731

    
732
  $query = db_select('block', 'b');
733
  $result = $query
734
    ->fields('b')
735
    ->condition('b.theme', $theme_key)
736
    ->condition('b.status', 1)
737
    ->orderBy('b.region')
738
    ->orderBy('b.weight')
739
    ->orderBy('b.module')
740
    ->addTag('block_load')
741
    ->addTag('translatable')
742
    ->execute();
743

    
744
  $block_info = $result->fetchAllAssoc('bid');
745
  // Allow modules to modify the block list.
746
  drupal_alter('block_list', $block_info);
747

    
748
  $blocks = array();
749
  foreach ($block_info as $block) {
750
    $blocks[$block->region]["{$block->module}_{$block->delta}"] = $block;
751
  }
752
  return $blocks;
753
}
754

    
755
/**
756
 * Implements hook_block_list_alter().
757
 *
758
 * Checks the page, user role, and user-specific visibility settings.
759
 * Removes the block if the visibility conditions are not met.
760
 */
761
function block_block_list_alter(&$blocks) {
762
  global $user, $theme_key;
763

    
764
  // Build an array of roles for each block.
765
  $block_roles = array();
766
  $result = db_query('SELECT module, delta, rid FROM {block_role}');
767
  foreach ($result as $record) {
768
    $block_roles[$record->module][$record->delta][] = $record->rid;
769
  }
770

    
771
  foreach ($blocks as $key => $block) {
772
    if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
773
      // This block was added by a contrib module, leave it in the list.
774
      continue;
775
    }
776

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

    
786
    // Use the user's block visibility setting, if necessary.
787
    if ($block->custom != BLOCK_CUSTOM_FIXED) {
788
      if ($user->uid && isset($user->data['block'][$block->module][$block->delta])) {
789
        $enabled = $user->data['block'][$block->module][$block->delta];
790
      }
791
      else {
792
        $enabled = ($block->custom == BLOCK_CUSTOM_ENABLED);
793
      }
794
    }
795
    else {
796
      $enabled = TRUE;
797
    }
798

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

    
804
    if (!$enabled) {
805
      unset($blocks[$key]);
806
      continue;
807
    }
808

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

    
844
/**
845
 * Render the content and subject for a set of blocks.
846
 *
847
 * @param $region_blocks
848
 *   An array of block objects such as returned for one region by _block_load_blocks().
849
 *
850
 * @return
851
 *   An array of visible blocks as expected by drupal_render().
852
 */
853
function _block_render_blocks($region_blocks) {
854
  $cacheable = TRUE;
855

    
856
  // We preserve the submission of forms in blocks, by fetching from cache only
857
  // if the request method is 'GET' (or 'HEAD').
858
  if ($_SERVER['REQUEST_METHOD'] != 'GET' && $_SERVER['REQUEST_METHOD'] != 'HEAD') {
859
    $cacheable = FALSE;
860
  }
861
  // Block caching is not usually compatible with node access modules, so by
862
  // default it is disabled when node access modules exist. However, it can be
863
  // allowed by using the variable 'block_cache_bypass_node_grants'.
864
  elseif (!variable_get('block_cache_bypass_node_grants', FALSE) && count(module_implements('node_grants'))) {
865
    $cacheable = FALSE;
866
  }
867

    
868
  // Proceed to loop over all blocks in order to compute their respective cache
869
  // identifiers; this allows us to do one single cache_get_multiple() call
870
  // instead of doing one cache_get() call per block.
871
  $cached_blocks = array();
872
  $cids = array();
873

    
874
  if ($cacheable) {
875
    foreach ($region_blocks as $key => $block) {
876
      if (!isset($block->content)) {
877
        if (($cid = _block_get_cache_id($block))) {
878
          $cids[$key] = $cid;
879
        }
880
      }
881
    }
882

    
883
    if ($cids) {
884
      // We cannot pass $cids in directly because cache_get_multiple() will
885
      // modify it, and we need to use it later on in this function.
886
      $cid_values = array_values($cids);
887
      $cached_blocks = cache_get_multiple($cid_values, 'cache_block');
888
    }
889
  }
890

    
891
  foreach ($region_blocks as $key => $block) {
892
    // Render the block content if it has not been created already.
893
    if (!isset($block->content)) {
894
      // Erase the block from the static array - we'll put it back if it has
895
      // content.
896
      unset($region_blocks[$key]);
897

    
898
      $cid = empty($cids[$key]) ? NULL : $cids[$key];
899

    
900
      // Try fetching the block from the previously loaded cache entries.
901
      if (isset($cached_blocks[$cid])) {
902
        $array = $cached_blocks[$cid]->data;
903
      }
904
      else {
905
        $array = module_invoke($block->module, 'block_view', $block->delta);
906

    
907
        // Valid PHP function names cannot contain hyphens.
908
        $delta = str_replace('-', '_', $block->delta);
909
        // Allow modules to modify the block before it is viewed, via either
910
        // hook_block_view_alter() or hook_block_view_MODULE_DELTA_alter().
911
        drupal_alter(array('block_view', "block_view_{$block->module}_{$delta}"), $array, $block);
912

    
913
        if (isset($cid)) {
914
          cache_set($cid, $array, 'cache_block', CACHE_TEMPORARY);
915
        }
916
      }
917

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

    
944
/**
945
 * Assemble the cache_id to use for a given block.
946
 *
947
 * The cache_id string reflects the viewing context for the current block
948
 * instance, obtained by concatenating the relevant context information
949
 * (user, page, ...) according to the block's cache settings (BLOCK_CACHE_*
950
 * constants). Two block instances can use the same cached content when
951
 * they share the same cache_id.
952
 *
953
 * Theme and language contexts are automatically differentiated.
954
 *
955
 * @param $block
956
 * @return
957
 *   The string used as cache_id for the block.
958
 */
959
function _block_get_cache_id($block) {
960
  global $user;
961

    
962
  // User 1 being out of the regular 'roles define permissions' schema,
963
  // it brings too many chances of having unwanted output get in the cache
964
  // and later be served to other users. We therefore exclude user 1 from
965
  // block caching.
966
  if (variable_get('block_cache', FALSE) && !in_array($block->cache, array(DRUPAL_NO_CACHE, DRUPAL_CACHE_CUSTOM)) && $user->uid != 1) {
967
    // Start with common sub-patterns: block identification, theme, language.
968
    $cid_parts[] = $block->module;
969
    $cid_parts[] = $block->delta;
970
    $cid_parts = array_merge($cid_parts, drupal_render_cid_parts($block->cache));
971

    
972
    return implode(':', $cid_parts);
973
  }
974
}
975

    
976
/**
977
 * Implements hook_flush_caches().
978
 */
979
function block_flush_caches() {
980
  // Rehash blocks for active themes. We don't use list_themes() here,
981
  // because if MAINTENANCE_MODE is defined it skips reading the database,
982
  // and we can't tell which themes are active.
983
  $themes = db_query("SELECT name FROM {system} WHERE type = 'theme' AND status = 1");
984
  foreach ($themes as $theme) {
985
    _block_rehash($theme->name);
986
  }
987

    
988
  return array('cache_block');
989
}
990

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

    
1019
  // Create the $content variable that templates expect.
1020
  $variables['content'] = $variables['elements']['#children'];
1021

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

    
1024
  $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->region;
1025
  $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->module;
1026
  // Hyphens (-) and underscores (_) play a special role in theme suggestions.
1027
  // Theme suggestions should only contain underscores, because within
1028
  // drupal_find_theme_templates(), underscores are converted to hyphens to
1029
  // match template file names, and then converted back to underscores to match
1030
  // pre-processing and other function names. So if your theme suggestion
1031
  // contains a hyphen, it will end up as an underscore after this conversion,
1032
  // and your function names won't be recognized. So, we need to convert
1033
  // hyphens to underscores in block deltas for the theme suggestions.
1034
  $variables['theme_hook_suggestions'][] = 'block__' . $variables['block']->module . '__' . strtr($variables['block']->delta, '-', '_');
1035

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

    
1040
/**
1041
 * Implements hook_user_role_delete().
1042
 *
1043
 * Removes deleted role from blocks that use it.
1044
 */
1045
function block_user_role_delete($role) {
1046
  db_delete('block_role')
1047
    ->condition('rid', $role->rid)
1048
    ->execute();
1049
}
1050

    
1051
/**
1052
 * Implements hook_menu_delete().
1053
 */
1054
function block_menu_delete($menu) {
1055
  db_delete('block')
1056
    ->condition('module', 'menu')
1057
    ->condition('delta', $menu['menu_name'])
1058
    ->execute();
1059
  db_delete('block_role')
1060
    ->condition('module', 'menu')
1061
    ->condition('delta', $menu['menu_name'])
1062
    ->execute();
1063
}
1064

    
1065
/**
1066
 * Implements hook_form_FORM_ID_alter().
1067
 */
1068
function block_form_system_performance_settings_alter(&$form, &$form_state) {
1069
  $disabled = (!variable_get('block_cache_bypass_node_grants', FALSE) && count(module_implements('node_grants')));
1070
  $form['caching']['block_cache'] = array(
1071
    '#type' => 'checkbox',
1072
    '#title' => t('Cache blocks'),
1073
    '#default_value' => variable_get('block_cache', FALSE),
1074
    '#disabled' => $disabled,
1075
    '#description' => $disabled ? t('Block caching is inactive because you have enabled modules defining content access restrictions.') : NULL,
1076
    '#weight' => -1,
1077
  );
1078
}
1079

    
1080
/**
1081
 * Implements hook_admin_paths().
1082
 */
1083
function block_admin_paths() {
1084
  $paths = array(
1085
    // Exclude the block demonstration page from admin (overlay) treatment.
1086
    // This allows us to present this page in its true form, full page.
1087
    'admin/structure/block/demo/*' => FALSE,
1088
  );
1089
  return $paths;
1090
}
1091

    
1092
/**
1093
 * Implements hook_modules_uninstalled().
1094
 *
1095
 * Cleans up {block} and {block_role} tables from modules' blocks.
1096
 */
1097
function block_modules_uninstalled($modules) {
1098
  db_delete('block')
1099
    ->condition('module', $modules, 'IN')
1100
    ->execute();
1101
  db_delete('block_role')
1102
    ->condition('module', $modules, 'IN')
1103
    ->execute();
1104
}