comparison modules/block/block.module @ 1:c1f4ac30525a 6.0

Drupal 6.0
author Franck Deroche <webmaster@defr.org>
date Tue, 23 Dec 2008 14:28:28 +0100
parents
children 2427550111ae
comparison
equal deleted inserted replaced
0:5a113a1c4740 1:c1f4ac30525a
1 <?php
2 // $Id: block.module,v 1.299 2008/02/03 19:12:57 goba Exp $
3
4 /**
5 * @file
6 * Controls the boxes that are displayed around the main content.
7 */
8
9 /**
10 * Denotes that a block is not enabled in any region and should not
11 * be shown.
12 */
13 define('BLOCK_REGION_NONE', -1);
14
15 /**
16 * Constants defining cache granularity for blocks.
17 *
18 * Modules specify the caching patterns for their blocks using binary
19 * combinations of these constants in their hook_block(op 'list'):
20 * $block[delta]['cache'] = BLOCK_CACHE_PER_ROLE | BLOCK_CACHE_PER_PAGE;
21 * BLOCK_CACHE_PER_ROLE is used as a default when no caching pattern is
22 * specified.
23 *
24 * The block cache is cleared in cache_clear_all(), and uses the same clearing
25 * policy than page cache (node, comment, user, taxonomy added or updated...).
26 * Blocks requiring more fine-grained clearing might consider disabling the
27 * built-in block cache (BLOCK_NO_CACHE) and roll their own.
28 *
29 * Note that user 1 is excluded from block caching.
30 */
31
32 /**
33 * The block should not get cached. This setting should be used:
34 * - for simple blocks (notably those that do not perform any db query),
35 * where querying the db cache would be more expensive than directly generating
36 * the content.
37 * - for blocks that change too frequently.
38 */
39 define('BLOCK_NO_CACHE', -1);
40
41 /**
42 * The block can change depending on the roles the user viewing the page belongs to.
43 * This is the default setting, used when the block does not specify anything.
44 */
45 define('BLOCK_CACHE_PER_ROLE', 0x0001);
46
47 /**
48 * The block can change depending on the user viewing the page.
49 * This setting can be resource-consuming for sites with large number of users,
50 * and thus should only be used when BLOCK_CACHE_PER_ROLE is not sufficient.
51 */
52 define('BLOCK_CACHE_PER_USER', 0x0002);
53
54 /**
55 * The block can change depending on the page being viewed.
56 */
57 define('BLOCK_CACHE_PER_PAGE', 0x0004);
58
59 /**
60 * The block is the same for every user on every page where it is visible.
61 */
62 define('BLOCK_CACHE_GLOBAL', 0x0008);
63
64 /**
65 * Implementation of hook_help().
66 */
67 function block_help($path, $arg) {
68 switch ($path) {
69 case 'admin/help#block':
70 $output = '<p>'. t('Blocks are boxes of content rendered into an area, or region, of a web page. The default theme Garland, for example, implements the regions "left sidebar", "right sidebar", "content", "header", and "footer", and a block may appear in any one of these areas. 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.', array('@blocks' => url('admin/build/block'))) .'</p>';
71 $output .= '<p>'. t('Although blocks are usually generated automatically by modules (like the <em>User login</em> block, for example), administrators can also define custom blocks. Custom blocks have a title, description, and body. The body of the block can be as long as necessary, and can contain content supported by any available <a href="@input-format">input format</a>.', array('@input-format' => url('admin/settings/filters'))) .'</p>';
72 $output .= '<p>'. t('When working with blocks, remember that:') .'</p>';
73 $output .= '<ul><li>'. t('since not all themes implement the same regions, or display regions in the same way, blocks are positioned on a per-theme basis.') .'</li>';
74 $output .= '<li>'. t('disabled blocks, or blocks not in a region, are never shown.') .'</li>';
75 $output .= '<li>'. t('when throttle module is enabled, throttled blocks (blocks with the <em>Throttle</em> checkbox selected) are hidden during high server loads.') .'</li>';
76 $output .= '<li>'. t('blocks can be configured to be visible only on certain pages.') .'</li>';
77 $output .= '<li>'. t('blocks can be configured to be visible only when specific conditions are true.') .'</li>';
78 $output .= '<li>'. t('blocks can be configured to be visible only for certain user roles.') .'</li>';
79 $output .= '<li>'. t('when allowed by an administrator, specific blocks may be enabled or disabled on a per-user basis using the <em>My account</em> page.') .'</li>';
80 $output .= '<li>'. t('some dynamic blocks, such as those generated by modules, will be displayed only on certain pages.') .'</li></ul>';
81 $output .= '<p>'. t('For more information, see the online handbook entry for <a href="@block">Block module</a>.', array('@block' => 'http://drupal.org/handbook/modules/block/')) .'</p>';
82 return $output;
83 case 'admin/build/block':
84 $throttle = module_exists('throttle');
85 $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. To change the region or order of a block, grab a drag-and-drop handle under the <em>Block</em> column and drag the block to a new location in the list. (Grab a handle by clicking and holding the mouse while hovering over a handle icon.) 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.') .'</p>';
86 if ($throttle) {
87 $output .= '<p>'. t('To reduce CPU usage, database traffic or bandwidth, blocks may be automatically disabled during high server loads by selecting their <em>Throttle</em> checkbox. Adjust throttle thresholds on the <a href="@throttleconfig">throttle configuration page</a>.', array('@throttleconfig' => url('admin/settings/throttle'))) .'</p>';
88 }
89 $output .= '<p>'. t('Click the <em>configure</em> link next to each block to configure its specific title and visibility settings. Use the <a href="@add-block">add block page</a> to create a custom block.', array('@add-block' => url('admin/build/block/add'))) .'</p>';
90 return $output;
91 case 'admin/build/block/add':
92 return '<p>'. t('Use this page to create a new custom block. New blocks are disabled by default, and must be moved to a region on the <a href="@blocks">blocks administration page</a> to be visible.', array('@blocks' => url('admin/build/block'))) .'</p>';
93 }
94 }
95
96 /**
97 * Implementation of hook_theme()
98 */
99 function block_theme() {
100 return array(
101 'block_admin_display_form' => array(
102 'template' => 'block-admin-display-form',
103 'file' => 'block.admin.inc',
104 'arguments' => array('form' => NULL),
105 ),
106 );
107 }
108
109 /**
110 * Implementation of hook_perm().
111 */
112 function block_perm() {
113 return array('administer blocks', 'use PHP for block visibility');
114 }
115
116 /**
117 * Implementation of hook_menu().
118 */
119 function block_menu() {
120 $items['admin/build/block'] = array(
121 'title' => 'Blocks',
122 'description' => 'Configure what block content appears in your site\'s sidebars and other regions.',
123 'page callback' => 'block_admin_display',
124 'access arguments' => array('administer blocks'),
125 'file' => 'block.admin.inc',
126 );
127 $items['admin/build/block/list'] = array(
128 'title' => 'List',
129 'type' => MENU_DEFAULT_LOCAL_TASK,
130 'weight' => -10,
131 );
132 $items['admin/build/block/list/js'] = array(
133 'title' => 'JavaScript List Form',
134 'page callback' => 'block_admin_display_js',
135 'type' => MENU_CALLBACK,
136 'file' => 'block.admin.inc',
137 );
138 $items['admin/build/block/configure'] = array(
139 'title' => 'Configure block',
140 'page callback' => 'drupal_get_form',
141 'page arguments' => array('block_admin_configure'),
142 'type' => MENU_CALLBACK,
143 'file' => 'block.admin.inc',
144 );
145 $items['admin/build/block/delete'] = array(
146 'title' => 'Delete block',
147 'page callback' => 'drupal_get_form',
148 'page arguments' => array('block_box_delete'),
149 'type' => MENU_CALLBACK,
150 'file' => 'block.admin.inc',
151 );
152 $items['admin/build/block/add'] = array(
153 'title' => 'Add block',
154 'page callback' => 'drupal_get_form',
155 'page arguments' => array('block_add_block_form'),
156 'type' => MENU_LOCAL_TASK,
157 'file' => 'block.admin.inc',
158 );
159 $default = variable_get('theme_default', 'garland');
160 foreach (list_themes() as $key => $theme) {
161 $items['admin/build/block/list/'. $key] = array(
162 'title' => check_plain($theme->info['name']),
163 'page arguments' => array($key),
164 'type' => $key == $default ? MENU_DEFAULT_LOCAL_TASK : MENU_LOCAL_TASK,
165 'weight' => $key == $default ? -10 : 0,
166 'file' => 'block.admin.inc',
167 'access callback' => '_block_themes_access',
168 'access arguments' => array($theme),
169 );
170 }
171 return $items;
172 }
173
174 /**
175 * Menu item access callback - only admin or enabled themes can be accessed
176 */
177 function _block_themes_access($theme) {
178 return user_access('administer blocks') && ($theme->status || $theme->name == variable_get('admin_theme', '0'));
179 }
180
181 /**
182 * Implementation of hook_block().
183 *
184 * Generates the administrator-defined blocks for display.
185 */
186 function block_block($op = 'list', $delta = 0, $edit = array()) {
187 switch ($op) {
188 case 'list':
189 $blocks = array();
190
191 $result = db_query('SELECT bid, info FROM {boxes} ORDER BY info');
192 while ($block = db_fetch_object($result)) {
193 $blocks[$block->bid]['info'] = $block->info;
194 // Not worth caching.
195 $blocks[$block->bid]['cache'] = BLOCK_NO_CACHE;
196 }
197 return $blocks;
198
199 case 'configure':
200 $box = array('format' => FILTER_FORMAT_DEFAULT);
201 if ($delta) {
202 $box = block_box_get($delta);
203 }
204 if (filter_access($box['format'])) {
205 return block_box_form($box);
206 }
207 break;
208
209 case 'save':
210 block_box_save($edit, $delta);
211 break;
212
213 case 'view':
214 $block = db_fetch_object(db_query('SELECT body, format FROM {boxes} WHERE bid = %d', $delta));
215 $data['content'] = check_markup($block->body, $block->format, FALSE);
216 return $data;
217 }
218 }
219
220 /**
221 * Update the 'blocks' DB table with the blocks currently exported by modules.
222 *
223 * @return
224 * Blocks currently exported by modules.
225 */
226 function _block_rehash() {
227 global $theme_key;
228
229 init_theme();
230
231 $result = db_query("SELECT * FROM {blocks} WHERE theme = '%s'", $theme_key);
232 $old_blocks = array();
233 while ($old_block = db_fetch_array($result)) {
234 $old_blocks[$old_block['module']][$old_block['delta']] = $old_block;
235 }
236
237 $blocks = array();
238 // Valid region names for the theme.
239 $regions = system_region_list($theme_key);
240
241 foreach (module_list() as $module) {
242 $module_blocks = module_invoke($module, 'block', 'list');
243 if ($module_blocks) {
244 foreach ($module_blocks as $delta => $block) {
245 if (empty($old_blocks[$module][$delta])) {
246 // If it's a new block, add identifiers.
247 $block['module'] = $module;
248 $block['delta'] = $delta;
249 $block['theme'] = $theme_key;
250 if (!isset($block['pages'])) {
251 // {block}.pages is type 'text', so it cannot have a
252 // default value, and not null, so we need to provide
253 // value if the module did not.
254 $block['pages'] = '';
255 }
256 // Add defaults and save it into the database.
257 drupal_write_record('blocks', $block);
258 // Set region to none if not enabled.
259 $block['region'] = $block['status'] ? $block['region'] : BLOCK_REGION_NONE;
260 // Add to the list of blocks we return.
261 $blocks[] = $block;
262 }
263 else {
264 // If it's an existing block, database settings should overwrite
265 // the code. But aside from 'info' everything that's definable in
266 // code is stored in the database and we do not store 'info', so we
267 // do not need to update the database here.
268 // Add 'info' to this block.
269 $old_blocks[$module][$delta]['info'] = $block['info'];
270 // If the region name does not exist, disable the block and assign it to none.
271 if (!empty($old_blocks[$module][$delta]['region']) && !isset($regions[$old_blocks[$module][$delta]['region']])) {
272 drupal_set_message(t('The block %info was assigned to the invalid region %region and has been disabled.', array('%info' => $old_blocks[$module][$delta]['info'], '%region' => $old_blocks[$module][$delta]['region'])), 'warning');
273 $old_blocks[$module][$delta]['status'] = 0;
274 $old_blocks[$module][$delta]['region'] = BLOCK_REGION_NONE;
275 }
276 else {
277 $old_blocks[$module][$delta]['region'] = $old_blocks[$module][$delta]['status'] ? $old_blocks[$module][$delta]['region'] : BLOCK_REGION_NONE;
278 }
279 // Add this block to the list of blocks we return.
280 $blocks[] = $old_blocks[$module][$delta];
281 // Remove this block from the list of blocks to be deleted.
282 unset($old_blocks[$module][$delta]);
283 }
284 }
285 }
286 }
287
288 // Remove blocks that are no longer defined by the code from the database.
289 foreach ($old_blocks as $module => $old_module_blocks) {
290 foreach ($old_module_blocks as $delta => $block) {
291 db_query("DELETE FROM {blocks} WHERE module = '%s' AND delta = '%s' AND theme = '%s'", $module, $delta, $theme_key);
292 }
293 }
294 return $blocks;
295 }
296
297 function block_box_get($bid) {
298 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));
299 }
300
301 /**
302 * Define the custom block form.
303 */
304 function block_box_form($edit = array()) {
305 $edit += array(
306 'info' => '',
307 'body' => '',
308 );
309 $form['info'] = array(
310 '#type' => 'textfield',
311 '#title' => t('Block description'),
312 '#default_value' => $edit['info'],
313 '#maxlength' => 64,
314 '#description' => t('A brief description of your block. Used on the <a href="@overview">block overview page</a>.', array('@overview' => url('admin/build/block'))),
315 '#required' => TRUE,
316 '#weight' => -19,
317 );
318 $form['body_field']['#weight'] = -17;
319 $form['body_field']['body'] = array(
320 '#type' => 'textarea',
321 '#title' => t('Block body'),
322 '#default_value' => $edit['body'],
323 '#rows' => 15,
324 '#description' => t('The content of the block as shown to the user.'),
325 '#weight' => -17,
326 );
327 if (!isset($edit['format'])) {
328 $edit['format'] = FILTER_FORMAT_DEFAULT;
329 }
330 $form['body_field']['format'] = filter_form($edit['format'], -16);
331
332 return $form;
333 }
334
335 function block_box_save($edit, $delta) {
336 if (!filter_access($edit['format'])) {
337 $edit['format'] = FILTER_FORMAT_DEFAULT;
338 }
339
340 db_query("UPDATE {boxes} SET body = '%s', info = '%s', format = %d WHERE bid = %d", $edit['body'], $edit['info'], $edit['format'], $delta);
341
342 return TRUE;
343 }
344
345 /**
346 * Implementation of hook_user().
347 *
348 * Allow users to decide which custom blocks to display when they visit
349 * the site.
350 */
351 function block_user($type, $edit, &$account, $category = NULL) {
352 switch ($type) {
353 case 'form':
354 if ($category == 'account') {
355 $rids = array_keys($account->roles);
356 $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 (". db_placeholders($rids) .") OR r.rid IS NULL) ORDER BY b.weight, b.module", $rids);
357 $form['block'] = array('#type' => 'fieldset', '#title' => t('Block configuration'), '#weight' => 3, '#collapsible' => TRUE, '#tree' => TRUE);
358 while ($block = db_fetch_object($result)) {
359 $data = module_invoke($block->module, 'block', 'list');
360 if ($data[$block->delta]['info']) {
361 $return = TRUE;
362 $form['block'][$block->module][$block->delta] = array('#type' => 'checkbox', '#title' => check_plain($data[$block->delta]['info']), '#default_value' => isset($account->block[$block->module][$block->delta]) ? $account->block[$block->module][$block->delta] : ($block->custom == 1));
363 }
364 }
365
366 if (!empty($return)) {
367 return $form;
368 }
369 }
370
371 break;
372 case 'validate':
373 if (empty($edit['block'])) {
374 $edit['block'] = array();
375 }
376 return $edit;
377 }
378 }
379
380 /**
381 * Return all blocks in the specified region for the current user.
382 *
383 * @param $region
384 * The name of a region.
385 *
386 * @return
387 * An array of block objects, indexed with <i>module</i>_<i>delta</i>.
388 * If you are displaying your blocks in one or two sidebars, you may check
389 * whether this array is empty to see how many columns are going to be
390 * displayed.
391 *
392 * @todo
393 * Now that the blocks table has a primary key, we should use that as the
394 * array key instead of <i>module</i>_<i>delta</i>.
395 */
396 function block_list($region) {
397 global $user, $theme_key;
398
399 static $blocks = array();
400
401 if (!count($blocks)) {
402 $rids = array_keys($user->roles);
403 $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 (". db_placeholders($rids) .") OR r.rid IS NULL) ORDER BY b.region, b.weight, b.module", 'b', 'bid'), array_merge(array($theme_key), $rids));
404 while ($block = db_fetch_object($result)) {
405 if (!isset($blocks[$block->region])) {
406 $blocks[$block->region] = array();
407 }
408 // Use the user's block visibility setting, if necessary
409 if ($block->custom != 0) {
410 if ($user->uid && isset($user->block[$block->module][$block->delta])) {
411 $enabled = $user->block[$block->module][$block->delta];
412 }
413 else {
414 $enabled = ($block->custom == 1);
415 }
416 }
417 else {
418 $enabled = TRUE;
419 }
420
421 // Match path if necessary
422 if ($block->pages) {
423 if ($block->visibility < 2) {
424 $path = drupal_get_path_alias($_GET['q']);
425 // Compare with the internal and path alias (if any).
426 $page_match = drupal_match_path($path, $block->pages);
427 if ($path != $_GET['q']) {
428 $page_match = $page_match || drupal_match_path($_GET['q'], $block->pages);
429 }
430 // When $block->visibility has a value of 0, the block is displayed on
431 // all pages except those listed in $block->pages. When set to 1, it
432 // is displayed only on those pages listed in $block->pages.
433 $page_match = !($block->visibility xor $page_match);
434 }
435 else {
436 $page_match = drupal_eval($block->pages);
437 }
438 }
439 else {
440 $page_match = TRUE;
441 }
442
443 if ($enabled && $page_match) {
444 // Check the current throttle status and see if block should be displayed
445 // based on server load.
446 if (!($block->throttle && (module_invoke('throttle', 'status') > 0))) {
447 // Try fetching the block from cache. Block caching is not compatible with
448 // node_access modules. We also preserve the submission of forms in blocks,
449 // by fetching from cache only if the request method is 'GET'.
450 if (!count(module_implements('node_grants')) && $_SERVER['REQUEST_METHOD'] == 'GET' && ($cid = _block_get_cache_id($block)) && ($cache = cache_get($cid, 'cache_block'))) {
451 $array = $cache->data;
452 }
453 else {
454 $array = module_invoke($block->module, 'block', 'view', $block->delta);
455 if (isset($cid)) {
456 cache_set($cid, $array, 'cache_block', CACHE_TEMPORARY);
457 }
458 }
459
460 if (isset($array) && is_array($array)) {
461 foreach ($array as $k => $v) {
462 $block->$k = $v;
463 }
464 }
465 }
466 if (isset($block->content) && $block->content) {
467 // Override default block title if a custom display title is present.
468 if ($block->title) {
469 // Check plain here to allow module generated titles to keep any markup.
470 $block->subject = $block->title == '<none>' ? '' : check_plain($block->title);
471 }
472 if (!isset($block->subject)) {
473 $block->subject = '';
474 }
475 $blocks[$block->region]["{$block->module}_{$block->delta}"] = $block;
476 }
477 }
478 }
479 }
480 // Create an empty array if there were no entries
481 if (!isset($blocks[$region])) {
482 $blocks[$region] = array();
483 }
484 return $blocks[$region];
485 }
486
487 /**
488 * Assemble the cache_id to use for a given block.
489 *
490 * The cache_id string reflects the viewing context for the current block
491 * instance, obtained by concatenating the relevant context information
492 * (user, page, ...) according to the block's cache settings (BLOCK_CACHE_*
493 * constants). Two block instances can use the same cached content when
494 * they share the same cache_id.
495 *
496 * Theme and language contexts are automatically differenciated.
497 *
498 * @param $block
499 * @return
500 * The string used as cache_id for the block.
501 */
502 function _block_get_cache_id($block) {
503 global $theme, $base_root, $user;
504
505 // User 1 being out of the regular 'roles define permissions' schema,
506 // it brings too many chances of having unwanted output get in the cache
507 // and later be served to other users. We therefore exclude user 1 from
508 // block caching.
509 if (variable_get('block_cache', 0) && $block->cache != BLOCK_NO_CACHE && $user->uid != 1) {
510 $cid_parts = array();
511
512 // Start with common sub-patterns: block identification, theme, language.
513 $cid_parts[] = $block->module;
514 $cid_parts[] = $block->delta;
515 $cid_parts[] = $theme;
516 if (module_exists('locale')) {
517 global $language;
518 $cid_parts[] = $language->language;
519 }
520
521 // 'PER_ROLE' and 'PER_USER' are mutually exclusive. 'PER_USER' can be a
522 // resource drag for sites with many users, so when a module is being
523 // equivocal, we favor the less expensive 'PER_ROLE' pattern.
524 if ($block->cache & BLOCK_CACHE_PER_ROLE) {
525 $cid_parts[] = 'r.'. implode(',', array_keys($user->roles));
526 }
527 elseif ($block->cache & BLOCK_CACHE_PER_USER) {
528 $cid_parts[] = "u.$user->uid";
529 }
530
531 if ($block->cache & BLOCK_CACHE_PER_PAGE) {
532 $cid_parts[] = $base_root . request_uri();
533 }
534
535 return implode(':', $cid_parts);
536 }
537 }