You are here

function node_teaser in Drupal 4

Same name and namespace in other branches
  1. 5 modules/node/node.module \node_teaser()
  2. 6 modules/node/node.module \node_teaser()

Automatically generate a teaser for a node body in a given format.

3 calls to node_teaser()
aggregator_page_rss in modules/aggregator.module
Menu callback; generate an RSS 0.92 feed of aggregator items or categories.
node_preview in modules/node.module
Generate a node preview.
node_submit in modules/node.module
Prepare node for save and allow modules to make changes.

File

modules/node.module, line 150
The core that allows content to be submitted to the site.

Code

function node_teaser($body, $format = NULL) {
  $size = variable_get('teaser_length', 600);

  // find where the delimiter is in the body
  $delimiter = strpos($body, '<!--break-->');

  // If the size is zero, and there is no delimiter, the entire body is the teaser.
  if ($size == 0 && $delimiter === FALSE) {
    return $body;
  }

  // If a valid delimiter has been specified, use it to chop off the teaser.
  if ($delimiter !== FALSE) {
    return substr($body, 0, $delimiter);
  }

  // We check for the presence of the PHP evaluator filter in the current
  // format. If the body contains PHP code, we do not split it up to prevent
  // parse errors.
  if (isset($format)) {
    $filters = filter_list_format($format);
    if (isset($filters['filter/1']) && strpos($body, '<?') !== FALSE) {
      return $body;
    }
  }

  // If we have a short body, the entire body is the teaser.
  if (strlen($body) < $size) {
    return $body;
  }

  // The teaser may not be longer than maximum length specified. Initial slice.
  $teaser = truncate_utf8($body, $size);
  $position = 0;

  // Cache the reverse of the teaser.
  $reversed = strrev($teaser);

  // In some cases, no delimiter has been specified. In this case, we try to
  // split at paragraph boundaries.
  $breakpoints = array(
    '</p>' => 0,
    '<br />' => 6,
    '<br>' => 4,
    "\n" => 1,
  );

  // We use strpos on the reversed needle and haystack for speed.
  foreach ($breakpoints as $point => $offset) {
    $length = strpos($reversed, strrev($point));
    if ($length !== FALSE) {
      $position = -$length - $offset;
      return $position == 0 ? $teaser : substr($teaser, 0, $position);
    }
  }

  // When even the first paragraph is too long, we try to split at the end of
  // the last full sentence.
  $breakpoints = array(
    '. ' => 1,
    '! ' => 1,
    '? ' => 1,
    '。' => 0,
    '؟ ' => 1,
  );
  $min_length = strlen($reversed);
  foreach ($breakpoints as $point => $offset) {
    $length = strpos($reversed, strrev($point));
    if ($length !== FALSE) {
      $min_length = min($length, $min_length);
      $position = 0 - $length - $offset;
    }
  }
  return $position == 0 ? $teaser : substr($teaser, 0, $position);
}