3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 // Author(s): Jon Abernathy <jon@chuggnutt.com>
19 // Copyright (c) 2005-2007 Jon Abernathy <jon@chuggnutt.com>
22 * Takes HTML and converts it to formatted, plain text.
24 * Thanks to Alexander Krug (http://www.krugar.de/) to pointing out and
25 * correcting an error in the regexp search array. Fixed 7/30/03.
27 * Updated set_html() function's file reading mechanism, 9/25/03.
29 * Thanks to Joss Sanglier (http://www.dancingbear.co.uk/) for adding
30 * several more HTML entity codes to the $search and $replace arrays.
33 * Thanks to Darius Kasperavicius (http://www.dar.dar.lt/) for
34 * suggesting the addition of $allowed_tags and its supporting function
35 * (which I slightly modified). Updated 3/12/04.
37 * Thanks to Justin Dearing for pointing out that a replacement for the
38 * <TH> tag was missing, and suggesting an appropriate fix.
41 * Thanks to Mathieu Collas (http://www.myefarm.com/) for finding a
42 * display/formatting bug in the _build_link_list() function: email
43 * readers would show the left bracket and number ("[1") as part of the
44 * rendered email address.
47 * Thanks to Wojciech Bajon (http://histeria.pl/) for submitting code
48 * to handle relative links, which I hadn't considered. I modified his
49 * code a bit to handle normal HTTP links and MAILTO links. Also for
50 * suggesting three additional HTML entity codes to search for.
53 * Thanks to Jacob Chandler for pointing out another link condition
54 * for the _build_link_list() function: "https".
57 * Thanks to Marc Bertrand (http://www.dresdensky.com/) for
58 * suggesting a revision to the word wrapping functionality; if you
59 * specify a $width of 0 or less, word wrapping will be ignored.
62 * *** Big housecleaning updates below:
64 * Thanks to Colin Brown (http://www.sparkdriver.co.uk/) for
65 * suggesting the fix to handle </li> and blank lines (whitespace).
66 * Christian Basedau (http://www.movetheweb.de/) also suggested the
69 * Special thanks to Marcus Bointon (http://www.synchromedia.co.uk/),
70 * Christian Basedau, Norbert Laposa (http://ln5.co.uk/),
71 * Bas van de Weijer, and Marijn van Butselaar
72 * for pointing out my glaring error in the <th> handling. Marcus also
73 * supplied a host of fixes.
75 * Thanks to Jeffrey Silverman (http://www.newtnotes.com/) for pointing
76 * out that extra spaces should be compressed--a problem addressed with
77 * Marcus Bointon's fixes but that I had not yet incorporated.
79 * Thanks to Daniel Schledermann (http://www.typoconsult.dk/) for
80 * suggesting a valuable fix with <a> tag handling.
82 * Thanks to Wojciech Bajon (again!) for suggesting fixes and additions,
83 * including the <a> tag handling that Daniel Schledermann pointed
84 * out but that I had not yet incorporated. I haven't (yet)
85 * incorporated all of Wojciech's changes, though I may at some
88 * *** End of the housecleaning updates. Updated 08/08/07.
91 * @copyright Jon Abernathy <jon@chuggnutt.com>
92 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
97 * @copyright Jon Abernathy <jon@chuggnutt.com>
98 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
104 * Contains the HTML content to convert.
112 * Contains the converted, formatted text.
120 * Maximum width of the formatted text, in columns.
122 * Set this value to 0 (or less) to ignore word wrapping
123 * and not constrain text to a fixed-width column.
125 * @var integer $width
131 * List of preg* regular expression patterns to search for,
132 * used in conjunction with $replace.
139 "/\r/", // Non-legal carriage return
140 "/[\n\t]+/", // Newlines and tabs
141 '/[ ]{2,}/', // Runs of spaces, pre-handling
142 '/<script[^>]*>.*?<\/script>/i', // <script>s -- which strip_tags supposedly has problems with
143 '/<style[^>]*>.*?<\/style>/i', // <style>s -- which strip_tags supposedly has problems with
144 //'/<!-- .* -->/', // Comments -- which strip_tags might have problem a with
145 '/<p[^>]*>/i', // <P>
146 '/<br[^>]*>/i', // <br>
147 '/<i[^>]*>(.*?)<\/i>/i', // <i>
148 '/<em[^>]*>(.*?)<\/em>/i', // <em>
149 '/(<ul[^>]*>|<\/ul>)/i', // <ul> and </ul>
150 '/(<ol[^>]*>|<\/ol>)/i', // <ol> and </ol>
151 '/<li[^>]*>(.*?)<\/li>/i', // <li> and </li>
152 '/<li[^>]*>/i', // <li>
153 '/<hr[^>]*>/i', // <hr>
154 '/(<table[^>]*>|<\/table>)/i', // <table> and </table>
155 '/(<tr[^>]*>|<\/tr>)/i', // <tr> and </tr>
156 '/<td[^>]*>(.*?)<\/td>/i', // <td> and </td>
157 '/&(nbsp|#160);/i', // Non-breaking space
158 '/&(quot|rdquo|ldquo|#8220|#8221|#147|#148);/i',
160 '/&(apos|rsquo|lsquo|#8216|#8217);/i', // Single quotes
161 '/>/i', // Greater-than
162 '/</i', // Less-than
163 '/&(amp|#38);/i', // Ampersand
164 '/&(copy|#169);/i', // Copyright
165 '/&(trade|#8482|#153);/i', // Trademark
166 '/&(reg|#174);/i', // Registered
167 '/&(mdash|#151|#8212);/i', // mdash
168 '/&(ndash|minus|#8211|#8722);/i', // ndash
169 '/&(bull|#149|#8226);/i', // Bullet
170 '/&(pound|#163);/i', // Pound sign
171 '/&(euro|#8364);/i', // Euro sign
172 '/[ ]{2,}/' // Runs of spaces, post-handling
176 * List of pattern replacements corresponding to patterns searched.
178 * @var array $replace
182 var $replace = array(
183 '', // Non-legal carriage return
184 ' ', // Newlines and tabs
185 ' ', // Runs of spaces, pre-handling
186 '', // <script>s -- which strip_tags supposedly has problems with
187 '', // <style>s -- which strip_tags supposedly has problems with
188 //'', // Comments -- which strip_tags might have problem a with
193 "\n\n", // <ul> and </ul>
194 "\n\n", // <ol> and </ol>
195 "\t* \\1\n", // <li> and </li>
197 "\n-------------------------\n", // <hr>
198 "\n\n", // <table> and </table>
199 "\n", // <tr> and </tr>
200 "\t\t\\1\n", // <td> and </td>
201 ' ', // Non-breaking space
202 '"', // Double quotes
203 "'", // Single quotes
214 'EUR', // Euro sign. € ?
215 ' ' // Runs of spaces, post-handling
219 * List of preg* regular expression patterns to search for
220 * and replace using callback function.
222 * @var array $callback_search
225 var $callback_search = array(
226 '/<(h)[123456][^>]*>(.*?)<\/h[123456]>/i', // H1 - H3
227 '/<(b)[^>]*>(.*?)<\/b>/i', // <b>
228 '/<(strong)[^>]*>(.*?)<\/strong>/i', // <strong>
229 '/<(a) [^>]*href=("|\')([^"\']+)\2[^>]*>(.*?)<\/a>/i',
231 '/<(th)[^>]*>(.*?)<\/th>/i', // <th> and </th>
232 '/<(img)[^>]*alt=\"([^>"]+)\"[^>]*>/i', // <img> with alt
236 * List of preg* regular expression patterns to search for in PRE body,
237 * used in conjunction with $pre_replace.
239 * @var array $pre_search
243 var $pre_search = array(
252 * List of pattern replacements corresponding to patterns searched for PRE body.
254 * @var array $pre_replace
258 var $pre_replace = array(
260 ' ',
267 * Contains a list of HTML tags to allow in the resulting text.
269 * @var string $allowed_tags
271 * @see set_allowed_tags()
273 var $allowed_tags = '';
276 * Contains the base URL that relative links should resolve to.
284 * Indicates whether content in the $html variable has been converted yet.
286 * @var boolean $_converted
290 var $_converted = false;
293 * Contains URL addresses from links to be rendered in plain text.
295 * @var string $_link_list
297 * @see _build_link_list()
299 var $_link_list = '';
302 * Number of valid links detected in the text, used for plain text
303 * display (rendered similar to footnotes).
305 * @var integer $_link_count
307 * @see _build_link_list()
309 var $_link_count = 0;
312 * Boolean flag, true if a table of link URLs should be listed after the text.
314 * @var boolean $_do_links
318 var $_do_links = true;
323 * If the HTML source string (or file) is supplied, the class
324 * will instantiate with that source propagated, all that has
325 * to be done it to call get_text().
327 * @param string $source HTML content
328 * @param boolean $from_file Indicates $source is a file to pull content from
329 * @param boolean $do_links Indicate whether a table of link URLs is desired
330 * @param integer $width Maximum width of the formatted text, 0 for no limit
334 function html2text( $source = '', $from_file = false, $do_links = true, $width = 75 )
336 if ( !empty($source) ) {
337 $this->set_html($source, $from_file);
340 $this->set_base_url();
341 $this->_do_links
= $do_links;
342 $this->width
= $width;
346 * Loads source HTML into memory, either from $source string or a file.
348 * @param string $source HTML content
349 * @param boolean $from_file Indicates $source is a file to pull content from
353 function set_html( $source, $from_file = false )
355 if ( $from_file && file_exists($source) ) {
356 $this->html
= file_get_contents($source);
359 $this->html
= $source;
361 $this->_converted
= false;
365 * Returns the text, converted from HTML.
372 if ( !$this->_converted
) {
380 * Prints the text, converted from HTML.
385 function print_text()
387 print $this->get_text();
391 * Alias to print_text(), operates identically.
399 print $this->get_text();
403 * Sets the allowed HTML tags to pass through to the resulting text.
405 * Tags should be in the form "<p>", with no corresponding closing tag.
410 function set_allowed_tags( $allowed_tags = '' )
412 if ( !empty($allowed_tags) ) {
413 $this->allowed_tags
= $allowed_tags;
418 * Sets a base URL to handle relative links.
423 function set_base_url( $url = '' )
426 if ( !empty($_SERVER['HTTP_HOST']) ) {
427 $this->url
= 'http://' . $_SERVER['HTTP_HOST'];
432 // Strip any trailing slashes for consistency (relative
433 // URLs may already start with a slash like "/file.html")
434 if ( substr($url, -1) == '/' ) {
435 $url = substr($url, 0, -1);
442 * Workhorse function that does actual conversion.
444 * First performs custom tag replacement specified by $search and
445 * $replace arrays. Then strips any remaining HTML tags, reduces whitespace
446 * and newlines to a readable format, and word wraps the text to
454 // Variables used for building the link list
455 $this->_link_count
= 0;
456 $this->_link_list
= '';
458 $text = trim($this->html
);
461 $this->_convert_pre($text);
463 // Run our defined search-and-replace
464 $text = preg_replace($this->search
, $this->replace
, $text);
465 $text = preg_replace_callback($this->callback_search
, array('html2text', '_preg_callback'), $text);
467 // Replace known html entities
468 $text = html_entity_decode($text, ENT_COMPAT
, 'UTF-8');
470 // Remove unknown/unhandled entities (this cannot be done in search-and-replace block)
471 $text = preg_replace('/&[^&;]+;/i', '', $text);
473 // Strip any other HTML tags
474 $text = strip_tags($text, $this->allowed_tags
);
476 // Bring down number of empty lines to 2 max
477 $text = preg_replace("/\n\s+\n/", "\n\n", $text);
478 $text = preg_replace("/[\n]{3,}/", "\n\n", $text);
481 if ( !empty($this->_link_list
) ) {
482 $text .= "\n\nLinks:\n------\n" . $this->_link_list
;
485 // Wrap the text to a readable format
486 // for PHP versions >= 4.0.2. Default width is 75
487 // If width is 0 or less, don't wrap the text.
488 if ( $this->width
> 0 ) {
489 $text = wordwrap($text, $this->width
);
494 $this->_converted
= true;
498 * Helper function called by preg_replace() on link replacement.
500 * Maintains an internal list of links to be displayed at the end of the
501 * text, with numeric indices to the original point in the text they
502 * appeared. Also makes an effort at identifying and handling absolute
503 * and relative links.
505 * @param string $link URL of the link
506 * @param string $display Part of the text to associate number with
510 function _build_link_list( $link, $display )
512 if ( !$this->_do_links
) return $display;
514 if ( substr($link, 0, 7) == 'http://' ||
substr($link, 0, 8) == 'https://' ||
515 substr($link, 0, 7) == 'mailto:' ) {
516 $this->_link_count++
;
517 $this->_link_list
.= "[" . $this->_link_count
. "] $link\n";
518 $additional = ' [' . $this->_link_count
. ']';
519 } elseif ( substr($link, 0, 11) == 'javascript:' ) {
520 // Don't count the link; ignore it
522 // what about href="#anchor" ?
524 $this->_link_count++
;
525 $this->_link_list
.= "[" . $this->_link_count
. "] " . $this->url
;
526 if ( substr($link, 0, 1) != '/' ) {
527 $this->_link_list
.= '/';
529 $this->_link_list
.= "$link\n";
530 $additional = ' [' . $this->_link_count
. ']';
533 return $display . $additional;
537 * Helper function for PRE body conversion.
539 * @param string $text HTML content
542 function _convert_pre(&$text)
544 while(preg_match('/<pre[^>]*>(.*)<\/pre>/ismU', $text, $matches)) {
545 $result = preg_replace($this->pre_search
, $this->pre_replace
, $matches[1]);
546 $text = preg_replace('/<pre[^>]*>.*<\/pre>/ismU', '<div><br>' . $result . '<br></div>', $text, 1);
551 * Callback function for preg_replace_callback use.
553 * @param array $matches PREG matches
557 function _preg_callback($matches)
559 switch($matches[1]) {
562 return $this->_strtoupper($matches[2]);
564 return $this->_strtoupper("\t\t". $matches[2] ."\n");
566 return $this->_strtoupper("\n\n". $matches[2] ."\n\n");
568 return $this->_build_link_list($matches[3], $matches[4]);
570 return '[' . $matches[2] . ']';
575 * Strtoupper multibyte wrapper function
581 function _strtoupper($str)
583 $tl = textlib_get_instance();
584 return $tl->strtoupper($str);