summaryrefslogtreecommitdiff
path: root/modules/block/block.module
blob: 223c380fd3e23bee6ea2867dc962989bc93e6ae0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
<?php
// $Id$

/**
 * @file
 * Controls the boxes that are displayed around the main content.
 */

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

/**
 * Implementation of hook_help().
 */
function block_help($path, $arg) {
  switch ($path) {
    case 'admin/help#block':
      $output = '<p>'. t('Blocks are boxes of content that may be rendered into certain regions of your web pages, for example, into sidebars. Blocks are usually generated automatically by modules (e.g., Recent Forum Topics), but administrators can also define custom blocks.') .'</p>';
      $output .= '<p>'. t('The region each block appears in depends on both which theme you are using (some themes allow greater control over block placement than others), and on the settings in the block administration section.') .'</p>';
      $output .= '<p>'. t('The block administration screen lets you specify the vertical placement of the blocks within a region. You do this by assigning a weight to each block. Lighter blocks (those having a smaller weight) "float up" towards the top of the region; heavier ones "sink".') .'</p>';
      $output .= t("<p>A block's visibility depends on:</p>
<ul>
<li>Its region placement. Blocks with no region assigned to them are never shown.</li>
<li>Its throttle checkbox when throttle module is enabled. Throttled blocks are hidden during high server loads.</li>
<li>Its page visibility settings. Blocks can be configured to be visible/hidden on certain pages.</li>
<li>Its custom visibility settings. Blocks can be configured to be visible only when specific conditions are true.</li>
<li>Its user visibility settings. Administrators can choose to let users decide whether to show/hide certain blocks.</li>
<li>Its user-role visibility settings. Administrators can choose to let blocks be visible only for certain user roles.</li>
<li>Its function. Some dynamic blocks, such as those generated by modules, will be displayed only on certain pages.</li>
</ul>
");
      $output .= '<h3>'. t('Module blocks') .'</h3>';
      $output .= '<p>'. t('Some modules generate blocks that become available when the modules are enabled. These blocks can be administered via the <a href="@admin-block">blocks administration page</a>.</p>', array('@admin-block' => url('admin/build/block'))) .'</p>';
      $output .= '<h3>'. t('Administrator defined blocks') .'</h3>';
      $output .= '<p>'. t('Administrators can also define custom blocks. These blocks consist of a title, a description, and a body which can be as long as you wish. Block content can be in any of the input formats supported for other content.') .'</p>';
      $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="@block">Block page</a>.', array('@block' => 'http://drupal.org/handbook/modules/block/')) .'</p>';
      return $output;
    case 'admin/build/block':
      return t('<p>Blocks are boxes of content that may be rendered into certain regions of your web pages, for example, into sidebars. They are usually generated automatically by modules, but administrators can create blocks manually.</p>
<p>Only enabled blocks are shown. You can position blocks by specifying which area of the page they should appear in (e.g., a sidebar).  Highlighted labels on this page show the regions into which blocks can be rendered. You can specify where within a region a block will appear by adjusting its weight.</p>
<p>If you want certain blocks to disable themselves temporarily during high server loads, check the "Throttle" box. You can configure the auto-throttle on the <a href="@throttle">throttle configuration page</a> after having enabled the throttle module.</p>
<p>You can configure the behaviour of each block (for example, specifying on which pages and for what users it will appear) by clicking the "configure" link for each block.</p>', array('@throttle' => url('admin/settings/throttle')));
    case 'admin/build/block/add':
      return '<p>'. t('Here you can create a new block. Once you have created this block you must make it active and give it a place on the page using <a href="@overview">blocks</a>. The description is used in the "block" column on the <a href="@overview">blocks</a> page.', array('@overview' => url('admin/build/block'))) .'</p>';
  }
}

/**
 * Implementation of hook_theme()
 */
function block_theme() {
  return array(
    'block_admin_display' => array(
      'file' => 'block-admin-display',
      'arguments' => array('form' => NULL),
    ),
  );
}

/**
 * Implementation of hook_perm().
 */
function block_perm() {
  return array('administer blocks', 'use PHP for block visibility');
}

/**
 * Implementation of hook_menu().
 */
function block_menu() {
  $items['admin/build/block'] = array(
    'title' => 'Blocks',
    'description' => 'Configure what block content appears in your site\'s sidebars and other regions.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('block_admin_display'),
    'access arguments' => array('administer blocks'),
    'file' => 'block.admin.inc',
  );
  $items['admin/build/block/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/build/block/configure'] = array(
    'title' => 'Configure block',
    'page arguments' => array('block_admin_configure'),
    'type' => MENU_CALLBACK,
    'file' => 'block.admin.inc',
  );
  $items['admin/build/block/delete'] = array(
    'title' => 'Delete block',
    'page arguments' => array('block_box_delete'),
    'type' => MENU_CALLBACK,
    'file' => 'block.admin.inc',
  );
  $items['admin/build/block/add'] = array(
    'title' => 'Add block',
    'page arguments' => array('block_add_block_form'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'block.admin.inc',
  );
  $default = variable_get('theme_default', 'garland');
  foreach (list_themes() as $key => $theme) {
    $items['admin/build/block/list/'. $key] = array(
      'title' => check_plain($theme->info['name']),
      'page arguments' => array('block_admin_display', $key),
      'type' => $key == $default ? MENU_DEFAULT_LOCAL_TASK : MENU_LOCAL_TASK,
      'weight' => $key == $default ? -10 : 0,
      'file' => 'block.admin.inc',
    );
  }
  return $items;
}

/**
 * Implementation of hook_block().
 *
 * Generates the administrator-defined blocks for display.
 */
function block_block($op = 'list', $delta = 0, $edit = array()) {
  switch ($op) {
    case 'list':
      $blocks = array();

      $result = db_query('SELECT bid, info FROM {boxes} ORDER BY info');
      while ($block = db_fetch_object($result)) {
        $blocks[$block->bid]['info'] = $block->info;
      }
      return $blocks;

    case 'configure':
      $box = array('format' => FILTER_FORMAT_DEFAULT);
      if ($delta) {
        $box = block_box_get($delta);
      }
      if (filter_access($box['format'])) {
        return block_box_form($box);
      }
      break;

    case 'save':
      block_box_save($edit, $delta);
      break;

    case 'view':
      $block = db_fetch_object(db_query('SELECT body, format FROM {boxes} WHERE bid = %d', $delta));
      $data['content'] = check_markup($block->body, $block->format, FALSE);
      return $data;
  }
}

/**
 * Update the 'blocks' DB table with the blocks currently exported by modules.
 *
 * @return
 *   Blocks currently exported by modules.
 */
function _block_rehash() {
  global $theme_key;

  init_theme();

  $result = db_query("SELECT * FROM {blocks} WHERE theme = '%s'", $theme_key);
  while ($old_block = db_fetch_object($result)) {
    $old_blocks[$old_block->module][$old_block->delta] = $old_block;
  }

  $blocks = array();

  foreach (module_list() as $module) {
    $module_blocks = module_invoke($module, 'block', 'list');
    if ($module_blocks) {
      foreach ($module_blocks as $delta => $block) {
        $block['module'] = $module;
        $block['delta']  = $delta;
        // If previously written to database, load values.
        if (!empty($old_blocks[$module][$delta])) {
          $block['status'] = $old_blocks[$module][$delta]->status;
          $block['weight'] = $old_blocks[$module][$delta]->weight;
          $block['region'] = $old_blocks[$module][$delta]->region;
          $block['visibility'] = $old_blocks[$module][$delta]->visibility;
          $block['pages'] = $old_blocks[$module][$delta]->pages;
          $block['custom'] = $old_blocks[$module][$delta]->custom;
          $block['throttle'] = $old_blocks[$module][$delta]->throttle;
          $block['title'] = $old_blocks[$module][$delta]->title;
        }
        // Otherwise, use any set values, or else substitute defaults.
        else {
          $properties = array('status' => 0, 'weight' => 0, 'region' => 'left', 'pages' => '', 'custom' => 0, 'title' => '');
          foreach ($properties as $property => $default) {
            if (!isset($block[$property])) {
              $block[$property] = $default;
            }
          }
        }

        $blocks[] = $block;
      }
    }
  }

  db_lock_table('blocks');
  // Remove all blocks from table.
  db_query("DELETE FROM {blocks} WHERE theme = '%s'", $theme_key);

  // Reinsert new set of blocks into table.
  foreach ($blocks as $block) {
    $block += array(
      'visibility' => NULL,
      'throttle' => NULL,
    );
    db_query("INSERT INTO {blocks} (module, delta, theme, status, weight, region, visibility, pages, custom, throttle, title) VALUES ('%s', '%s', '%s', %d, %d, '%s', %d, '%s', %d, %d, '%s')", $block['module'], $block['delta'], $theme_key, $block['status'], $block['weight'], $block['region'], $block['visibility'], $block['pages'], $block['custom'], $block['throttle'], $block['title']);
  }
  db_unlock_tables();

  return $blocks;
}

function block_box_get($bid) {
  return db_fetch_array(db_query("SELECT bx.*, bl.title FROM {boxes} bx INNER JOIN {blocks} bl ON bx.bid = bl.delta WHERE bl.module = 'block' AND bx.bid = %d", $bid));
}

/**
 * Define the custom block form.
 */
function block_box_form($edit = array()) {
  $edit += array(
    'info' => '',
    'body' => '',
  );
  $form['info'] = array(
    '#type' => 'textfield',
    '#title' => t('Block description'),
    '#default_value' => $edit['info'],
    '#maxlength' => 64,
    '#description' => t('A brief description of your block. Used on the <a href="@overview">block overview page</a>.', array('@overview' => url('admin/build/block'))),
    '#required' => TRUE,
    '#weight' => -19,
  );
  $form['body_field']['#weight'] = -17;
  $form['body_field']['body'] = array(
    '#type' => 'textarea',
    '#title' => t('Block body'),
    '#default_value' => $edit['body'],
    '#rows' => 15,
    '#description' => t('The content of the block as shown to the user.'),
    '#weight' => -17,
  );
  if (!isset($edit['format'])) {
    $edit['format'] = FILTER_FORMAT_DEFAULT;
  }
  $form['body_field']['format'] = filter_form($edit['format'], -16);

  return $form;
}

function block_box_save($edit, $delta) {
  if (!filter_access($edit['format'])) {
    $edit['format'] = FILTER_FORMAT_DEFAULT;
  }

  db_query("UPDATE {boxes} SET body = '%s', info = '%s', format = %d WHERE bid = %d", $edit['body'], $edit['info'], $edit['format'], $delta);

  return TRUE;
}

/**
 * Implementation of hook_user().
 *
 * Allow users to decide which custom blocks to display when they visit
 * the site.
 */
function block_user($type, $edit, &$user, $category = NULL) {
  global $user;
  switch ($type) {
    case 'form':
      if ($category == 'account') {
        $result = db_query("SELECT DISTINCT b.* FROM {blocks} b LEFT JOIN {blocks_roles} r ON b.module = r.module AND b.delta = r.delta WHERE b.status = 1 AND b.custom != 0 AND (r.rid IN (%s) OR r.rid IS NULL) ORDER BY b.weight, b.module", implode(',', array_keys($user->roles)));
        $form['block'] = array('#type' => 'fieldset', '#title' => t('Block configuration'), '#weight' => 3, '#collapsible' => TRUE, '#tree' => TRUE);
        while ($block = db_fetch_object($result)) {
          $data = module_invoke($block->module, 'block', 'list');
          if ($data[$block->delta]['info']) {
            $return = TRUE;
            $form['block'][$block->module][$block->delta] = array('#type' => 'checkbox', '#title' => check_plain($data[$block->delta]['info']), '#default_value' => isset($user->block[$block->module][$block->delta]) ? $user->block[$block->module][$block->delta] : ($block->custom == 1));
          }
        }

        if (!empty($return)) {
          return $form;
        }
      }

      break;
    case 'validate':
      if (empty($edit['block'])) {
        $edit['block'] = array();
      }
      return $edit;
  }
}

/**
 * Return all blocks in the specified region for the current user.
 *
 * @param $region
 *   The name of a region.
 *
 * @return
 *   An array of block objects, indexed with <i>module</i>_<i>delta</i>.
 *   If you are displaying your blocks in one or two sidebars, you may check
 *   whether this array is empty to see how many columns are going to be
 *   displayed.
 *
 * @todo
 *   Add a proper primary key (bid) to the blocks table so we don't have
 *   to mess around with this <i>module</i>_<i>delta</i> construct.
 *   Currently, the blocks table has no primary key defined!
 */
function block_list($region) {
  global $user, $theme_key;

  static $blocks = array();

  if (!count($blocks)) {
    $result = db_query(db_rewrite_sql("SELECT DISTINCT b.* FROM {blocks} b LEFT JOIN {blocks_roles} r ON b.module = r.module AND b.delta = r.delta WHERE b.theme = '%s' AND b.status = 1 AND (r.rid IN (%s) OR r.rid IS NULL) ORDER BY b.region, b.weight, b.module", 'b', 'bid'), $theme_key, implode(',', array_keys($user->roles)));
    while ($block = db_fetch_object($result)) {
      if (!isset($blocks[$block->region])) {
        $blocks[$block->region] = array();
      }
      // Use the user's block visibility setting, if necessary
      if ($block->custom != 0) {
        if ($user->uid && isset($user->block[$block->module][$block->delta])) {
          $enabled = $user->block[$block->module][$block->delta];
        }
        else {
          $enabled = ($block->custom == 1);
        }
      }
      else {
        $enabled = TRUE;
      }

      // Match path if necessary
      if ($block->pages) {
        if ($block->visibility < 2) {
          $path = drupal_get_path_alias($_GET['q']);
          $regexp = '/^('. preg_replace(array('/(\r\n?|\n)/', '/\\\\\*/', '/(^|\|)\\\\<front\\\\>($|\|)/'), array('|', '.*', '\1'. preg_quote(variable_get('site_frontpage', 'node'), '/') .'\2'), preg_quote($block->pages, '/')) .')$/';
          // Compare with the internal and path alias (if any).
          $page_match = preg_match($regexp, $path);
          if ($path != $_GET['q']) {
            $page_match = $page_match || preg_match($regexp, $_GET['q']);
          }
          // When $block->visibility has a value of 0, the block is displayed on
          // all pages except those listed in $block->pages. When set to 1, it
          // is displayed only on those pages listed in $block->pages.
          $page_match = !($block->visibility xor $page_match);
        }
        else {
          $page_match = drupal_eval($block->pages);
        }
      }
      else {
        $page_match = TRUE;
      }

      if ($enabled && $page_match) {
        // Check the current throttle status and see if block should be displayed
        // based on server load.
        if (!($block->throttle && (module_invoke('throttle', 'status') > 0))) {
          $array = module_invoke($block->module, 'block', 'view', $block->delta);
          if (isset($array) && is_array($array)) {
            foreach ($array as $k => $v) {
              $block->$k = $v;
            }
          }
        }
        if (isset($block->content) && $block->content) {
          // Override default block title if a custom display title is present.
          if ($block->title) {
            // Check plain here to allow module generated titles to keep any markup.
            $block->subject = $block->title == '<none>' ? '' : check_plain($block->title);
          }
          $blocks[$block->region]["{$block->module}_{$block->delta}"] = $block;
        }
      }
    }
  }
  // Create an empty array if there were no entries
  if (!isset($blocks[$region])) {
    $blocks[$region] = array();
  }
  return $blocks[$region];
}