<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[BuddyPress][4989] trunk: Modifies bp_create_excerpt() to take account of HTML tag length when truncating long texts.</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg > ul, #logmsg > ol { margin-left: 0; margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://buddypress.trac.wordpress.org/changeset/4989">4989</a></dd>
<dt>Author</dt> <dd>boonebgorges</dd>
<dt>Date</dt> <dd>2011-08-16 11:33:09 +0000 (Tue, 16 Aug 2011)</dd>
</dl>

<h3>Log Message</h3>
<pre>Modifies bp_create_excerpt() to take account of HTML tag length when truncating long texts. Thanks to CakePHP for the function. Refactors BP use of bp_create_excerpt(), where necessary, to account for new function argument structure. Reworks bp_activity_truncate_entry() so that already-truncated activity items (like blog posts) do not get a Read More link when they contain HTML. Introduces fallback functions for some multibyte string functions, to make bp_create_excerpt() work properly. Thanks to MediaWiki for these fallbacks. Fixes <a href="http://buddypress.trac.wordpress.org/ticket/3452">#3452</a>. Props DJPaul for all the help with this patch.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#trunkbpactivitybpactivityfiltersphp">trunk/bp-activity/bp-activity-filters.php</a></li>
<li><a href="#trunkbpactivitybpactivitytemplatephp">trunk/bp-activity/bp-activity-template.php</a></li>
<li><a href="#trunkbpcorebpcoretemplatephp">trunk/bp-core/bp-core-template.php</a></li>
<li><a href="#trunkbpcorebpcorewpabstractionphp">trunk/bp-core/bp-core-wpabstraction.php</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="trunkbpactivitybpactivityfiltersphp"></a>
<div class="modfile"><h4>Modified: trunk/bp-activity/bp-activity-filters.php (4988 => 4989)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/bp-activity/bp-activity-filters.php        2011-08-15 20:02:37 UTC (rev 4988)
+++ trunk/bp-activity/bp-activity-filters.php        2011-08-16 11:33:09 UTC (rev 4989)
</span><span class="lines">@@ -188,13 +188,19 @@
</span><span class="cx"> 
</span><span class="cx">         $append_text    = apply_filters( 'bp_activity_excerpt_append_text', __( '[Read more]', 'buddypress' ) );
</span><span class="cx">         $excerpt_length = apply_filters( 'bp_activity_excerpt_length', 358 );
</span><del>-        $excerpt        = $text;
</del><span class="cx"> 
</span><del>-        $id = !empty( $activities_template-&gt;activity-&gt;current_comment-&gt;id ) ? 'acomment-read-more-' . $activities_template-&gt;activity-&gt;current_comment-&gt;id : 'activity-read-more-' . bp_get_activity_id();
</del><ins>+        // Run the text through the excerpt function. If it's too short, the original text will be
+        // returned.
+        $excerpt        = bp_create_excerpt( $text, $excerpt_length, array( 'ending' =&gt; __( '&amp;hellip;', 'buddypress' ) ) );
</ins><span class="cx"> 
</span><del>-        if ( strlen( $excerpt ) &gt; $excerpt_length )
-                $excerpt = sprintf( '%1$s&lt;span class=&quot;activity-read-more&quot; id=&quot;%2$s&quot;&gt;&lt;a href=&quot;%3$s&quot; rel=&quot;nofollow&quot;&gt;%4$s&lt;/a&gt;&lt;/span&gt;', bp_create_excerpt( $excerpt, $excerpt_length, true, '&amp;hellip;' ), $id, bp_get_activity_thread_permalink(), $append_text );
</del><ins>+        // If the text returned by bp_create_excerpt() is different from the original text (ie it's
+        // been truncated), add the &quot;Read More&quot; link.
+        if ( $excerpt != $text ) {
+                $id = !empty( $activities_template-&gt;activity-&gt;current_comment-&gt;id ) ? 'acomment-read-more-' . $activities_template-&gt;activity-&gt;current_comment-&gt;id : 'activity-read-more-' . bp_get_activity_id();
</ins><span class="cx"> 
</span><ins>+                $excerpt = sprintf( '%1$s&lt;span class=&quot;activity-read-more&quot; id=&quot;%2$s&quot;&gt;&lt;a href=&quot;%3$s&quot; rel=&quot;nofollow&quot;&gt;%4$s&lt;/a&gt;&lt;/span&gt;', $excerpt, $id, bp_get_activity_thread_permalink(), $append_text );
+        }
+
</ins><span class="cx">         return apply_filters( 'bp_activity_truncate_entry', $excerpt, $text, $append_text );
</span><span class="cx"> }
</span><span class="cx"> add_filter( 'bp_get_activity_content_body', 'bp_activity_truncate_entry', 5 );
</span></span></pre></div>
<a id="trunkbpactivitybpactivitytemplatephp"></a>
<div class="modfile"><h4>Modified: trunk/bp-activity/bp-activity-template.php (4988 => 4989)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/bp-activity/bp-activity-template.php        2011-08-15 20:02:37 UTC (rev 4988)
+++ trunk/bp-activity/bp-activity-template.php        2011-08-16 11:33:09 UTC (rev 4989)
</span><span class="lines">@@ -1536,7 +1536,7 @@
</span><span class="cx">                         $title = substr( $title, 0, -1 );
</span><span class="cx"> 
</span><span class="cx">                 if ( 'activity_update' == $activities_template-&gt;activity-&gt;type )
</span><del>-                        $title .= ': ' . strip_tags( ent2ncr( trim( convert_chars( bp_create_excerpt( $activities_template-&gt;activity-&gt;content, 70, true, &quot; [&amp;#133;]&quot; ) ) ) ) );
</del><ins>+                        $title .= ': ' . strip_tags( ent2ncr( trim( convert_chars( bp_create_excerpt( $activities_template-&gt;activity-&gt;content, 70, array( 'ending' =&gt; &quot; [&amp;#133;]&quot; ) ) ) ) ) );
</ins><span class="cx"> 
</span><span class="cx">                 return apply_filters( 'bp_get_activity_feed_item_title', $title );
</span><span class="cx">         }
</span></span></pre></div>
<a id="trunkbpcorebpcoretemplatephp"></a>
<div class="modfile"><h4>Modified: trunk/bp-core/bp-core-template.php (4988 => 4989)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/bp-core/bp-core-template.php        2011-08-15 20:02:37 UTC (rev 4988)
+++ trunk/bp-core/bp-core-template.php        2011-08-16 11:33:09 UTC (rev 4989)
</span><span class="lines">@@ -346,36 +346,142 @@
</span><span class="cx">                 return apply_filters( 'bp_get_button', $button-&gt;contents, $args, $button );
</span><span class="cx">         }
</span><span class="cx"> 
</span><ins>+
</ins><span class="cx"> /**
</span><del>- * bp_create_excerpt()
</del><ins>+ * Truncates text.
</ins><span class="cx">  *
</span><del>- * Fakes an excerpt on any content. Will not truncate words.
</del><ins>+ * Cuts a string to the length of $length and replaces the last characters
+ * with the ending if the text is longer than length.
</ins><span class="cx">  *
</span><del>- * @package BuddyPress Core
- * @param $text str The text to create the excerpt from
- * @param $excerpt_length Minimum excerpt length, in characters
- * @param $filter_shortcodes When true, registered shortcodes (in square brackets) will be stripped
- * @param $append_text Be sure to include a leading space
- * @return str The excerpt text
</del><ins>+ * This function is borrowed from CakePHP v2.0, under the MIT license. See
+ * http://book.cakephp.org/view/1469/Text#truncate-1625
+ *
+ * ### Options:
+ *
+ * - `ending` Will be used as Ending and appended to the trimmed string
+ * - `exact` If false, $text will not be cut mid-word
+ * - `html` If true, HTML tags would be handled correctly
+ * - `filter_shortcodes` If true, shortcodes will be stripped before truncating
+ *
+ * @package BuddyPress
+ *
+ * @param string  $text String to truncate.
+ * @param integer $length Length of returned string, including ellipsis.
+ * @param array $options An array of html attributes and options.
+ * @return string Trimmed string.
</ins><span class="cx">  */
</span><del>-function bp_create_excerpt( $text, $excerpt_length = 225, $filter_shortcodes = true, $append_text = ' [&amp;hellip;]' ) { // Fakes an excerpt if needed
</del><ins>+function bp_create_excerpt( $text, $length = 225, $options = array() ) {
+        // Backward compatibility. The third argument used to be a boolean $filter_shortcodes
+        $filter_shortcodes_default = is_bool( $options ) ? $options : true;
+
+        $defaults = array(
+                'ending'            =&gt; __( ' [&amp;hellip;]', 'buddypress' ),
+                'exact'             =&gt; false,
+                'html'              =&gt; true,
+                'filter_shortcodes' =&gt; $filter_shortcodes_default
+        );
+        $r = wp_parse_args( $options, $defaults );
+        extract( $r );
+
+        // Save the original text, to be passed along to the filter
</ins><span class="cx">         $original_text = $text;
</span><del>-        $text = str_replace( ']]&gt;', ']]&amp;gt;', $text );
</del><span class="cx"> 
</span><del>-        $excerpt_length = apply_filters( 'bp_excerpt_length', $excerpt_length );
-        $append_text = apply_filters( 'bp_excerpt_append_text', $append_text );
</del><ins>+        // Allow plugins to modify these values globally
+        $length = apply_filters( 'bp_excerpt_length', $length );
+        $ending = apply_filters( 'bp_excerpt_append_text', $ending );
</ins><span class="cx"> 
</span><ins>+        // Remove shortcodes if necessary
</ins><span class="cx">         if ( $filter_shortcodes )
</span><span class="cx">                 $text = strip_shortcodes( $text );
</span><span class="cx"> 
</span><del>-        preg_match( &quot;%\s*((?:&lt;[^&gt;]+&gt;)+\S*)\s*|\s+%s&quot;, $text, $matches, PREG_OFFSET_CAPTURE, $excerpt_length );
</del><ins>+        // When $html is true, the excerpt should be created without including HTML tags in the
+        // excerpt length
+        if ( $html ) {
+                // The text is short enough. No need to truncate
+                if ( mb_strlen( preg_replace( '/&lt;.*?&gt;/', '', $text ) ) &lt;= $length ) {
+                        return $text;
+                }
</ins><span class="cx"> 
</span><del>-        if ( !empty( $matches ) ) {
-                $pos = array_pop( array_pop( $matches ) );
-                $text = substr( $text, 0, $pos ) . $append_text;
</del><ins>+                $totalLength = mb_strlen( strip_tags( $ending ) );
+                $openTags    = array();
+                $truncate    = '';
+
+                // Find all the tags and put them in a stack for later use
+                preg_match_all( '/(&lt;\/?([\w+]+)[^&gt;]*&gt;)?([^&lt;&gt;]*)/', $text, $tags, PREG_SET_ORDER );
+                foreach ( $tags as $tag ) {
+                        // Process tags that need to be closed
+                        if ( !preg_match( '/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s',  $tag[2] ) ) {
+                                if ( preg_match( '/&lt;[\w]+[^&gt;]*&gt;/s', $tag[0] ) ) {
+                                        array_unshift( $openTags, $tag[2] );
+                                } else if ( preg_match('/&lt;\/([\w]+)[^&gt;]*&gt;/s', $tag[0], $closeTag ) ) {
+                                        $pos = array_search( $closeTag[1], $openTags );
+                                        if ( $pos !== false ) {
+                                                array_splice( $openTags, $pos, 1 );
+                                        }
+                                }
+                        }
+                        $truncate .= $tag[1];
+
+                        $contentLength = mb_strlen( preg_replace( '/&amp;[0-9a-z]{2,8};|&amp;#[0-9]{1,7};|&amp;#x[0-9a-f]{1,6};/i', ' ', $tag[3] ) );
+                        if ( $contentLength + $totalLength &gt; $length ) {
+                                $left = $length - $totalLength;
+                                $entitiesLength = 0;
+                                if ( preg_match_all( '/&amp;[0-9a-z]{2,8};|&amp;#[0-9]{1,7};|&amp;#x[0-9a-f]{1,6};/i', $tag[3], $entities, PREG_OFFSET_CAPTURE ) ) {
+                                        foreach ( $entities[0] as $entity ) {
+                                                if ( $entity[1] + 1 - $entitiesLength &lt;= $left ) {
+                                                        $left--;
+                                                        $entitiesLength += mb_strlen( $entity[0] );
+                                                } else {
+                                                        break;
+                                                }
+                                        }
+                                }
+
+                                $truncate .= mb_substr( $tag[3], 0 , $left + $entitiesLength );
+                                break;
+                        } else {
+                                $truncate .= $tag[3];
+                                $totalLength += $contentLength;
+                        }
+                        if ( $totalLength &gt;= $length ) {
+                                break;
+                        }
+                }
+        } else {
+                if ( mb_strlen( $text ) &lt;= $length ) {
+                        return $text;
+                } else {
+                        $truncate = mb_substr( $text, 0, $length - mb_strlen( $ending ) );
+                }
</ins><span class="cx">         }
</span><span class="cx"> 
</span><del>-        return apply_filters( 'bp_create_excerpt', $text, $original_text, $excerpt_length, $filter_shortcodes, $append_text );
</del><ins>+        // If $exact is false, we can't break on words
+        if ( !$exact ) {
+                $spacepos = mb_strrpos( $truncate, ' ' );
+                if ( isset( $spacepos ) ) {
+                        if ( $html ) {
+                                $bits = mb_substr( $truncate, $spacepos );
+                                preg_match_all( '/&lt;\/([a-z]+)&gt;/', $bits, $droppedTags, PREG_SET_ORDER );
+                                if ( !empty( $droppedTags ) ) {
+                                        foreach ( $droppedTags as $closingTag ) {
+                                                if ( !in_array( $closingTag[1], $openTags ) ) {
+                                                        array_unshift( $openTags, $closingTag[1] );
+                                                }
+                                        }
+                                }
+                        }
+                        $truncate = mb_substr( $truncate, 0, $spacepos );
+                }
+        }
+        $truncate .= $ending;
+
+        if ( $html ) {
+                foreach ( $openTags as $tag ) {
+                        $truncate .= '&lt;/' . $tag . '&gt;';
+                }
+        }
+
+        return apply_filters( 'bp_create_excerpt', $truncate, $original_text, $length, $options );
</ins><span class="cx"> }
</span><span class="cx"> add_filter( 'bp_create_excerpt', 'wp_trim_excerpt' );
</span><span class="cx"> add_filter( 'bp_create_excerpt', 'stripslashes_deep' );
</span></span></pre></div>
<a id="trunkbpcorebpcorewpabstractionphp"></a>
<div class="modfile"><h4>Modified: trunk/bp-core/bp-core-wpabstraction.php (4988 => 4989)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/bp-core/bp-core-wpabstraction.php        2011-08-15 20:02:37 UTC (rev 4988)
+++ trunk/bp-core/bp-core-wpabstraction.php        2011-08-16 11:33:09 UTC (rev 4989)
</span><span class="lines">@@ -26,7 +26,7 @@
</span><span class="cx">                         return get_option( $option_name, $default );
</span><span class="cx">                 }
</span><span class="cx">         }
</span><del>-        
</del><ins>+
</ins><span class="cx">         if ( !function_exists( 'update_blog_option' ) ) {
</span><span class="cx">                 function update_blog_option( $blog_id, $option_name, $value ) {
</span><span class="cx">                         return update_option( $option_name, $value );
</span><span class="lines">@@ -73,4 +73,84 @@
</span><span class="cx">         else
</span><span class="cx">                 return &quot;{$prefix}spam = 0 AND {$prefix}deleted = 0 AND {$prefix}user_status = 0&quot;;
</span><span class="cx"> }
</span><ins>+
+/**
+ * Multibyte encoding fallback functions
+ *
+ * The PHP multibyte encoding extension is not enabled by default. In cases where it is not enabled,
+ * these functions provide a fallback.
+ *
+ * Borrowed from MediaWiki, under the GPLv2. Thanks!
+ */
+if ( !function_exists( 'mb_strlen' ) ) {
+        /**
+         * Fallback implementation of mb_strlen, hardcoded to UTF-8.
+         * @param string $str
+         * @param string $enc optional encoding; ignored
+         * @return int
+         */
+        function mb_strlen( $str, $enc = '' ) {
+                $counts = count_chars( $str );
+                $total = 0;
+
+                // Count ASCII bytes
+                for( $i = 0; $i &lt; 0x80; $i++ ) {
+                        $total += $counts[$i];
+                }
+
+                // Count multibyte sequence heads
+                for( $i = 0xc0; $i &lt; 0xff; $i++ ) {
+                        $total += $counts[$i];
+                }
+                return $total;
+        }
+}
+
+if ( !function_exists( 'mb_strpos' ) ) {
+        /**
+         * Fallback implementation of mb_strpos, hardcoded to UTF-8.
+         * @param $haystack String
+         * @param $needle String
+         * @param $offset String: optional start position
+         * @param $encoding String: optional encoding; ignored
+         * @return int
+         */
+        function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
+                $needle = preg_quote( $needle, '/' );
+
+                $ar = array();
+                preg_match( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE, $offset );
+
+                if( isset( $ar[0][1] ) ) {
+                        return $ar[0][1];
+                } else {
+                        return false;
+                }
+        }
+}
+
+if ( !function_exists( 'mb_strrpos' ) ) {
+        /**
+         * Fallback implementation of mb_strrpos, hardcoded to UTF-8.
+         * @param $haystack String
+         * @param $needle String
+         * @param $offset String: optional start position
+         * @param $encoding String: optional encoding; ignored
+         * @return int
+         */
+        function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
+                $needle = preg_quote( $needle, '/' );
+
+                $ar = array();
+                preg_match_all( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE, $offset );
+
+                if( isset( $ar[0] ) &amp;&amp; count( $ar[0] ) &gt; 0 &amp;&amp;
+                        isset( $ar[0][count( $ar[0] ) - 1][1] ) ) {
+                        return $ar[0][count( $ar[0] ) - 1][1];
+                } else {
+                        return false;
+                }
+        }
+}
+
</ins><span class="cx"> ?&gt;
</span><span class="cx">\ No newline at end of file
</span></span></pre>
</div>
</div>

</body>
</html>