From 225214683fdb9f565decd782f149b67e3bb0358d Mon Sep 17 00:00:00 2001
From: Bob Vincent <bobvin@pillars.net>
Date: Mon, 16 May 2011 11:19:32 -0400
Subject: [PATCH 1/2] Issue #221257 by pillarsdotnet: text_summary() should be HTML-aware.

---
 modules/field/modules/text/text.info   |    1 +
 modules/field/modules/text/text.module |  217 ++++++++++++++++++++------------
 modules/field/modules/text/text.test   |  197 ++++++++++++++++-------------
 3 files changed, 242 insertions(+), 173 deletions(-)

diff --git a/modules/field/modules/text/text.info b/modules/field/modules/text/text.info
index b424d2d452f05bb23498dac2e1504826c59c7ae6..e3f045eea3a698f22e0602eb837afe698c4d6c6f 100644
--- a/modules/field/modules/text/text.info
+++ b/modules/field/modules/text/text.info
@@ -4,5 +4,6 @@ package = Core
 version = VERSION
 core = 8.x
 dependencies[] = field
+dependencies[] = filter
 files[] = text.test
 required = TRUE
diff --git a/modules/field/modules/text/text.module b/modules/field/modules/text/text.module
index 89c605cf2c046eb48d448e20d27a63ef88a8583f..9829123927a53cebb5809c5f2bb3d98ec67266c6 100644
--- a/modules/field/modules/text/text.module
+++ b/modules/field/modules/text/text.module
@@ -330,49 +330,38 @@ function _text_sanitize($instance, $langcode, $item, $column) {
  * @param $text
  *   The content for which a summary will be generated.
  * @param $format
- *   The format of the content.
- *   If the PHP filter is present and $text contains PHP code, we do not
- *   split it up to prevent parse errors.
- *   If the line break filter is present then we treat newlines embedded in
- *   $text as line breaks.
- *   If the htmlcorrector filter is present, it will be run on the generated
- *   summary (if different from the incoming $text).
+ *   The format of the content. The $text string will be passed through
+ *   check_markup() before generating a summary.
  * @param $size
- *   The desired character length of the summary. If omitted, the default
- *   value will be used. Ignored if the special delimiter is present
- *   in $text.
+ *   The desired character length of the summary, not counting HTML tags. If
+ *   omitted, the default value will be used. Ignored if the special delimiter
+ *   is present in $text.
  * @return
  *   The generated summary.
  */
 function text_summary($text, $format = NULL, $size = NULL) {
-
-  if (!isset($size)) {
-    // What used to be called 'teaser' is now called 'summary', but
-    // the variable 'teaser_length' is preserved for backwards compatibility.
-    $size = variable_get('teaser_length', 600);
-  }
-
   // Find where the delimiter is in the body
   $delimiter = strpos($text, '<!--break-->');
 
-  // If the size is zero, and there is no delimiter, the entire body is the summary.
-  if ($size == 0 && $delimiter === FALSE) {
-    return $text;
-  }
-
   // If a valid delimiter has been specified, use it to chop off the summary.
   if ($delimiter !== FALSE) {
-    return substr($text, 0, $delimiter);
+    // Since there is no drupal_strpos(), we must use substr() instead of
+    // drupal_substr() here, or we'll break on UTF-8 input.
+    return trim(check_markup(substr($text, 0, $delimiter), $format));
   }
 
-  // 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['php_code']) && $filters['php_code']->status && strpos($text, '<?') !== FALSE) {
-      return $text;
-    }
+  // Start with the trimmed, formatted version of $text.
+  $text = trim(check_markup($text, $format));
+
+  if (!isset($size)) {
+    // What used to be called 'teaser' is now called 'summary', but
+    // the variable 'teaser_length' is preserved for backwards compatibility.
+    $size = variable_get('teaser_length', 600);
+  }
+
+  // If the size is zero, the entire body is the summary.
+  if ($size == 0) {
+    return $text;
   }
 
   // If we have a short body, the entire body is the summary.
@@ -380,68 +369,130 @@ function text_summary($text, $format = NULL, $size = NULL) {
     return $text;
   }
 
-  // If the delimiter has not been specified, try to split at paragraph or
-  // sentence boundaries.
+  // Generate a DOM Document to hold the full body.
+  $body_doc = filter_dom_load($text);
+  $body_node = $body_doc->documentElement;
 
-  // The summary may not be longer than maximum length specified. Initial slice.
-  $summary = truncate_utf8($text, $size);
+  // Generate a DOM Document to hold the summary.
+  $summary_doc = new DOMDocument();
 
-  // Store the actual length of the UTF8 string -- which might not be the same
-  // as $size.
-  $max_rpos = strlen($summary);
+  // Recursively copy each child node from $body_node to $summary_doc
+  // until $size limit is reached.
+  _text_summarize($body_node, $size, $summary_doc, $summary_doc);
 
-  // How much to cut off the end of the summary so that it doesn't end in the
-  // middle of a paragraph, sentence, or word.
-  // Initialize it to maximum in order to find the minimum.
-  $min_rpos = $max_rpos;
+  // Convert the summary document back to XHTML.
+  $output = filter_dom_serialize($summary_doc);
 
-  // Store the reverse of the summary. We use strpos on the reversed needle and
-  // haystack for speed and convenience.
-  $reversed = strrev($summary);
-
-  // Build an array of arrays of break points grouped by preference.
-  $break_points = array();
-
-  // A paragraph near the end of sliced summary is most preferable.
-  $break_points[] = array('</p>' => 0);
-
-  // If no complete paragraph then treat line breaks as paragraphs.
-  $line_breaks = array('<br />' => 6, '<br>' => 4);
-  // Newline only indicates a line break if line break converter
-  // filter is present.
-  if (isset($filters['filter_autop'])) {
-    $line_breaks["\n"] = 1;
+  // DOM automatically wraps plain-text in a <p> tag, but if the original
+  // formatted version was plaintext, then the summary should be plaintext
+  // also.
+  if ($text === strip_tags($text)) {
+    $output = strip_tags($output);
   }
-  $break_points[] = $line_breaks;
-
-  // If the first paragraph is too long, split at the end of a sentence.
-  $break_points[] = array('. ' => 1, '! ' => 1, '? ' => 1, '。' => 0, '؟ ' => 1);
+  return trim($output);
+}
 
-  // Iterate over the groups of break points until a break point is found.
-  foreach ($break_points as $points) {
-    // Look for each break point, starting at the end of the summary.
-    foreach ($points as $point => $offset) {
-      // The summary is already reversed, but the break point isn't.
-      $rpos = strpos($reversed, strrev($point));
-      if ($rpos !== FALSE) {
-        $min_rpos = min($rpos + $offset, $min_rpos);
-      }
+/**
+ * Helper function for text_summary.
+ *
+ * Recursively copies elements from $body to $summary, subtracting the length
+ * of the textContent portions from $size until $size reaches zero.
+ *
+ * @param $body
+ *   The source DOMNode.
+ * @param $size
+ *   The maximum number of textContent characters to copy.
+ * @param $summary
+ *   The destination DOMNode.
+ * @param $doc
+ *   The destination DOMDocument. Should be the same as the
+ *   $summary->ownerDocument property.
+ * @param $parents
+ *   An array of tag names of ancestor nodes.
+ *
+ * @return
+ *   The number of additional characters left to copy.
+ */
+function _text_summarize($body, $size, $summary, $doc, $parents = array()) {
+  static $sentence_splitter;
+  if (!isset($sentence_splitter)) {
+    // According to http://unicode.org/review/pr-23.html,
+    // these are the Unicode Sentence_Terminal characters.
+    $stops =
+      '!' . // Exclamation mark.
+      '.' . // Full stop.
+      '?' . // Question mark.
+      '?' . // Armenian full stop.
+      '?' . // Arabic question mark.
+      '?' . // Arabic full stop.
+      '?' . // Syriac end of paragraph.
+      '?' . // Syriac supralinear full stop.
+      '?' . // Syriac sublinear full stop.
+      '?' . // Devanagari danda.
+      '?' . // Myanmar sign little section.
+      '?' . // Myanmar sign section.
+      '?' . // Ethiopic full stop.
+      '?' . // Ethiopic question mark.
+      '?' . // Ethiopic paragraph separator.
+      '?' . // Canadian syllabics full stop.
+      '?' . // Mongolian full stop.
+      '?' . // Mongolian manchu full stop.
+      '?' . // Double exclamation mark.
+      '?' . // Interrobang.
+      '?' . // Double question mark.
+      '?' . // Question exclamation mark.
+      '?' . // Exclamation question mark.
+      '?' . // Ideographic full stop.
+      '?' . // Small full stop.
+      '?' . // Small exclamation mark.
+      '?' . // Fullwidth exclamation mark.
+      '?' . // Fullwidth full stop.
+      '?' . // Fullwidth question mark.
+      '?';  // Halfwidth ideographic full stop.
+    // We split after Sentence_Terminal characters only if preceded by a Letter
+    // character and followed by a Separator character.
+    $sentence_splitter = '/(?<=\p{L}[' . $stops . '])(?=\p{Z})/u';
+  }
+  if ($body->nodeType === XML_TEXT_NODE) {
+    $text_length = drupal_strlen($body->textContent);
+    if ($text_length <= $size) {
+      $size -= $text_length;
+      $summary->appendChild($doc->createTextNode($body->textContent));
+      return $size;
     }
-
-    // If a break point was found in this group, slice and stop searching.
-    if ($min_rpos !== $max_rpos) {
-      // Don't slice with length 0. Length must be <0 to slice from RHS.
-      $summary = ($min_rpos === 0) ? $summary : substr($summary, 0, 0 - $min_rpos);
-      break;
+    // We avoid breaking text nodes within code blocks.
+    if (in_array('code', $parents)) {
+      // Return zero to avoid adding subsequent text nodes.
+      return 0;
     }
+    $sentences = preg_split($sentence_splitter, $body->textContent);
+    $text = '';
+    foreach ($sentences as $sentence) {
+      $sentence_length = drupal_strlen($sentence);
+      // Only add the sentence if it fits within the length limit.
+      if ($sentence_length > $size) {
+        break;
+      }
+      $text .= $sentence;
+      $size -= $sentence_length;
+    }
+    $summary->appendChild($doc->createTextNode($text));
+    // Return zero to avoid adding subsequent text nodes.
+    return 0;
   }
-
-  // If the htmlcorrector filter is present, apply it to the generated summary.
-  if (isset($filters['filter_htmlcorrector'])) {
-    $summary = _filter_htmlcorrector($summary);
+  if ($body->hasChildNodes()) {
+    $node = $summary->appendChild($doc->createElement($body->tagName));
+    $parents[] = $body->tagName;
+    foreach ($body->childNodes as $child) {
+      if ($size > 0) {
+        $size = _text_summarize($child, $size, $node, $doc, $parents);
+      }
+      else {
+        break;
+      }
+    }
   }
-
-  return $summary;
+  return $size;
 }
 
 /**
diff --git a/modules/field/modules/text/text.test b/modules/field/modules/text/text.test
index b42fed7e09894d352b3ecdd27431234e6ae77f72..78d252d4267baa74b59960a61b708fe6f4f6815c 100644
--- a/modules/field/modules/text/text.test
+++ b/modules/field/modules/text/text.test
@@ -258,7 +258,8 @@ class TextSummaryTestCase extends DrupalWebTestCase {
    */
   function testFirstSentenceQuestion() {
     $text = 'A question? A sentence. Another sentence.';
-    $expected = 'A question? A sentence.';
+    // The default format includes the auto-paragraph filter.
+    $expected = '<p>A question? A sentence.</p>';
     $this->callTextSummary($text, $expected, NULL, 30);
   }
 
@@ -270,11 +271,52 @@ class TextSummaryTestCase extends DrupalWebTestCase {
             'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ' . // 108
             'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. ' . // 103
             'Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'; // 110
-    $expected = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ' .
+    $expected = '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ' .
                 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ' .
-                'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.';
-    // First three sentences add up to: 336, so add one for space and then 3 to get half-way into next word.
-    $this->callTextSummary($text, $expected, NULL, 340);
+                'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>';
+    // Test that sentence splitting works when we replace the full stops with
+    // any other Sentence_Terminal character.
+    $sentence_terminals = array(
+      '!', // Exclamation mark.
+      '.', // Full stop.
+      '?', // Question mark.
+      '?', // Armenian full stop.
+      '?', // Arabic question mark.
+      '?', // Arabic full stop.
+      '?', // Syriac end of paragraph.
+      '?', // Syriac supralinear full stop.
+      '?', // Syriac sublinear full stop.
+      '?', // Devanagari danda.
+      '?', // Myanmar sign little section.
+      '?', // Myanmar sign section.
+      '?', // Ethiopic full stop.
+      '?', // Ethiopic question mark.
+      '?', // Ethiopic paragraph separator.
+      '?', // Canadian syllabics full stop.
+      '?', // Mongolian full stop.
+      '?', // Mongolian manchu full stop.
+      '?', // Double exclamation mark.
+      '?', // Interrobang.
+      '?', // Double question mark.
+      '?', // Question exclamation mark.
+      '?', // Exclamation question mark.
+      '?', // Ideographic full stop.
+      '?', // Small full stop.
+      '?', // Small exclamation mark.
+      '?', // Fullwidth exclamation mark.
+      '?', // Fullwidth full stop.
+      '?', // Fullwidth question mark.
+      '?', // Halfwidth ideographic full stop.
+    );
+    foreach ($sentence_terminals as $stop) {
+      // First three sentences add up to: 336, so add one for space and then 3 to get half-way into next word.
+      $this->callTextSummary(
+        str_replace('.', $stop, $text),
+        str_replace('.', $stop, $expected),
+        NULL,
+        340
+      );
+    }
   }
 
   /**
@@ -286,104 +328,79 @@ class TextSummaryTestCase extends DrupalWebTestCase {
 
     // The summaries we expect text_summary() to return when $size is the index
     // of each array item.
-    // Using no text format:
-    $expected = array(
-      "<p>\nHi\n</p>\n<p>\nfolks\n<br />\n!\n</p>",
-      "<",
-      "<p",
-      "<p>",
-      "<p>\n",
-      "<p>\nH",
-      "<p>\nHi",
-      "<p>\nHi\n",
-      "<p>\nHi\n<",
-      "<p>\nHi\n</",
-      "<p>\nHi\n</p",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>\n<p>\nfolks\n<br />\n!\n</p>",
-      "<p>\nHi\n</p>\n<p>\nfolks\n<br />\n!\n</p>",
-      "<p>\nHi\n</p>\n<p>\nfolks\n<br />\n!\n</p>",
-    );
 
-    // And using a text format WITH the line-break and htmlcorrector filters.
-    $expected_lb = array(
-      "<p>\nHi\n</p>\n<p>\nfolks\n<br />\n!\n</p>",
-      "",
-      "<p></p>",
-      "<p></p>",
-      "<p></p>",
-      "<p></p>",
-      "<p></p>",
-      "<p>\nHi</p>",
-      "<p>\nHi</p>",
-      "<p>\nHi</p>",
-      "<p>\nHi</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>",
-      "<p>\nHi\n</p>\n<p>\nfolks\n<br />\n!\n</p>",
-      "<p>\nHi\n</p>\n<p>\nfolks\n<br />\n!\n</p>",
-      "<p>\nHi\n</p>\n<p>\nfolks\n<br />\n!\n</p>",
+    // Using filtered_html format:
+    $expected = array (
+      0 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      1 => "<p></p>",
+      2 => "<p>Hi</p>",
+      3 => "<p>Hi</p>",
+      4 => "<p>Hi</p>\n<p></p>",
+      5 => "<p>Hi</p>\n<p></p>",
+      6 => "<p>Hi</p>\n<p></p>",
+      7 => "<p>Hi</p>\n<p></p>",
+      8 => "<p>Hi</p>\n<p>folks</p>",
+      9 => "<p>Hi</p>\n<p>folks</p>",
+      10 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      11 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      12 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      13 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      14 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      15 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      16 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      17 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      18 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      19 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      20 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      21 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      22 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      23 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      24 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      25 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      26 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      27 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      28 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      29 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      30 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      31 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      32 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      33 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      34 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      35 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      36 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
+      37 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
     );
 
     // Test text_summary() for different sizes.
     for ($i = 0; $i <= 37; $i++) {
-      $this->callTextSummary($text, $expected[$i],    NULL, $i);
-      $this->callTextSummary($text, $expected_lb[$i], 'plain_text', $i);
-      $this->callTextSummary($text, $expected_lb[$i], 'filtered_html', $i);
+      $this->callTextSummary($text, $expected[$i], 'filtered_html', $i);
     }
   }
 
   /**
+   * Test that we avoid breaking text in the middle of a CODE block.
+   */
+  function testCode() {
+    $text = 'This is an example code block:'
+      . '<code>$example = "Sentence one.  Sentence two. Sentence three.</code>';
+    $expected = '<p>This is an example code block:<code /></p>';
+    $this->callTextSummary($text, $expected, 'full_html', 65);
+  }
+
+  /**
    * Calls text_summary() and asserts that the expected teaser is returned.
    */
   function callTextSummary($text, $expected, $format = NULL, $size = NULL) {
     $summary = text_summary($text, $format, $size);
-    $this->assertIdentical($summary, $expected, t('Generated summary "@summary" matches expected "@expected".', array('@summary' => $summary, '@expected' => $expected)));
+    $replacements = array(
+      '@summary' => '"' . str_replace("\n", '\n', $summary) . '"',
+      '@expected' => '"' . str_replace("\n", '\n', $expected) . '"',
+    );
+    $comment = t(
+      'Generated summary @summary matches expected @expected.',
+      $replacements
+    );
+    $this->assertIdentical($summary, $expected, $comment);
   }
 
   /**
-- 
1.7.4.1


From 63e0e5dcf176542402b1d93e9647e694e73eb8d0 Mon Sep 17 00:00:00 2001
From: Bob Vincent <bobvin@pillars.net>
Date: Wed, 18 May 2011 18:53:56 -0400
Subject: [PATCH 2/2] Issue #823380, #221257 by AlexisWilke, NancyDru, greg.harvey, pillarsdotnet, AES2, vito_swat, scito, joachim, intoxination: Better read_more handling.

---
 modules/book/book.test                 |    7 +-
 modules/field/field.module             |   35 ++++++++
 modules/field/modules/text/text.module |   25 ++++--
 modules/field/modules/text/text.test   |    2 +-
 modules/node/node.module               |    4 +-
 modules/node/node.test                 |  150 ++++++++++++++++++++++++++++++--
 6 files changed, 205 insertions(+), 18 deletions(-)

diff --git a/modules/book/book.test b/modules/book/book.test
index cc61778b9d321f1e4f0b27d14752d4ab7e57dc99..aa1620e0cd5131b28284c5ea31629b11dee11e91 100644
--- a/modules/book/book.test
+++ b/modules/book/book.test
@@ -164,8 +164,9 @@ class BookTestCase extends DrupalWebTestCase {
 
     // Check printer friendly version.
     $this->drupalGet('book/export/html/' . $node->nid);
-    $this->assertText($node->title, t('Printer friendly title found.'));
-    $this->assertRaw(check_markup($node->body[LANGUAGE_NONE][0]['value'], $node->body[LANGUAGE_NONE][0]['format']), t('Printer friendly body found.'));
+    $this->assertText($node->title, t('Printer friendly title
+ found.'));
+    $this->assertRaw(trim(check_markup($node->body[LANGUAGE_NONE][0]['value'], $node->body[LANGUAGE_NONE][0]['format'])), t('Printer friendly body found.'));
 
     $number++;
   }
@@ -234,7 +235,7 @@ class BookTestCase extends DrupalWebTestCase {
     // Make sure each part of the book is there.
     foreach ($nodes as $node) {
       $this->assertText($node->title, t('Node title found in printer friendly version.'));
-      $this->assertRaw(check_markup($node->body[LANGUAGE_NONE][0]['value'], $node->body[LANGUAGE_NONE][0]['format']), t('Node body found in printer friendly version.'));
+      $this->assertRaw(trim(check_markup($node->body[LANGUAGE_NONE][0]['value'], $node->body[LANGUAGE_NONE][0]['format'])), t('Node body found in printer friendly version.'));
     }
 
     // Make sure we can't export an unsupported format.
diff --git a/modules/field/field.module b/modules/field/field.module
index 9e03c8d911dc3dc6ef42eee599752bbc789399ed..367d1046bcf617d7df1004eb651f444bb6a9a0b0 100644
--- a/modules/field/field.module
+++ b/modules/field/field.module
@@ -1010,6 +1010,41 @@ function field_extract_bundle($entity_type, $bundle) {
 }
 
 /**
+ * Check if any fields should trigger a readmore.
+ *
+ * This will parse through all renderable fields in the renederable array
+ * and check for #readmore property. If #readmore is TRUE, then we will
+ * return TRUE to signify that the caller should include a readmore link.
+ *
+ * @param $elements
+ *   An array of renderable fields
+ * @return
+ *   True if a single element has #readmore set to TRUE, otherwise FALSE.
+ */
+function field_has_read_more($elements) {
+  // Early-return if the user does not have access.
+  if (empty($elements) || (isset($elements['#access']) && !$elements['#access'])) {
+    return FALSE;
+  }
+
+  // Return if #read_more is set on this element.
+  if (!empty($elements['#read_more']) && $elements['#read_more']) {
+    return TRUE;
+  }
+
+  // Iterate through children.
+  foreach (element_children($elements) as $key) {
+    if (field_has_read_more($elements[$key])) {
+      // A child element has #read_more set to TRUE.
+      return TRUE;
+    }
+  }
+
+  // Neither this element, nor any child elements had #read_more set.
+  return FALSE;
+}
+
+/**
  * Theme preprocess function for theme_field() and field.tpl.php.
  *
  * @see theme_field()
diff --git a/modules/field/modules/text/text.module b/modules/field/modules/text/text.module
index 9829123927a53cebb5809c5f2bb3d98ec67266c6..5f673eda32c86e82189503bf9b431ef07de54862 100644
--- a/modules/field/modules/text/text.module
+++ b/modules/field/modules/text/text.module
@@ -261,24 +261,35 @@ function text_field_formatter_view($entity_type, $entity, $field, $instance, $la
     case 'text_default':
     case 'text_trimmed':
       foreach ($items as $delta => $item) {
-        $output = _text_sanitize($instance, $langcode, $item, 'value');
+        $output = trim(_text_sanitize($instance, $langcode, $item, 'value'));
+        $readmore = FALSE;
         if ($display['type'] == 'text_trimmed') {
-          $output = text_summary($output, $instance['settings']['text_processing'] ? $item['format'] : NULL, $display['settings']['trim_length']);
+          $trimmed_output = text_summary($output, $instance['settings']['text_processing'] ? $item['format'] : NULL, $display['settings']['trim_length']);
+          if ($trimmed_output != $output){
+            $readmore = TRUE;
+          }
+          $output = $trimmed_output;
         }
-        $element[$delta] = array('#markup' => $output);
+        $element[$delta] = array('#markup' => $output, '#read_more' => $readmore);
       }
       break;
 
     case 'text_summary_or_trimmed':
       foreach ($items as $delta => $item) {
+        $readmore = FALSE;
         if (!empty($item['summary'])) {
-          $output = _text_sanitize($instance, $langcode, $item, 'summary');
+          $readmore = TRUE;
+          $output = trim(_text_sanitize($instance, $langcode, $item, 'summary'));
         }
         else {
-          $output = _text_sanitize($instance, $langcode, $item, 'value');
-          $output = text_summary($output, $instance['settings']['text_processing'] ? $item['format'] : NULL, $display['settings']['trim_length']);
+          $output = trim(_text_sanitize($instance, $langcode, $item, 'value'));
+          $trimmed_output = text_summary($output, $instance['settings']['text_processing'] ? $item['format'] : NULL, $display['settings']['trim_length']);
+          if ($trimmed_output != $output){
+            $readmore = TRUE;
+          }
+          $output = $trimmed_output;
         }
-        $element[$delta] = array('#markup' => $output);
+        $element[$delta] = array('#markup' => $output, '#read_more' => $readmore);
       }
       break;
 
diff --git a/modules/field/modules/text/text.test b/modules/field/modules/text/text.test
index 78d252d4267baa74b59960a61b708fe6f4f6815c..11f0cc0b54135a75449aa4c47e6dfaf268924631 100644
--- a/modules/field/modules/text/text.test
+++ b/modules/field/modules/text/text.test
@@ -330,7 +330,7 @@ class TextSummaryTestCase extends DrupalWebTestCase {
     // of each array item.
 
     // Using filtered_html format:
-    $expected = array (
+    $expected = array(
       0 => "<p>Hi</p>\n<p>folks</p>\n<p>!</p>",
       1 => "<p></p>",
       2 => "<p>Hi</p>",
diff --git a/modules/node/node.module b/modules/node/node.module
index d19cf2985a54a2ce8b8ff26bee5f842be49d9391..d3ed56f86d2e2857c8cff057c1069052cb33d851 100644
--- a/modules/node/node.module
+++ b/modules/node/node.module
@@ -1369,7 +1369,9 @@ function node_build_content($node, $view_mode = 'full', $langcode = NULL) {
     '#pre_render' => array('drupal_pre_render_links'),
     '#attributes' => array('class' => array('links', 'inline')),
   );
-  if ($view_mode == 'teaser') {
+  // Only show read more in teaser view_mode and if a field has #read_more
+  // set to TRUE.
+  if ($view_mode == 'teaser' && field_has_read_more($node->content)) {
     $node_title_stripped = strip_tags($node->title);
     $links['node-readmore'] = array(
       'title' => t('Read more<span class="element-invisible"> about @title</span>', array('@title' => $node_title_stripped)),
diff --git a/modules/node/node.test b/modules/node/node.test
index 8a871c0c731fcf61fd5c52d0bb8e962c4e916f46..ce9e63cdc7e567b5cfd1f8e95c9b8d91411c6fc5 100644
--- a/modules/node/node.test
+++ b/modules/node/node.test
@@ -475,7 +475,7 @@ class NodeCreationTestCase extends DrupalWebTestCase {
   }
 
   function setUp() {
-    // Enable dummy module that implements hook_node_insert for exceptions.
+    // Enable dummy module that implements hook_node_insert() for exceptions.
     parent::setUp('node_test_exception');
 
     $web_user = $this->drupalCreateUser(array('create page content', 'edit own page content'));
@@ -770,7 +770,7 @@ class NodeRSSContentTestCase extends DrupalWebTestCase {
   }
 
   function setUp() {
-    // Enable dummy module that implements hook_node_view.
+    // Enable dummy module that implements hook_node_view().
     parent::setUp('node_test');
 
     // Use bypass node access permission here, because the test class uses
@@ -886,7 +886,7 @@ class NodeAccessUnitTest extends DrupalWebTestCase {
 }
 
 /**
- * Test case to verify hook_node_access_records functionality.
+ * Test case to verify hook_node_access_records() functionality.
  */
 class NodeAccessRecordsUnitTest extends DrupalWebTestCase {
   public static function getInfo() {
@@ -1447,7 +1447,7 @@ class NodeAdminTestCase extends DrupalWebTestCase {
    * Tests content overview with different user permissions.
    *
    * Taxonomy filters are tested separately.
-   * @see TaxonomyNodeFilterTestCase
+   * @see TaxonomyNodeFilterTestCase()
    */
   function testContentAdminPages() {
     $this->drupalLogin($this->admin_user);
@@ -1578,7 +1578,7 @@ class NodeTitleTestCase extends DrupalWebTestCase {
     // Test <title> tag.
     $this->drupalGet("node/$node->nid");
     $xpath = '//title';
-    $this->assertEqual(current($this->xpath($xpath)), $node->title .' | Drupal', 'Page title is equal to node title.', 'Node');
+    $this->assertEqual(current($this->xpath($xpath)), $node->title . ' | Drupal', 'Page title is equal to node title.', 'Node');
 
     // Test breadcrumb in comment preview.
     $this->drupalGet("comment/reply/$node->nid");
@@ -1603,7 +1603,7 @@ class NodeFeedTestCase extends DrupalWebTestCase {
       'name' => 'Node feed',
       'description' => 'Ensures that node_feed() functions correctly.',
       'group' => 'Node',
-   );
+    );
   }
 
   /**
@@ -2146,3 +2146,141 @@ class NodeTokenReplaceTestCase extends DrupalWebTestCase {
     }
   }
 }
+
+/**
+ * Test the "Read more" link for teasers.
+ */
+class NodeTeaserReadMoreTest extends DrupalWebTestCase {
+
+  public static function getInfo() {
+    return array(
+      'name' => 'Teaser read more',
+      'description' => 'Test the "Read more" link for teasers.',
+      'group' => 'Node',
+    );
+  }
+
+  function setUp() {
+    parent::setUp();
+
+    $web_user = $this->drupalCreateUser(array(
+      'create article content',
+      'create page content',
+      'administer filters',
+      filter_permission_name(filter_format_load('filtered_html')),
+      filter_permission_name(filter_format_load('full_html')),
+      'administer content types',
+      'access administration pages',
+      'bypass node access',
+      'administer taxonomy',
+      'administer nodes',
+    ));
+    $this->drupalLogin($web_user);
+  }
+
+  /**
+   * Create a node where teaser and full view are equal. The "Read more" link
+   * must not appear.
+   */
+  function testTeaserIsComplete() {
+    $node1 = $this->drupalCreateNode(array(
+      'type' => 'article',
+      'promote' => 1,
+      'body' => array(
+        LANGUAGE_NONE => array(
+          '0' => array(
+            'value' => 'body_' . $this->randomName(32),
+          ),
+        ),
+      ),
+    ) );
+
+    $this->drupalGet('node');
+    $this->assertText($node1->title, t('Node title appears on the default listing.'));
+    $this->assertText($node1->body['und'][0]['value'], t('Node body appears on the default listing.'));
+    // Confirm that promoted node appears without the read more link in the
+    // default node listing.
+    $this->assertNoText('Read more', t('"Read more" does not appear in the default listing.'));
+  }
+
+  /**
+   * Create a node with a tag where teaser and full view are equal. The
+   * "Read more" link must not appear.
+   */
+  function testTeaserIsCompleteWithTag() {
+    // Post an article with a taxonomy term.
+    $langcode = LANGUAGE_NONE;
+    $tag = 'tag_' . $this->randomName(8);
+    $edit = array();
+    $edit['title'] = 'title_' . $this->randomName(8);
+    $edit["body[$langcode][0][value]"] = 'body_' . $this->randomName(32);
+    $edit["field_tags[$langcode]"] = $tag;
+    $edit['promote'] = 1;
+    $this->drupalPost('node/add/article', $edit, t('Save'));
+    $node1 = $this->drupalGetNodeByTitle($edit['title']);
+
+    $this->drupalGet('node');
+    $this->assertText($node1->title, t('Node title appears on the default listing.'));
+    $this->assertText($node1->body['und'][0]['value'], t('Node body appears on the default listing.'));
+    $this->assertText($tag, t('Tag appears on the default listing.'));
+    // Confirm that promoted node appears without the read more link in the
+    // default node listing.
+    $this->assertNoText('Read more', t('"Read more" does not appear in the default listing.'));
+  }
+
+  /**
+   * Create a node with a summary. The "Read more" link must be set.
+   */
+  function testTeaserSummary() {
+    $body = 'body_' . $this->randomName(32);
+    $summary = 'summary_' . $this->randomName(32);
+    $node1 = $this->drupalCreateNode(array(
+      'type' => 'article',
+      'promote' => 1,
+      'body' => array(
+        LANGUAGE_NONE => array(
+          '0' => array(
+            'value' => $body,
+            'summary' => $summary,
+          ),
+        ),
+      ),
+    ) );
+
+    $this->drupalGet('node');
+    $this->assertText($node1->title, t('Node title appears on the default listing.'));
+    $this->assertText($summary, t('The summary text appears in the default listing.'));
+    $this->assertNoText($body, t('The body text does not appear in the default listing.'));
+    // Confirm that promoted node appears with the read more link in the
+    // default node listing.
+    $this->assertText('Read more', t('"Read more" appears in the default listing.'));
+  }
+
+  /**
+   * Create a node with trimmed body. The "Read more" link must be set.
+   */
+  function testTeaserTrimmed() {
+    $node1 = $this->drupalCreateNode(array(
+      'type' => 'article',
+      'promote' => 1,
+      'body' => array(
+        LANGUAGE_NONE => array(
+          '0' => array(
+            'value' => 'teaser<!--break-->body',
+            // Set text format to Full HTML due to bug http://drupal.org/node/881006
+            'format' => 'full_html',
+          ),
+        ),
+      ),
+    ) );
+
+    $this->drupalGet('node');
+    $this->assertText($node1->title, t('Node title appears on the default listing.'));
+    $this->assertText('teaser', t('The teaser text appears in the default listing.'));
+    $this->assertNoText('body', t('The body text does not appear in the default listing:<hr />' . $this->drupalGetContent()));
+    // Confirm that promoted node appears with the read more link in the
+    // default node listing.
+    $this->assertText('Read more', t('"Read more" appears in the default listing.'));
+  }
+
+}
\ No newline at end of file
-- 
1.7.4.1

