2 // $Id: block.module 144 2007-03-28 07:52:20Z thierry $
6 * Controls the boxes that are displayed around the main content.
10 * Implementation of hook_help().
12 function block_help($section) {
14 case 'admin/help#block':
15 $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>';
16 $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>';
17 $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>';
18 $output .= t('<p>A block\'s visibility depends on:</p>
20 <li>Its enabled checkbox. Disabled blocks are never shown.</li>
21 <li>Its throttle checkbox. Throttled blocks are hidden during high server loads.</li>
22 <li>Its page visibility settings. Blocks can be configured to be visible/hidden on certain pages.</li>
23 <li>Its custom visibility settings. Blocks can be configured to be visible only when specific conditions are true.</li>
24 <li>Its user visibility settings. Administrators can choose to let users decide whether to show/hide certain blocks.</li>
25 <li>Its function. Some dynamic blocks, such as those generated by modules, will be displayed only on certain pages.</li>
28 $output .= '<h3>'. t('Module blocks') .'</h3>';
29 $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/block'))) .'</p>';
30 $output .= '<h3>'. t('Administrator defined blocks') .'</h3>';
31 $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>';
32 $output .= t('<p>You can</p>
34 <li>enable, throttle and configure blocks at <a href="%admin-block">administer >> blocks</a>.</li>
35 <li>add an administrator-defined block at <a href="%admin-block-add">administer >> blocks >> add block</a>.</li>
37 ', array('%admin-block' => url('admin/block'), '%admin-block-add' => url('admin/block/add')));
38 $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>';
40 case 'admin/modules#description':
41 return t('Controls the boxes that are displayed around the main content.');
44 <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>
45 <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>
46 <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>
47 <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>
48 ", array('%throttle' => url('admin/settings/throttle')));
49 case 'admin/block/add':
50 return t('<p>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 title is used when displaying the block. The description is used in the "block" column on the <a href="%overview">blocks</a> page.</p>', array('%overview' => url('admin/block')));
55 * Implementation of hook_perm().
57 function block_perm() {
58 return array('administer blocks', 'use PHP for block visibility');
62 * Implementation of hook_menu().
64 function block_menu($may_cache) {
68 $items[] = array('path' => 'admin/block', 'title' => t('blocks'),
69 'access' => user_access('administer blocks'),
70 'callback' => 'block_admin_display');
71 $items[] = array('path' => 'admin/block/list', 'title' => t('list'),
72 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
73 $items[] = array('path' => 'admin/block/configure', 'title' => t('configure block'),
74 'access' => user_access('administer blocks'),
75 'callback' => 'block_admin_configure',
76 'type' => MENU_CALLBACK);
77 $items[] = array('path' => 'admin/block/delete', 'title' => t('delete block'),
78 'access' => user_access('administer blocks'),
79 'callback' => 'block_box_delete',
80 'type' => MENU_CALLBACK);
81 $items[] = array('path' => 'admin/block/add', 'title' => t('add block'),
82 'access' => user_access('administer blocks'),
83 'callback' => 'block_box_add',
84 'type' => MENU_LOCAL_TASK);
85 foreach (list_themes() as $key => $theme) {
87 if ($key == variable_get('theme_default', 'bluemarine')) {
88 $items[] = array('path' => 'admin/block/list/' . $key, 'title' => t('%key settings', array('%key' => $key)),
89 'access' => user_access('administer blocks'), 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
92 $items[] = array('path' => 'admin/block/list/' . $key, 'title' => t('%key settings', array('%key' => $key)),
93 'access' => user_access('administer blocks'), 'type' => MENU_LOCAL_TASK);
103 * Implementation of hook_block().
105 * Generates the administrator-defined blocks for display.
107 function block_block($op = 'list', $delta = 0, $edit = array()) {
112 $result = db_query('SELECT bid, title, info FROM {boxes} ORDER BY title');
113 while ($block = db_fetch_object($result)) {
114 $blocks[$block->bid]['info'] = $block->info ? check_plain($block->info) : check_plain($block->title);
119 $box = block_box_get($delta);
120 if (filter_access($box['format'])) {
121 return block_box_form($box);
126 block_box_save($edit, $delta);
130 $block = db_fetch_object(db_query('SELECT * FROM {boxes} WHERE bid = %d', $delta));
131 $data['subject'] = check_plain($block->title);
132 $data['content'] = check_markup($block->body, $block->format, FALSE);
138 * Update the 'blocks' DB table with the blocks currently exported by modules.
141 * Blocks currently exported by modules.
143 function _block_rehash() {
148 $result = db_query("SELECT * FROM {blocks} WHERE theme = '%s'", $theme_key);
149 while ($old_block = db_fetch_object($result)) {
150 $old_blocks[$old_block->module][$old_block->delta] = $old_block;
153 db_query("DELETE FROM {blocks} WHERE theme = '%s'", $theme_key);
155 foreach (module_list() as $module) {
156 $module_blocks = module_invoke($module, 'block', 'list');
157 if ($module_blocks) {
158 foreach ($module_blocks as $delta => $block) {
159 $block['module'] = $module;
160 $block['delta'] = $delta;
161 // If previously written to database, load values.
162 if ($old_blocks[$module][$delta]) {
163 $block['status'] = $old_blocks[$module][$delta]->status;
164 $block['weight'] = $old_blocks[$module][$delta]->weight;
165 $block['region'] = $old_blocks[$module][$delta]->region;
166 $block['visibility'] = $old_blocks[$module][$delta]->visibility;
167 $block['pages'] = $old_blocks[$module][$delta]->pages;
168 $block['custom'] = $old_blocks[$module][$delta]->custom;
169 $block['throttle'] = $old_blocks[$module][$delta]->throttle;
171 // Otherwise, use any set values, or else substitute defaults.
173 $properties = array('status' => 0, 'weight' => 0, 'region' => 'left', 'pages' => '', 'custom' => 0);
174 foreach ($properties as $property => $default) {
175 if (!isset($block[$property])) {
176 $block[$property] = $default;
181 // Reinsert blocks into table
182 db_query("INSERT INTO {blocks} (module, delta, theme, status, weight, region, visibility, pages, custom, throttle) VALUES ('%s', '%s', '%s', %d, %d, '%s', %d, '%s', %d, %d)",
183 $block['module'], $block['delta'], $theme_key, $block['status'], $block['weight'], $block['region'], $block['visibility'], $block['pages'], $block['custom'], $block['throttle']);
193 * Generate main block administration form.
195 function block_admin_display() {
196 global $theme_key, $custom_theme;
198 // If non-default theme configuration has been selected, set the custom theme.
200 $custom_theme = arg(3);
203 $custom_theme = variable_get('theme_default', 'bluemarine');
207 // Fetch and sort blocks
208 $blocks = _block_rehash();
209 usort($blocks, '_block_compare');
211 $throttle = module_exist('throttle');
212 $block_regions = system_region_list($theme_key);
215 $form['#action'] = arg(3) ? url('admin/block/list/' . $theme_key) : url('admin/block');
216 $form['#tree'] = TRUE;
217 foreach ($blocks as $i => $block) {
218 $form[$i]['module'] = array('#type' => 'value', '#value' => $block['module']);
219 $form[$i]['delta'] = array('#type' => 'value', '#value' => $block['delta']);
220 $form[$i]['info'] = array('#value' => $block['info']);
221 $form[$i]['status'] = array('#type' => 'checkbox', '#default_value' => $block['status']);
222 $form[$i]['theme'] = array('#type' => 'hidden', '#value' => $theme_key);
223 $form[$i]['weight'] = array('#type' => 'weight', '#default_value' => $block['weight']);
224 $form[$i]['region'] = array('#type' => 'select',
225 '#default_value' => isset($block['region']) ? $block['region'] : system_default_region($theme_key),
226 '#options' => $block_regions,
230 $form[$i]['throttle'] = array('#type' => 'checkbox', '#default_value' => $block['throttle']);
232 $form[$i]['configure'] = array('#value' => l(t('configure'), 'admin/block/configure/'. $block['module'] .'/'. $block['delta']));
233 if ($block['module'] == 'block') {
234 $form[$i]['delete'] = array('#value' => l(t('delete'), 'admin/block/delete/'. $block['delta']));
237 $form['submit'] = array('#type' => 'submit', '#value' => t('Save blocks'));
239 return drupal_get_form('block_admin_display', $form);
243 * Helper function for sorting blocks on admin/block.
245 * Active blocks are sorted by region, then by weight.
246 * Disabled blocks are sorted by name.
248 function _block_compare($a, $b) {
249 $status = $b['status'] - $a['status'];
250 // Separate enabled from disabled.
256 $place = strcmp($a['region'], $b['region']);
257 return $place ? $place : ($a['weight'] - $b['weight']);
261 return strcmp($a['info'], $b['info']);
266 * Process main block administration form submission.
268 function block_admin_display_submit($form_id, $form_values) {
269 foreach ($form_values as $block) {
270 db_query("UPDATE {blocks} SET status = %d, weight = %d, region = '%s', throttle = %d WHERE module = '%s' AND delta = '%s' AND theme = '%s'", $block['status'], $block['weight'], $block['region'], $block['throttle'], $block['module'], $block['delta'], $block['theme']);
272 drupal_set_message(t('The block settings have been updated.'));
277 * Theme main block administration form submission.
279 * Note: the blocks are already sorted in the right order,
280 * grouped by status, region and weight.
282 function theme_block_admin_display($form) {
285 $throttle = module_exist('throttle');
286 $block_regions = system_region_list($theme_key);
288 // Highlight regions on page to provide visual reference.
289 foreach ($block_regions as $key => $value) {
290 drupal_set_content($key, '<div class="block-region">' . $value . '</div>');
297 foreach (element_children($form) as $i) {
299 // Only take form elements that are blocks.
300 if (is_array($block['info'])) {
302 $region = $block['region']['#default_value'];
303 $status = $block['status']['#default_value'];
305 // Output region header
306 if ($status && $region != $last_region) {
307 $region_title = t('%region', array('%region' => drupal_ucfirst($block_regions[$region])));
308 $rows[] = array(array('data' => $region_title, 'class' => 'region', 'colspan' => ($throttle ? 7 : 6)));
309 $last_region = $region;
311 // Output disabled header
312 elseif ($status != $last_status) {
313 $rows[] = array(array('data' => t('Disabled'), 'class' => 'region', 'colspan' => ($throttle ? 7 : 6)));
314 $last_status = $status;
317 // Generate block row
319 array('data' => form_render($block['info']), 'class' => 'block'),
320 form_render($block['status']) . form_render($block['theme']),
321 form_render($block['weight']),
322 form_render($block['region'])
325 $row[] = form_render($block['throttle']);
327 $row[] = form_render($block['configure']);
328 $row[] = $block['delete'] ? form_render($block['delete']) : '';
334 $header = array(t('Block'), t('Enabled'), t('Weight'), t('Placement'));
336 $header[] = t('Throttle');
338 $header[] = array('data' => t('Operations'), 'colspan' => 2);
340 $output = theme('table', $header, $rows, array('id' => 'blocks'));
341 $output .= form_render($form['submit']);
342 // Also render the form_id as there is no form_render($form) call (as form_render does not appear to handle the
343 // multi-dimensional block form array very well).
344 $output .= form_render($form['form_id']);
349 function block_box_get($bid) {
350 return db_fetch_array(db_query('SELECT * FROM {boxes} WHERE bid = %d', $bid));
354 * Menu callback; displays the block configuration form.
356 function block_admin_configure($module = NULL, $delta = 0) {
358 $form['module'] = array('#type' => 'value', '#value' => $module);
359 $form['delta'] = array('#type' => 'value', '#value' => $delta);
361 $edit = db_fetch_array(db_query("SELECT pages, visibility, custom FROM {blocks} WHERE module = '%s' AND delta = '%s'", $module, $delta));
363 // Module-specific block configurations.
364 if ($settings = module_invoke($module, 'block', 'configure', $delta)) {
365 $form['block_settings'] = array(
366 '#type' => 'fieldset',
367 '#title' => t('Block specific settings'),
368 '#collapsible' => true,
371 foreach ($settings as $k => $v) {
372 $form['block_settings'][$k] = $v;
376 // Get the block subject for the page title.
377 $info = module_invoke($module, 'block', 'list');
378 drupal_set_title(t("'%name' block", array('%name' => $info[$delta]['info'])));
380 // Standard block configurations.
382 $form['user_vis_settings'] = array(
383 '#type' => 'fieldset',
384 '#title' => t('User specific visibility settings'),
385 '#collapsible' => true,
387 $form['user_vis_settings']['custom'] = array(
389 '#title' => t('Custom visibility settings'),
390 '#options' => array(t('Users cannot control whether or not they see this block.'), t('Show this block by default, but let individual users hide it.'), t('Hide this block by default but let individual users show it.')),
391 '#description' => t('Allow individual users to customize the visibility of this block in their account settings.'),
392 '#default_value' => $edit['custom'],
394 $form['page_vis_settings'] = array(
395 '#type' => 'fieldset',
396 '#title' => t('Page specific visibility settings'),
397 '#collapsible' => true,
399 $access = user_access('use PHP for block visibility');
401 if ($edit['visibility'] == 2 && !$access) {
402 $form['page_vis_settings'] = array();
403 $form['page_vis_settings']['visibility'] = array('#type' => 'value', '#value' => 2);
404 $form['page_vis_settings']['pages'] = array('#type' => 'value', '#value' => $edit['pages']);
407 $options = array(t('Show on every page except the listed pages.'), t('Show on only the listed pages.'));
408 $description = t("Enter one page per line as Drupal paths. The '*' character is a wildcard. Example paths are '%blog' for the blog page and %blog-wildcard for every personal blog. %front is the front page.", array('%blog' => theme('placeholder', 'blog'), '%blog-wildcard' => theme('placeholder', 'blog/*'), '%front' => theme('placeholder', '<front>')));
411 $options[] = t('Show if the following PHP code returns <code>TRUE</code> (PHP-mode, experts only).');
412 $description .= t('If the PHP-mode is chosen, enter PHP code between %php. Note that executing incorrect PHP-code can break your Drupal site.', array('%php' => theme('placeholder', '<?php ?>')));
414 $form['page_vis_settings']['visibility'] = array(
416 '#title' => t('Show block on specific pages'),
417 '#options' => $options,
418 '#default_value' => $edit['visibility'],
420 $form['page_vis_settings']['pages'] = array(
421 '#type' => 'textarea',
422 '#title' => t('Pages'),
423 '#default_value' => $edit['pages'],
424 '#description' => $description,
428 $form['submit'] = array(
430 '#value' => t('Save block'),
433 return drupal_get_form('block_admin_configure', $form);
436 function block_admin_configure_validate($form_id, $form_values) {
437 if ($form_values['module'] == 'block') {
438 if (empty($form_values['info']) || db_num_rows(db_query("SELECT bid FROM {boxes} WHERE bid != %d AND info = '%s'", $form_values['delta'], $form_values['info']))) {
439 form_set_error('info', t('Please ensure that each block description is unique.'));
444 function block_admin_configure_submit($form_id, $form_values) {
445 if (!form_get_errors()) {
446 db_query("UPDATE {blocks} SET visibility = %d, pages = '%s', custom = %d WHERE module = '%s' AND delta = '%s'", $form_values['visibility'], $form_values['pages'], $form_values['custom'], $form_values['module'], $form_values['delta']);
447 module_invoke($form_values['module'], 'block', 'save', $form_values['delta'], $form_values);
448 drupal_set_message(t('The block configuration has been saved.'));
450 return 'admin/block';
455 * Menu callback; displays the block creation form.
457 function block_box_add() {
458 $form = block_box_form();
459 $form['submit'] = array('#type' => 'submit', '#value' => t('Save block'));
461 return drupal_get_form('block_box_add', $form);
464 function block_box_add_validate($form_id, $form_values) {
465 if (empty($form_values['info']) || db_num_rows(db_query("SELECT info FROM {boxes} WHERE info = '%s'", $form_values['info']))) {
466 form_set_error('info', t('Please ensure that each block description is unique.'));
470 function block_box_add_submit($form_id, $form_values) {
471 if (!form_get_errors()) {
472 if (block_box_save($form_values)) {
473 drupal_set_message(t('The block has been created.'));
474 return 'admin/block';
480 * Menu callback; confirm deletion of custom blocks.
482 function block_box_delete($bid = 0) {
483 $box = block_box_get($bid);
484 $form['info'] = array('#type' => 'hidden', '#value' => $box['info'] ? $box['info'] : $box['title']);
485 $form['bid'] = array('#type' => 'hidden', '#value' => $bid);
487 return confirm_form('block_box_delete_confirm', $form, t('Are you sure you want to delete the block %name?', array('%name' => theme('placeholder', $box['info']))), 'admin/block', '', t('Delete'), t('Cancel'));
491 * Deletion of custom blocks.
493 function block_box_delete_confirm_submit($form_id, $form_values) {
494 db_query('DELETE FROM {boxes} WHERE bid = %d', $form_values['bid']);
495 drupal_set_message(t('The block %name has been removed.', array('%name' => theme('placeholder', $form_values['info']))));
497 return 'admin/block';
500 function block_box_form($edit = array()) {
501 $form['info'] = array(
502 '#type' => 'textfield',
503 '#title' => t('Block description'),
504 '#default_value' => $edit['info'],
506 '#description' => t('A brief description of your block. Used on the <a href="%overview">block overview page</a>.', array('%overview' => url('admin/block'))),
510 $form['title'] = array(
511 '#type' => 'textfield',
512 '#title' => t('Block title'),
513 '#default_value' => $edit['title'],
515 '#description' => t('The title of the block as shown to the user.'),
518 $form['body_filter']['#weight'] = -17;
519 $form['body_filter']['body'] = array(
520 '#type' => 'textarea',
521 '#title' => t('Block body'),
522 '#default_value' => $edit['body'],
524 '#description' => t('The content of the block as shown to the user.'),
527 $form['body_filter']['format'] = filter_form($edit['format'], -16);
532 function block_box_save($edit, $delta = NULL) {
533 if (!filter_access($edit['format'])) {
534 $edit['format'] = FILTER_FORMAT_DEFAULT;
538 db_query("UPDATE {boxes} SET title = '%s', body = '%s', info = '%s', format = %d WHERE bid = %d", $edit['title'], $edit['body'], $edit['info'], $edit['format'], $delta);
541 db_query("INSERT INTO {boxes} (title, body, info, format) VALUES ('%s', '%s', '%s', %d)", $edit['title'], $edit['body'], $edit['info'], $edit['format']);
547 * Implementation of hook_user().
549 * Allow users to decide which custom blocks to display when they visit
552 function block_user($type, $edit, &$user, $category = NULL) {
555 if ($category == 'account') {
556 $result = db_query('SELECT * FROM {blocks} WHERE status = 1 AND custom != 0 ORDER BY weight, module, delta');
557 $form['block'] = array('#type' => 'fieldset', '#title' => t('Block configuration'), '#weight' => 3, '#collapsible' => TRUE, '#tree' => TRUE);
558 while ($block = db_fetch_object($result)) {
559 $data = module_invoke($block->module, 'block', 'list');
560 if ($data[$block->delta]['info']) {
562 $form['block'][$block->module][$block->delta] = array('#type' => 'checkbox', '#title' => $data[$block->delta]['info'], '#default_value' => isset($user->block[$block->module][$block->delta]) ? $user->block[$block->module][$block->delta] : ($block->custom == 1));
573 if (!$edit['block']) {
574 $edit['block'] = array();
581 * Return all blocks in the specified region for the current user.
584 * The name of a region.
587 * An array of block objects, indexed with <i>module</i>_<i>delta</i>.
588 * If you are displaying your blocks in one or two sidebars, you may check
589 * whether this array is empty to see how many columns are going to be
593 * Add a proper primary key (bid) to the blocks table so we don't have
594 * to mess around with this <i>module</i>_<i>delta</i> construct.
595 * Currently, the blocks table has no primary key defined!
597 function block_list($region) {
598 global $user, $theme_key;
600 static $blocks = array();
602 if (!count($blocks)) {
603 $result = db_query("SELECT * FROM {blocks} WHERE theme = '%s' AND status = 1 ORDER BY region, weight, module", $theme_key);
604 while ($block = db_fetch_object($result)) {
605 if (!isset($blocks[$block->region])) {
606 $blocks[$block->region] = array();
608 // Use the user's block visibility setting, if necessary
609 if ($block->custom != 0) {
610 if ($user->uid && isset($user->block[$block->module][$block->delta])) {
611 $enabled = $user->block[$block->module][$block->delta];
614 $enabled = ($block->custom == 1);
621 // Match path if necessary
623 if ($block->visibility < 2) {
624 $path = drupal_get_path_alias($_GET['q']);
625 $regexp = '/^('. preg_replace(array('/(\r\n?|\n)/', '/\\\\\*/', '/(^|\|)\\\\<front\\\\>($|\|)/'), array('|', '.*', '\1'. preg_quote(variable_get('site_frontpage', 'node'), '/') .'\2'), preg_quote($block->pages, '/')) .')$/';
626 $page_match = !($block->visibility xor preg_match($regexp, $path));
629 $page_match = drupal_eval($block->pages);
636 if ($enabled && $page_match) {
637 // Check the current throttle status and see if block should be displayed
638 // based on server load.
639 if (!($block->throttle && (module_invoke('throttle', 'status') > 0))) {
640 $array = module_invoke($block->module, 'block', 'view', $block->delta);
641 if (isset($array) && is_array($array)) {
642 foreach ($array as $k => $v) {
647 if (isset($block->content) && $block->content) {
648 $blocks[$block->region]["{$block->module}_{$block->delta}"] = $block;
653 // Create an empty array if there were no entries
654 if (!isset($blocks[$region])) {
655 $blocks[$region] = array();
657 return $blocks[$region];