Spike PHPCoverage Details: block.module

Line #FrequencySource Line
1 <?php
2 // $Id: block.module,v 1.301 2008/03/21 08:41:25 dries 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('build/block/add'))) .'</p>';
90       return $output;
91     case '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(
114     'administer blocks' => t('Select which blocks are displayed, and arrange them on the page.'),
115     'use PHP for block visibility' => t('Enter PHP code in the field for block visibility settings. %warning', array('%warning' => t('Warning: Give to trusted roles only; this permission has security implications.'))),
116   );
117 }
118 
119 /**
120  * Implementation of hook_menu().
121  */
122 function block_menu() {
123   $items['admin/build/block'] = array(
1241    'title' => 'Blocks',
125     'description' => 'Configure what block content appears in your site\'s sidebars and other regions.',
126     'page callback' => 'block_admin_display',
127     'access arguments' => array('administer blocks'),
128     'file' => 'block.admin.inc',
129   );
130   $items['admin/build/block/list'] = array(
1311    'title' => 'List',
132     'type' => MENU_DEFAULT_LOCAL_TASK,
133     'weight' => -10,
134   );
135   $items['admin/build/block/list/js'] = array(
1361    'title' => 'JavaScript List Form',
137     'page callback' => 'block_admin_display_js',
138     'type' => MENU_CALLBACK,
139     'file' => 'block.admin.inc',
140   );
141   $items['admin/build/block/configure'] = array(
1421    'title' => 'Configure block',
143     'page callback' => 'drupal_get_form',
144     'page arguments' => array('block_admin_configure'),
145     'type' => MENU_CALLBACK,
146     'file' => 'block.admin.inc',
147   );
148   $items['admin/build/block/delete'] = array(
1491    'title' => 'Delete block',
150     'page callback' => 'drupal_get_form',
151     'page arguments' => array('block_box_delete'),
152     'type' => MENU_CALLBACK,
153     'file' => 'block.admin.inc',
154   );
155   $items['build/block/add'] = array(
1561    'title' => 'Add block',
157     'page callback' => 'drupal_get_form',
158     'page arguments' => array('block_add_block_form'),
159     'type' => MENU_LOCAL_TASK,
160     'file' => 'block.admin.inc',
161   );
1621  $default = variable_get('theme_default', 'garland');
1631  foreach (list_themes() as $key => $theme) {
164     $items['admin/build/block/list/'. $key] = array(
1651      'title' => check_plain($theme->info['name']),
166       'page arguments' => array($key),
167       'type' => $key == $default ? MENU_DEFAULT_LOCAL_TASK : MENU_LOCAL_TASK,
168       'weight' => $key == $default ? -10 : 0,
169       'file' => 'block.admin.inc',
170       'access callback' => '_block_themes_access',
171       'access arguments' => array($theme),
172     );
173   }
1741  return $items;
175 }
176 
177 /**
178  * Menu item access callback - only admin or enabled themes can be accessed
179  */
180 function _block_themes_access($theme) {
181   return user_access('administer blocks') && ($theme->status || $theme->name == variable_get('admin_theme', '0'));
182 }
183 
184 /**
185  * Implementation of hook_block().
186  *
187  * Generates the administrator-defined blocks for display.
188  */
189 function block_block($op = 'list', $delta = 0, $edit = array()) {
190   switch ($op) {
191     case 'list':
192       $blocks = array();
193 
194       $result = db_query('SELECT bid, info FROM {boxes} ORDER BY info');
195       while ($block = db_fetch_object($result)) {
196         $blocks[$block->bid]['info'] = $block->info;
197         // Not worth caching.
198         $blocks[$block->bid]['cache'] = BLOCK_NO_CACHE;
199       }
200       return $blocks;
201 
202     case 'configure':
203       $box = array('format' => FILTER_FORMAT_DEFAULT);
204       if ($delta) {
205         $box = block_box_get($delta);
206       }
207       if (filter_access($box['format'])) {
208         return block_box_form($box);
209       }
210       break;
211 
212     case 'save':
213       block_box_save($edit, $delta);
214       break;
215 
216     case 'view':
217       $block = db_fetch_object(db_query('SELECT body, format FROM {boxes} WHERE bid = %d', $delta));
218       $data['content'] = check_markup($block->body, $block->format, FALSE);
219       return $data;
220   }
221 }
222 
223 /**
224  * Update the 'blocks' DB table with the blocks currently exported by modules.
225  *
226  * @return
227  *   Blocks currently exported by modules.
228  */
229 function _block_rehash() {
230   global $theme_key;
231 
232   init_theme();
233 
234   $result = db_query("SELECT * FROM {blocks} WHERE theme = '%s'", $theme_key);
235   $old_blocks = array();
236   while ($old_block = db_fetch_array($result)) {
237     $old_blocks[$old_block['module']][$old_block['delta']] = $old_block;
238   }
239 
240   $blocks = array();
241   // Valid region names for the theme.
242   $regions = system_region_list($theme_key);
243 
244   foreach (module_list() as $module) {
245     $module_blocks = module_invoke($module, 'block', 'list');
246     if ($module_blocks) {
247       foreach ($module_blocks as $delta => $block) {
248         if (empty($old_blocks[$module][$delta])) {
249           // If it's a new block, add identifiers.
250           $block['module'] = $module;
251           $block['delta']  = $delta;
252           $block['theme']  = $theme_key;
253           if (!isset($block['pages'])) {
254             // {block}.pages is type 'text', so it cannot have a
255             // default value, and not null, so we need to provide
256             // value if the module did not.
257             $block['pages']  = '';
258           }
259           // Add defaults and save it into the database.
260           drupal_write_record('blocks', $block);
261           // Set region to none if not enabled.
262           $block['region'] = $block['status'] ? $block['region'] : BLOCK_REGION_NONE;
263           // Add to the list of blocks we return.
264           $blocks[] = $block;
265         }
266         else {
267           // If it's an existing block, database settings should overwrite
268           // the code. But aside from 'info' everything that's definable in
269           // code is stored in the database and we do not store 'info', so we
270           // do not need to update the database here.
271           // Add 'info' to this block.
272           $old_blocks[$module][$delta]['info'] = $block['info'];
273           // If the region name does not exist, disable the block and assign it to none.
274           if (!empty($old_blocks[$module][$delta]['region']) && !isset($regions[$old_blocks[$module][$delta]['region']])) {
275             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');
276             $old_blocks[$module][$delta]['status'] = 0;
277             $old_blocks[$module][$delta]['region'] = BLOCK_REGION_NONE;
278           }
279           else {
280             $old_blocks[$module][$delta]['region'] = $old_blocks[$module][$delta]['status'] ? $old_blocks[$module][$delta]['region'] : BLOCK_REGION_NONE;
281           }
282           // Add this block to the list of blocks we return.
283           $blocks[] = $old_blocks[$module][$delta];
284           // Remove this block from the list of blocks to be deleted.
285           unset($old_blocks[$module][$delta]);
286         }
287       }
288     }
289   }
290 
291   // Remove blocks that are no longer defined by the code from the database.
292   foreach ($old_blocks as $module => $old_module_blocks) {
293     foreach ($old_module_blocks as $delta => $block) {
294       db_query("DELETE FROM {blocks} WHERE module = '%s' AND delta = '%s' AND theme = '%s'", $module, $delta, $theme_key);
295     }
296   }
297   return $blocks;
298 }
299 
300 function block_box_get($bid) {
301   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));
302 }
303 
304 /**
305  * Define the custom block form.
306  */
307 function block_box_form($edit = array()) {
308   $edit += array(
309     'info' => '',
310     'body' => '',
311   );
312   $form['info'] = array(
313     '#type' => 'textfield',
314     '#title' => t('Block description'),
315     '#default_value' => $edit['info'],
316     '#maxlength' => 64,
317     '#description' => t('A brief description of your block. Used on the <a href="@overview">block overview page</a>.', array('@overview' => url('admin/build/block'))),
318     '#required' => TRUE,
319     '#weight' => -19,
320   );
321   $form['body_field']['#weight'] = -17;
322   $form['body_field']['body'] = array(
323     '#type' => 'textarea',
324     '#title' => t('Block body'),
325     '#default_value' => $edit['body'],
326     '#rows' => 15,
327     '#description' => t('The content of the block as shown to the user.'),
328     '#weight' => -17,
329   );
330   if (!isset($edit['format'])) {
331     $edit['format'] = FILTER_FORMAT_DEFAULT;
332   }
333   $form['body_field']['format'] = filter_form($edit['format'], -16);
334 
335   return $form;
336 }
337 
338 function block_box_save($edit, $delta) {
339   if (!filter_access($edit['format'])) {
340     $edit['format'] = FILTER_FORMAT_DEFAULT;
341   }
342 
343   db_query("UPDATE {boxes} SET body = '%s', info = '%s', format = %d WHERE bid = %d", $edit['body'], $edit['info'], $edit['format'], $delta);
344 
345   return TRUE;
346 }
347 
348 /**
349  * Implementation of hook_user().
350  *
351  * Allow users to decide which custom blocks to display when they visit
352  * the site.
353  */
354 function block_user($type, $edit, &$account, $category = NULL) {
355   switch ($type) {
3561    case 'form':
357       if ($category == 'account') {
358         $rids = array_keys($account->roles);
359         $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);
360         $form['block'] = array('#type' => 'fieldset', '#title' => t('Block configuration'), '#weight' => 3, '#collapsible' => TRUE, '#tree' => TRUE);
361         while ($block = db_fetch_object($result)) {
362           $data = module_invoke($block->module, 'block', 'list');
363           if ($data[$block->delta]['info']) {
364             $return = TRUE;
365             $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));
366           }
367         }
368 
369         if (!empty($return)) {
370           return $form;
371         }
372       }
373 
374       break;
3751    case 'validate':
376       if (empty($edit['block'])) {
377         $edit['block'] = array();
378       }
379       return $edit;
380   }
381 }
382 
383 /**
384  * Return all blocks in the specified region for the current user.
385  *
386  * @param $region
387  *   The name of a region.
388  *
389  * @return
390  *   An array of block objects, indexed with <i>module</i>_<i>delta</i>.
391  *   If you are displaying your blocks in one or two sidebars, you may check
392  *   whether this array is empty to see how many columns are going to be
393  *   displayed.
394  *
395  * @todo
396  *   Now that the blocks table has a primary key, we should use that as the
397  *   array key instead of <i>module</i>_<i>delta</i>.
398  */
399 function block_list($region) {
400   static $blocks = array();
401 
402   if (!count($blocks)) {
403     $blocks = _block_load_blocks();
404   }
405 
406   // Create an empty array if there were no entries
407   if (!isset($blocks[$region])) {
408     $blocks[$region] = array();
409   }
410 
411   $blocks[$region] = _block_render_blocks($blocks[$region]);
412 
413   return $blocks[$region];
414 }
415 
416 /**
417  * Load blocks information from the database
418  */
419 function _block_load_blocks() {
420   global $user, $theme_key;
421 
422   $blocks = array();
423   $rids = array_keys($user->roles);
424   $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));
425   while ($block = db_fetch_object($result)) {
426     if (!isset($blocks[$block->region])) {
427       $blocks[$block->region] = array();
428     }
429     // Use the user's block visibility setting, if necessary
430     if ($block->custom != 0) {
431       if ($user->uid && isset($user->block[$block->module][$block->delta])) {
432         $enabled = $user->block[$block->module][$block->delta];
433       }
434       else {
435         $enabled = ($block->custom == 1);
436       }
437     }
438     else {
439       $enabled = TRUE;
440     }
441 
442     // Match path if necessary
443     if ($block->pages) {
444       if ($block->visibility < 2) {
445         $path = drupal_get_path_alias($_GET['q']);
446         // Compare with the internal and path alias (if any).
447         $page_match = drupal_match_path($path, $block->pages);
448         if ($path != $_GET['q']) {
449           $page_match = $page_match || drupal_match_path($_GET['q'], $block->pages);
450         }
451         // When $block->visibility has a value of 0, the block is displayed on
452         // all pages except those listed in $block->pages. When set to 1, it
453         // is displayed only on those pages listed in $block->pages.
454         $page_match = !($block->visibility xor $page_match);
455       }
456       else {
457         $page_match = drupal_eval($block->pages);
458       }
459     }
460     else {
461       $page_match = TRUE;
462     }
463     $block->enabled = $enabled;
464     $block->page_match = $page_match;
465     $blocks[$block->region]["{$block->module}_{$block->delta}"] = $block;
466   }
467   return $blocks;
468 }
469 
470 /**
471  * Render the content and subject for a set of blocks.
472  *
473  * @param $region_blocks
474  *   An array of block objects such as returned for one region by _block_load_blocks()
475  *
476  * @return
477  *   An array of visible or not-throttled blocks with subject and content rendered.
478  */
479 function _block_render_blocks($region_blocks) {
480   foreach ($region_blocks as $key => $block) {
481     // Render the block content if it has not been created already.
482     if (!isset($block->content)) {
483       // Erase the block from the static array - we'll put it back if it has content.
484       unset($region_blocks[$key]);
485       if ($block->enabled && $block->page_match) {
486         // Check the current throttle status and see if block should be displayed
487         // based on server load.
488         if (!($block->throttle && (module_invoke('throttle', 'status') > 0))) {
489           // Try fetching the block from cache. Block caching is not compatible with
490           // node_access modules. We also preserve the submission of forms in blocks,
491           // by fetching from cache only if the request method is 'GET'.
492           if (!count(module_implements('node_grants')) && $_SERVER['REQUEST_METHOD'] == 'GET' && ($cid = _block_get_cache_id($block)) && ($cache = cache_get($cid, 'cache_block'))) {
493             $array = $cache->data;
494           }
495           else {
496             $array = module_invoke($block->module, 'block', 'view', $block->delta);
497             if (isset($cid)) {
498               cache_set($cid, $array, 'cache_block', CACHE_TEMPORARY);
499             }
500           }
501 
502           if (isset($array) && is_array($array)) {
503             foreach ($array as $k => $v) {
504               $block->$k = $v;
505             }
506           }
507         }
508         if (isset($block->content) && $block->content) {
509           // Override default block title if a custom display title is present.
510           if ($block->title) {
511             // Check plain here to allow module generated titles to keep any markup.
512             $block->subject = $block->title == '<none>' ? '' : check_plain($block->title);
513           }
514           if (!isset($block->subject)) {
515             $block->subject = '';
516           }
517           $region_blocks["{$block->module}_{$block->delta}"] = $block;
518         }
519       }
520     }
521   }
522   return $region_blocks;
523 }
524 
525 /**
526  * Assemble the cache_id to use for a given block.
527  *
528  * The cache_id string reflects the viewing context for the current block
529  * instance, obtained by concatenating the relevant context information
530  * (user, page, ...) according to the block's cache settings (BLOCK_CACHE_*
531  * constants). Two block instances can use the same cached content when
532  * they share the same cache_id.
533  *
534  * Theme and language contexts are automatically differenciated.
535  *
536  * @param $block
537  * @return
538  *   The string used as cache_id for the block.
539  */
540 function _block_get_cache_id($block) {
541   global $theme, $base_root, $user;
542 
543   // User 1 being out of the regular 'roles define permissions' schema,
544   // it brings too many chances of having unwanted output get in the cache
545   // and later be served to other users. We therefore exclude user 1 from
546   // block caching.
547   if (variable_get('block_cache', 0) && $block->cache != BLOCK_NO_CACHE && $user->uid != 1) {
548     $cid_parts = array();
549 
550     // Start with common sub-patterns: block identification, theme, language.
551     $cid_parts[] = $block->module;
552     $cid_parts[] = $block->delta;
553     $cid_parts[] = $theme;
554     if (module_exists('locale')) {
555       global $language;
556       $cid_parts[] = $language->language;
557     }
558 
559     // 'PER_ROLE' and 'PER_USER' are mutually exclusive. 'PER_USER' can be a
560     // resource drag for sites with many users, so when a module is being
561     // equivocal, we favor the less expensive 'PER_ROLE' pattern.
562     if ($block->cache & BLOCK_CACHE_PER_ROLE) {
563       $cid_parts[] = 'r.'. implode(',', array_keys($user->roles));
564     }
565     elseif ($block->cache & BLOCK_CACHE_PER_USER) {
566       $cid_parts[] = "u.$user->uid";
567     }
568 
569     if ($block->cache & BLOCK_CACHE_PER_PAGE) {
570       $cid_parts[] = $base_root . request_uri();
571     }
572 
573     return implode(':', $cid_parts);
574   }
575 }