3 /*************************************************************************
5 * class.html2text.inc *
7 *************************************************************************
9 * Converts HTML to formatted plain text *
11 * Copyright (c) 2005-2007 Jon Abernathy <jon@chuggnutt.com> *
12 * All rights reserved. *
14 * This script is free software; you can redistribute it and/or modify *
15 * it under the terms of the GNU General Public License as published by *
16 * the Free Software Foundation; either version 2 of the License, or *
17 * (at your option) any later version. *
19 * The GNU General Public License can be found at *
20 * http://www.gnu.org/copyleft/gpl.html. *
22 * This script is distributed in the hope that it will be useful, *
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
25 * GNU General Public License for more details. *
27 * Author(s): Jon Abernathy <jon@chuggnutt.com> *
29 * Last modified: 08/08/07 *
31 *************************************************************************/
33 if (!defined('RCMAIL_CHARSET')) {
34 define('RCMAIL_CHARSET', 'UTF-8');
38 * Takes HTML and converts it to formatted, plain text.
40 * Thanks to Alexander Krug (http://www.krugar.de/) to pointing out and
41 * correcting an error in the regexp search array. Fixed 7/30/03.
43 * Updated set_html() function's file reading mechanism, 9/25/03.
45 * Thanks to Joss Sanglier (http://www.dancingbear.co.uk/) for adding
46 * several more HTML entity codes to the $search and $replace arrays.
49 * Thanks to Darius Kasperavicius (http://www.dar.dar.lt/) for
50 * suggesting the addition of $allowed_tags and its supporting function
51 * (which I slightly modified). Updated 3/12/04.
53 * Thanks to Justin Dearing for pointing out that a replacement for the
54 * <TH> tag was missing, and suggesting an appropriate fix.
57 * Thanks to Mathieu Collas (http://www.myefarm.com/) for finding a
58 * display/formatting bug in the _build_link_list() function: email
59 * readers would show the left bracket and number ("[1") as part of the
60 * rendered email address.
63 * Thanks to Wojciech Bajon (http://histeria.pl/) for submitting code
64 * to handle relative links, which I hadn't considered. I modified his
65 * code a bit to handle normal HTTP links and MAILTO links. Also for
66 * suggesting three additional HTML entity codes to search for.
69 * Thanks to Jacob Chandler for pointing out another link condition
70 * for the _build_link_list() function: "https".
73 * Thanks to Marc Bertrand (http://www.dresdensky.com/) for
74 * suggesting a revision to the word wrapping functionality; if you
75 * specify a $width of 0 or less, word wrapping will be ignored.
78 * *** Big housecleaning updates below:
80 * Thanks to Colin Brown (http://www.sparkdriver.co.uk/) for
81 * suggesting the fix to handle </li> and blank lines (whitespace).
82 * Christian Basedau (http://www.movetheweb.de/) also suggested the
85 * Special thanks to Marcus Bointon (http://www.synchromedia.co.uk/),
86 * Christian Basedau, Norbert Laposa (http://ln5.co.uk/),
87 * Bas van de Weijer, and Marijn van Butselaar
88 * for pointing out my glaring error in the <th> handling. Marcus also
89 * supplied a host of fixes.
91 * Thanks to Jeffrey Silverman (http://www.newtnotes.com/) for pointing
92 * out that extra spaces should be compressed--a problem addressed with
93 * Marcus Bointon's fixes but that I had not yet incorporated.
95 * Thanks to Daniel Schledermann (http://www.typoconsult.dk/) for
96 * suggesting a valuable fix with <a> tag handling.
98 * Thanks to Wojciech Bajon (again!) for suggesting fixes and additions,
99 * including the <a> tag handling that Daniel Schledermann pointed
100 * out but that I had not yet incorporated. I haven't (yet)
101 * incorporated all of Wojciech's changes, though I may at some
104 * *** End of the housecleaning updates. Updated 08/08/07.
106 * @author Jon Abernathy <jon@chuggnutt.com>
114 * Contains the HTML content to convert.
122 * Contains the converted, formatted text.
130 * Maximum width of the formatted text, in columns.
132 * Set this value to 0 (or less) to ignore word wrapping
133 * and not constrain text to a fixed-width column.
135 * @var integer $width
141 * List of preg* regular expression patterns to search for,
142 * used in conjunction with $replace.
149 "/\r/", // Non-legal carriage return
150 "/[\n\t]+/", // Newlines and tabs
151 '/<script[^>]*>.*?<\/script>/i', // <script>s -- which strip_tags supposedly has problems with
152 '/<style[^>]*>.*?<\/style>/i', // <style>s -- which strip_tags supposedly has problems with
153 '/<p[^>]*>/i', // <P>
154 '/<br[^>]*>/i', // <br>
155 '/<i[^>]*>(.*?)<\/i>/i', // <i>
156 '/<em[^>]*>(.*?)<\/em>/i', // <em>
157 '/(<ul[^>]*>|<\/ul>)/i', // <ul> and </ul>
158 '/(<ol[^>]*>|<\/ol>)/i', // <ol> and </ol>
159 '/<li[^>]*>(.*?)<\/li>/i', // <li> and </li>
160 '/<li[^>]*>/i', // <li>
161 '/<hr[^>]*>/i', // <hr>
162 '/<div[^>]*>/i', // <div>
163 '/(<table[^>]*>|<\/table>)/i', // <table> and </table>
164 '/(<tr[^>]*>|<\/tr>)/i', // <tr> and </tr>
165 '/<td[^>]*>(.*?)<\/td>/i', // <td> and </td>
169 * List of pattern replacements corresponding to patterns searched.
171 * @var array $replace
175 var $replace = array(
176 '', // Non-legal carriage return
177 ' ', // Newlines and tabs
178 '', // <script>s -- which strip_tags supposedly has problems with
179 '', // <style>s -- which strip_tags supposedly has problems with
184 "\n\n", // <ul> and </ul>
185 "\n\n", // <ol> and </ol>
186 "\t* \\1\n", // <li> and </li>
188 "\n-------------------------\n", // <hr>
190 "\n\n", // <table> and </table>
191 "\n", // <tr> and </tr>
192 "\t\t\\1\n", // <td> and </td>
196 * List of preg* regular expression patterns to search for,
197 * used in conjunction with $ent_replace.
199 * @var array $ent_search
203 var $ent_search = array(
204 '/&(nbsp|#160);/i', // Non-breaking space
205 '/&(quot|rdquo|ldquo|#8220|#8221|#147|#148);/i',
207 '/&(apos|rsquo|lsquo|#8216|#8217);/i', // Single quotes
208 '/>/i', // Greater-than
209 '/</i', // Less-than
210 '/&(copy|#169);/i', // Copyright
211 '/&(trade|#8482|#153);/i', // Trademark
212 '/&(reg|#174);/i', // Registered
213 '/&(mdash|#151|#8212);/i', // mdash
214 '/&(ndash|minus|#8211|#8722);/i', // ndash
215 '/&(bull|#149|#8226);/i', // Bullet
216 '/&(pound|#163);/i', // Pound sign
217 '/&(euro|#8364);/i', // Euro sign
218 '/&(amp|#38);/i', // Ampersand: see _converter()
219 '/[ ]{2,}/', // Runs of spaces, post-handling
223 * List of pattern replacements corresponding to patterns searched.
225 * @var array $ent_replace
229 var $ent_replace = array(
230 ' ', // Non-breaking space
231 '"', // Double quotes
232 "'", // Single quotes
242 'EUR', // Euro sign. € ?
243 '|+|amp|+|', // Ampersand: see _converter()
244 ' ', // Runs of spaces, post-handling
248 * List of preg* regular expression patterns to search for
249 * and replace using callback function.
251 * @var array $callback_search
254 var $callback_search = array(
255 '/<(a) [^>]*href=("|\')([^"\']+)\2[^>]*>(.*?)<\/a>/i',
257 '/<(h)[123456][^>]*>(.*?)<\/h[123456]>/i', // H1 - H3
258 '/<(b)[^>]*>(.*?)<\/b>/i', // <b>
259 '/<(strong)[^>]*>(.*?)<\/strong>/i', // <strong>
260 '/<(th)[^>]*>(.*?)<\/th>/i', // <th> and </th>
261 '/<(img)[^>]*alt=\"([^>"]+)\"[^>]*>/i', // <img> with alt
265 * List of preg* regular expression patterns to search for in PRE body,
266 * used in conjunction with $pre_replace.
268 * @var array $pre_search
272 var $pre_search = array(
281 * List of pattern replacements corresponding to patterns searched for PRE body.
283 * @var array $pre_replace
287 var $pre_replace = array(
289 ' ',
296 * Contains a list of HTML tags to allow in the resulting text.
298 * @var string $allowed_tags
300 * @see set_allowed_tags()
302 var $allowed_tags = '';
305 * Contains the base URL that relative links should resolve to.
313 * Indicates whether content in the $html variable has been converted yet.
315 * @var boolean $_converted
319 var $_converted = false;
322 * Contains URL addresses from links to be rendered in plain text.
324 * @var array $_link_list
326 * @see _build_link_list()
328 var $_link_list = array();
331 * Boolean flag, true if a table of link URLs should be listed after the text.
333 * @var boolean $_do_links
337 var $_do_links = true;
342 * If the HTML source string (or file) is supplied, the class
343 * will instantiate with that source propagated, all that has
344 * to be done it to call get_text().
346 * @param string $source HTML content
347 * @param boolean $from_file Indicates $source is a file to pull content from
348 * @param boolean $do_links Indicate whether a table of link URLs is desired
349 * @param integer $width Maximum width of the formatted text, 0 for no limit
353 function html2text( $source = '', $from_file = false, $do_links = true, $width = 75 )
355 if ( $source !== '' ) {
356 $this->set_html($source, $from_file);
359 $this->set_base_url();
360 $this->_do_links
= $do_links;
361 $this->width
= $width;
365 * Loads source HTML into memory, either from $source string or a file.
367 * @param string $source HTML content
368 * @param boolean $from_file Indicates $source is a file to pull content from
372 function set_html( $source, $from_file = false )
374 if ( $from_file && file_exists($source) ) {
375 $this->html
= file_get_contents($source);
378 $this->html
= $source;
380 $this->_converted
= false;
384 * Returns the text, converted from HTML.
391 if ( !$this->_converted
) {
399 * Prints the text, converted from HTML.
404 function print_text()
406 print $this->get_text();
410 * Alias to print_text(), operates identically.
418 print $this->get_text();
422 * Sets the allowed HTML tags to pass through to the resulting text.
424 * Tags should be in the form "<p>", with no corresponding closing tag.
429 function set_allowed_tags( $allowed_tags = '' )
431 if ( !empty($allowed_tags) ) {
432 $this->allowed_tags
= $allowed_tags;
437 * Sets a base URL to handle relative links.
442 function set_base_url( $url = '' )
445 if ( !empty($_SERVER['HTTP_HOST']) ) {
446 $this->url
= 'http://' . $_SERVER['HTTP_HOST'];
451 // Strip any trailing slashes for consistency (relative
452 // URLs may already start with a slash like "/file.html")
453 if ( substr($url, -1) == '/' ) {
454 $url = substr($url, 0, -1);
461 * Workhorse function that does actual conversion (calls _converter() method).
468 // Variables used for building the link list
469 $this->_link_list
= array();
471 $text = trim($this->html
);
473 // Convert HTML to TXT
474 $this->_converter($text);
477 if (!empty($this->_link_list
)) {
478 $text .= "\n\nLinks:\n------\n";
479 foreach ($this->_link_list
as $idx => $url) {
480 $text .= '[' . ($idx+
1) . '] ' . $url . "\n";
486 $this->_converted
= true;
490 * Workhorse function that does actual conversion.
492 * First performs custom tag replacement specified by $search and
493 * $replace arrays. Then strips any remaining HTML tags, reduces whitespace
494 * and newlines to a readable format, and word wraps the text to
497 * @param string Reference to HTML content string
502 function _converter(&$text)
504 // Convert <BLOCKQUOTE> (before PRE!)
505 $this->_convert_blockquotes($text);
508 $this->_convert_pre($text);
510 // Run our defined tags search-and-replace
511 $text = preg_replace($this->search
, $this->replace
, $text);
513 // Run our defined tags search-and-replace with callback
514 $text = preg_replace_callback($this->callback_search
, array('html2text', '_preg_callback'), $text);
516 // Strip any other HTML tags
517 $text = strip_tags($text, $this->allowed_tags
);
519 // Run our defined entities/characters search-and-replace
520 $text = preg_replace($this->ent_search
, $this->ent_replace
, $text);
522 // Replace known html entities
523 $text = html_entity_decode($text, ENT_COMPAT
, 'UTF-8');
525 // Remove unknown/unhandled entities (this cannot be done in search-and-replace block)
526 $text = preg_replace('/&([a-zA-Z0-9]{2,6}|#[0-9]{2,4});/', '', $text);
528 // Convert "|+|amp|+|" into "&", need to be done after handling of unknown entities
529 // This properly handles situation of "&quot;" in input string
530 $text = str_replace('|+|amp|+|', '&', $text);
532 // Bring down number of empty lines to 2 max
533 $text = preg_replace("/\n\s+\n/", "\n\n", $text);
534 $text = preg_replace("/[\n]{3,}/", "\n\n", $text);
536 // remove leading empty lines (can be produced by eg. P tag on the beginning)
537 $text = ltrim($text, "\n");
539 // Wrap the text to a readable format
540 // for PHP versions >= 4.0.2. Default width is 75
541 // If width is 0 or less, don't wrap the text.
542 if ( $this->width
> 0 ) {
543 $text = wordwrap($text, $this->width
);
548 * Helper function called by preg_replace() on link replacement.
550 * Maintains an internal list of links to be displayed at the end of the
551 * text, with numeric indices to the original point in the text they
552 * appeared. Also makes an effort at identifying and handling absolute
553 * and relative links.
555 * @param string $link URL of the link
556 * @param string $display Part of the text to associate number with
560 function _build_link_list( $link, $display )
562 if (!$this->_do_links ||
empty($link)) {
566 // Ignored link types
567 if (preg_match('!^(javascript|mailto|#):!i', $link)) {
571 if (preg_match('!^(https?://)!i', $link)) {
576 if (substr($link, 0, 1) != '/') {
582 if (($index = array_search($url, $this->_link_list
)) === false) {
583 // Add the link to the list.
584 $this->_link_list
[] = $url;
585 $index = count($this->_link_list
);
588 // Use the index of the existing link in the list (we enumerate from 1, not from 0).
592 return $display . ' [' . ($index) . ']';
596 * Helper function for PRE body conversion.
598 * @param string HTML content
601 function _convert_pre(&$text)
603 // get the content of PRE element
604 while (preg_match('/<pre[^>]*>(.*)<\/pre>/ismU', $text, $matches)) {
605 // convert the content
606 $this->pre_content
= sprintf('<div><br>%s<br></div>',
607 preg_replace($this->pre_search
, $this->pre_replace
, $matches[1]));
608 // replace the content (use callback because content can contain $0 variable)
609 $text = preg_replace_callback('/<pre[^>]*>.*<\/pre>/ismU',
610 array('html2text', '_preg_pre_callback'), $text, 1);
612 $this->pre_content
= '';
617 * Helper function for BLOCKQUOTE body conversion.
619 * @param string HTML content
622 function _convert_blockquotes(&$text)
624 if (preg_match_all('/<\/*blockquote[^>]*>/i', $text, $matches, PREG_OFFSET_CAPTURE
)) {
627 foreach ($matches[0] as $m) {
628 if ($m[0][0] == '<' && $m[0][1] == '/') {
631 $level = 0; // malformed HTML: go to next blockquote
633 else if ($level > 0) {
634 // skip inner blockquote
638 $len = $end - $taglen - $start;
639 // Get blockquote content
640 $body = substr($text, $start +
$taglen - $diff, $len);
643 $p_width = $this->width
;
644 if ($this->width
> 0) $this->width
-= 2;
645 // Convert blockquote content
647 $this->_converter($body);
648 // Add citation markers and create PRE block
649 $body = preg_replace('/((^|\n)>*)/', '\\1> ', trim($body));
650 $body = '<pre>' . htmlspecialchars($body) . '</pre>';
652 $this->width
= $p_width;
654 $text = substr($text, 0, $start - $diff)
655 . $body . substr($text, $end +
strlen($m[0]) - $diff);
657 $diff = $len +
$taglen +
strlen($m[0]) - strlen($body);
664 $taglen = strlen($m[0]);
673 * Callback function for preg_replace_callback use.
675 * @param array PREG matches
678 private function _preg_callback($matches)
680 switch($matches[1]) {
683 return $this->_toupper($matches[2]);
685 return $this->_toupper("\t\t". $matches[2] ."\n");
687 return $this->_toupper("\n\n". $matches[2] ."\n\n");
689 // Remove spaces in URL (#1487805)
690 $url = str_replace(' ', '', $matches[3]);
691 return $this->_build_link_list($url, $matches[4]);
693 return '[' . $matches[2] . ']';
698 * Callback function for preg_replace_callback use in PRE content handler.
700 * @param array PREG matches
703 private function _preg_pre_callback($matches)
705 return $this->pre_content
;
709 * Strtoupper function with HTML tags and entities handling.
711 * @param string $str Text to convert
712 * @return string Converted text
714 private function _toupper($str)
716 // string can containg HTML tags
717 $chunks = preg_split('/(<[^>]*>)/', $str, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
);
719 // convert toupper only the text between HTML tags
720 foreach ($chunks as $idx => $chunk) {
721 if ($chunk[0] != '<') {
722 $chunks[$idx] = $this->_strtoupper($chunk);
726 return implode($chunks);
730 * Strtoupper multibyte wrapper function with HTML entities handling.
732 * @param string $str Text to convert
733 * @return string Converted text
735 private function _strtoupper($str)
737 $str = html_entity_decode($str, ENT_COMPAT
, RCMAIL_CHARSET
);
739 if (class_exists('core_text'))
740 $str = core_text
::strtoupper($str);
741 else if (function_exists('mb_strtoupper'))
742 $str = mb_strtoupper($str);
744 $str = strtoupper($str);
746 $str = htmlspecialchars($str, ENT_COMPAT
, RCMAIL_CHARSET
);