timeline: if a section is set to hidden and the user is not capable of editing a...
[moodle-blog-course-format.git] / lib / html2text.php
blobb7e3e3e9ec420e50c514fd252c91db4fd9e769ed
1 <?php
3 /*************************************************************************
4 * *
5 * class.html2text.inc *
6 * *
7 *************************************************************************
8 * *
9 * Converts HTML to formatted plain text *
10 * *
11 * Copyright (c) 2005-2007 Jon Abernathy <jon@chuggnutt.com> *
12 * All rights reserved. *
13 * *
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. *
18 * *
19 * The GNU General Public License can be found at *
20 * http://www.gnu.org/copyleft/gpl.html. *
21 * *
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. *
26 * *
27 * Author(s): Jon Abernathy <jon@chuggnutt.com> *
28 * *
29 * Last modified: 08/08/07 *
30 * *
31 *************************************************************************/
33 require_once "$CFG->libdir/textlib.class.php";
35 /**
36 * Takes HTML and converts it to formatted, plain text.
38 * Thanks to Alexander Krug (http://www.krugar.de/) to pointing out and
39 * correcting an error in the regexp search array. Fixed 7/30/03.
41 * Updated set_html() function's file reading mechanism, 9/25/03.
43 * Thanks to Joss Sanglier (http://www.dancingbear.co.uk/) for adding
44 * several more HTML entity codes to the $search and $replace arrays.
45 * Updated 11/7/03.
47 * Thanks to Darius Kasperavicius (http://www.dar.dar.lt/) for
48 * suggesting the addition of $allowed_tags and its supporting function
49 * (which I slightly modified). Updated 3/12/04.
51 * Thanks to Justin Dearing for pointing out that a replacement for the
52 * <TH> tag was missing, and suggesting an appropriate fix.
53 * Updated 8/25/04.
55 * Thanks to Mathieu Collas (http://www.myefarm.com/) for finding a
56 * display/formatting bug in the _build_link_list() function: email
57 * readers would show the left bracket and number ("[1") as part of the
58 * rendered email address.
59 * Updated 12/16/04.
61 * Thanks to Wojciech Bajon (http://histeria.pl/) for submitting code
62 * to handle relative links, which I hadn't considered. I modified his
63 * code a bit to handle normal HTTP links and MAILTO links. Also for
64 * suggesting three additional HTML entity codes to search for.
65 * Updated 03/02/05.
67 * Thanks to Jacob Chandler for pointing out another link condition
68 * for the _build_link_list() function: "https".
69 * Updated 04/06/05.
71 * Thanks to Marc Bertrand (http://www.dresdensky.com/) for
72 * suggesting a revision to the word wrapping functionality; if you
73 * specify a $width of 0 or less, word wrapping will be ignored.
74 * Updated 11/02/06.
76 * *** Big housecleaning updates below:
78 * Thanks to Colin Brown (http://www.sparkdriver.co.uk/) for
79 * suggesting the fix to handle </li> and blank lines (whitespace).
80 * Christian Basedau (http://www.movetheweb.de/) also suggested the
81 * blank lines fix.
83 * Special thanks to Marcus Bointon (http://www.synchromedia.co.uk/),
84 * Christian Basedau, Norbert Laposa (http://ln5.co.uk/),
85 * Bas van de Weijer, and Marijn van Butselaar
86 * for pointing out my glaring error in the <th> handling. Marcus also
87 * supplied a host of fixes.
89 * Thanks to Jeffrey Silverman (http://www.newtnotes.com/) for pointing
90 * out that extra spaces should be compressed--a problem addressed with
91 * Marcus Bointon's fixes but that I had not yet incorporated.
93 * Thanks to Daniel Schledermann (http://www.typoconsult.dk/) for
94 * suggesting a valuable fix with <a> tag handling.
96 * Thanks to Wojciech Bajon (again!) for suggesting fixes and additions,
97 * including the <a> tag handling that Daniel Schledermann pointed
98 * out but that I had not yet incorporated. I haven't (yet)
99 * incorporated all of Wojciech's changes, though I may at some
100 * future time.
102 * *** End of the housecleaning updates. Updated 08/08/07.
104 * @author Jon Abernathy <jon@chuggnutt.com>
105 * @version 1.0.0
106 * @since PHP 4.0.2
108 class html2text
112 * Contains the HTML content to convert.
114 * @var string $html
115 * @access public
117 var $html;
120 * Contains the converted, formatted text.
122 * @var string $text
123 * @access public
125 var $text;
128 * Maximum width of the formatted text, in columns.
130 * Set this value to 0 (or less) to ignore word wrapping
131 * and not constrain text to a fixed-width column.
133 * @var integer $width
134 * @access public
136 var $width = 70;
139 * List of preg* regular expression patterns to search for,
140 * used in conjunction with $replace.
142 * @var array $search
143 * @access public
144 * @see $replace
146 var $search = array(
147 "/\r/", // Non-legal carriage return
148 "/[\n\t]+/", // Newlines and tabs
149 '/[ ]{2,}/', // Runs of spaces, pre-handling
150 '/<script[^>]*>.*?<\/script>/i', // <script>s -- which strip_tags supposedly has problems with
151 '/<style[^>]*>.*?<\/style>/i', // <style>s -- which strip_tags supposedly has problems with
152 //'/<!-- .* -->/', // Comments -- which strip_tags might have problem a 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 '/(<table[^>]*>|<\/table>)/i', // <table> and </table>
163 '/(<tr[^>]*>|<\/tr>)/i', // <tr> and </tr>
164 '/<td[^>]*>(.*?)<\/td>/i', // <td> and </td>
165 '/&(nbsp|#160);/i', // Non-breaking space
166 '/&(quot|rdquo|ldquo|#8220|#8221|#147|#148);/i',
167 // Double quotes
168 '/&(apos|rsquo|lsquo|#8216|#8217);/i', // Single quotes
169 '/&gt;/i', // Greater-than
170 '/&lt;/i', // Less-than
171 '/&(amp|#38);/i', // Ampersand
172 '/&(copy|#169);/i', // Copyright
173 '/&(trade|#8482|#153);/i', // Trademark
174 '/&(reg|#174);/i', // Registered
175 '/&(mdash|#151|#8212);/i', // mdash
176 '/&(ndash|minus|#8211|#8722);/i', // ndash
177 '/&(bull|#149|#8226);/i', // Bullet
178 '/&(pound|#163);/i', // Pound sign
179 '/&(euro|#8364);/i', // Euro sign
180 '/[ ]{2,}/' // Runs of spaces, post-handling
184 * List of pattern replacements corresponding to patterns searched.
186 * @var array $replace
187 * @access public
188 * @see $search
190 var $replace = array(
191 '', // Non-legal carriage return
192 ' ', // Newlines and tabs
193 ' ', // Runs of spaces, pre-handling
194 '', // <script>s -- which strip_tags supposedly has problems with
195 '', // <style>s -- which strip_tags supposedly has problems with
196 //'', // Comments -- which strip_tags might have problem a with
197 "\n\n", // <P>
198 "\n", // <br>
199 '_\\1_', // <i>
200 '_\\1_', // <em>
201 "\n\n", // <ul> and </ul>
202 "\n\n", // <ol> and </ol>
203 "\t* \\1\n", // <li> and </li>
204 "\n\t* ", // <li>
205 "\n-------------------------\n", // <hr>
206 "\n\n", // <table> and </table>
207 "\n", // <tr> and </tr>
208 "\t\t\\1\n", // <td> and </td>
209 ' ', // Non-breaking space
210 '"', // Double quotes
211 "'", // Single quotes
212 '>',
213 '<',
214 '&',
215 '(c)',
216 '(tm)',
217 '(R)',
218 '--',
219 '-',
220 '*',
221 '£',
222 'EUR', // Euro sign. € ?
223 ' ' // Runs of spaces, post-handling
227 * List of preg* regular expression patterns to search for
228 * and replace using callback function.
230 * @var array $callback_search
231 * @access public
233 var $callback_search = array(
234 '/<(h)[123456][^>]*>(.*?)<\/h[123456]>/i', // H1 - H3
235 '/<(b)[^>]*>(.*?)<\/b>/i', // <b>
236 '/<(strong)[^>]*>(.*?)<\/strong>/i', // <strong>
237 '/<(a) [^>]*href=("|\')([^"\']+)\2[^>]*>(.*?)<\/a>/i',
238 // <a href="">
239 '/<(th)[^>]*>(.*?)<\/th>/i', // <th> and </th>
243 * List of preg* regular expression patterns to search for in PRE body,
244 * used in conjunction with $pre_replace.
246 * @var array $pre_search
247 * @access public
248 * @see $pre_replace
250 var $pre_search = array(
251 "/\n/",
252 "/\t/",
253 '/ /',
254 '/<pre[^>]*>/',
255 '/<\/pre>/'
259 * List of pattern replacements corresponding to patterns searched for PRE body.
261 * @var array $pre_replace
262 * @access public
263 * @see $pre_search
265 var $pre_replace = array(
266 '<br>',
267 '&nbsp;&nbsp;&nbsp;&nbsp;',
268 '&nbsp;',
274 * Contains a list of HTML tags to allow in the resulting text.
276 * @var string $allowed_tags
277 * @access public
278 * @see set_allowed_tags()
280 var $allowed_tags = '';
283 * Contains the base URL that relative links should resolve to.
285 * @var string $url
286 * @access public
288 var $url;
291 * Indicates whether content in the $html variable has been converted yet.
293 * @var boolean $_converted
294 * @access private
295 * @see $html, $text
297 var $_converted = false;
300 * Contains URL addresses from links to be rendered in plain text.
302 * @var string $_link_list
303 * @access private
304 * @see _build_link_list()
306 var $_link_list = '';
309 * Number of valid links detected in the text, used for plain text
310 * display (rendered similar to footnotes).
312 * @var integer $_link_count
313 * @access private
314 * @see _build_link_list()
316 var $_link_count = 0;
318 /**
319 * Boolean flag, true if a table of link URLs should be listed after the text.
321 * @var boolean $_do_links
322 * @access private
323 * @see html2text()
325 var $_do_links = true;
328 * Constructor.
330 * If the HTML source string (or file) is supplied, the class
331 * will instantiate with that source propagated, all that has
332 * to be done it to call get_text().
334 * @param string $source HTML content
335 * @param boolean $from_file Indicates $source is a file to pull content from
336 * @param boolean $do_links Indicate whether a table of link URLs is desired
337 * @param integer $width Maximum width of the formatted text, 0 for no limit
338 * @access public
339 * @return void
341 function html2text( $source = '', $from_file = false, $do_links = true, $width = 75 )
343 if ( !empty($source) ) {
344 $this->set_html($source, $from_file);
347 $this->set_base_url();
348 $this->_do_links = $do_links;
349 $this->width = $width;
353 * Loads source HTML into memory, either from $source string or a file.
355 * @param string $source HTML content
356 * @param boolean $from_file Indicates $source is a file to pull content from
357 * @access public
358 * @return void
360 function set_html( $source, $from_file = false )
362 if ( $from_file && file_exists($source) ) {
363 $this->html = file_get_contents($source);
365 else
366 $this->html = $source;
368 $this->_converted = false;
372 * Returns the text, converted from HTML.
374 * @access public
375 * @return string
377 function get_text()
379 if ( !$this->_converted ) {
380 $this->_convert();
383 return $this->text;
387 * Prints the text, converted from HTML.
389 * @access public
390 * @return void
392 function print_text()
394 print $this->get_text();
398 * Alias to print_text(), operates identically.
400 * @access public
401 * @return void
402 * @see print_text()
404 function p()
406 print $this->get_text();
410 * Sets the allowed HTML tags to pass through to the resulting text.
412 * Tags should be in the form "<p>", with no corresponding closing tag.
414 * @access public
415 * @return void
417 function set_allowed_tags( $allowed_tags = '' )
419 if ( !empty($allowed_tags) ) {
420 $this->allowed_tags = $allowed_tags;
425 * Sets a base URL to handle relative links.
427 * @access public
428 * @return void
430 function set_base_url( $url = '' )
432 if ( empty($url) ) {
433 if ( !empty($_SERVER['HTTP_HOST']) ) {
434 $this->url = 'http://' . $_SERVER['HTTP_HOST'];
435 } else {
436 $this->url = '';
438 } else {
439 // Strip any trailing slashes for consistency (relative
440 // URLs may already start with a slash like "/file.html")
441 if ( substr($url, -1) == '/' ) {
442 $url = substr($url, 0, -1);
444 $this->url = $url;
449 * Workhorse function that does actual conversion.
451 * First performs custom tag replacement specified by $search and
452 * $replace arrays. Then strips any remaining HTML tags, reduces whitespace
453 * and newlines to a readable format, and word wraps the text to
454 * $width characters.
456 * @access private
457 * @return void
459 function _convert()
461 // Variables used for building the link list
462 $this->_link_count = 0;
463 $this->_link_list = '';
465 $text = trim(stripslashes($this->html));
467 // Convert <PRE>
468 $this->_convert_pre($text);
470 // Run our defined search-and-replace
471 $text = preg_replace($this->search, $this->replace, $text);
472 $text = preg_replace_callback($this->callback_search, array(&$this, '_preg_callback'), $text);
474 // Replace known html entities
475 $tl=textlib_get_instance();
476 $text = $tl->entities_to_utf8($text, true);
478 // Remove unknown/unhandled entities (this cannot be done in search-and-replace block)
479 $text = preg_replace('/&[^&;]+;/i', '', $text);
481 // Strip any other HTML tags
482 $text = strip_tags($text, $this->allowed_tags);
484 // Bring down number of empty lines to 2 max
485 $text = preg_replace("/\n\s+\n/", "\n\n", $text);
486 $text = preg_replace("/[\n]{3,}/", "\n\n", $text);
488 // Add link list
489 if ( !empty($this->_link_list) ) {
490 $text .= "\n\nLinks:\n------\n" . $this->_link_list;
493 // Wrap the text to a readable format
494 // for PHP versions >= 4.0.2. Default width is 75
495 // If width is 0 or less, don't wrap the text.
496 if ( $this->width > 0 ) {
497 $text = wordwrap($text, $this->width);
500 $this->text = $text;
502 $this->_converted = true;
506 * Helper function called by preg_replace() on link replacement.
508 * Maintains an internal list of links to be displayed at the end of the
509 * text, with numeric indices to the original point in the text they
510 * appeared. Also makes an effort at identifying and handling absolute
511 * and relative links.
513 * @param string $link URL of the link
514 * @param string $display Part of the text to associate number with
515 * @access private
516 * @return string
518 function _build_link_list( $link, $display )
520 if ( !$this->_do_links ) return $display;
522 if ( substr($link, 0, 7) == 'http://' || substr($link, 0, 8) == 'https://' ||
523 substr($link, 0, 7) == 'mailto:' ) {
524 $this->_link_count++;
525 $this->_link_list .= "[" . $this->_link_count . "] $link\n";
526 $additional = ' [' . $this->_link_count . ']';
527 } elseif ( substr($link, 0, 11) == 'javascript:' ) {
528 // Don't count the link; ignore it
529 $additional = '';
530 // what about href="#anchor" ?
531 } else {
532 $this->_link_count++;
533 $this->_link_list .= "[" . $this->_link_count . "] " . $this->url;
534 if ( substr($link, 0, 1) != '/' ) {
535 $this->_link_list .= '/';
537 $this->_link_list .= "$link\n";
538 $additional = ' [' . $this->_link_count . ']';
541 return $display . $additional;
545 * Helper function for PRE body conversion.
547 * @param string HTML content
548 * @access private
550 function _convert_pre(&$text)
552 while(preg_match('/<pre[^>]*>(.*)<\/pre>/ismU', $text, $matches)) {
553 $result = preg_replace($this->pre_search, $this->pre_replace, $matches[1]);
554 $text = preg_replace('/<pre[^>]*>.*<\/pre>/ismU', '<div><br>' . $result . '<br></div>', $text, 1);
559 * Callback function for preg_replace_callback use.
561 * @param array PREG matches
562 * @return string
563 * @access private
565 function _preg_callback($matches)
567 switch($matches[1]) {
568 case 'b':
569 case 'strong':
570 return $this->_strtoupper($matches[2]);
571 case 'hr':
572 return $this->_strtoupper("\t\t". $matches[2] ."\n");
573 case 'h':
574 return $this->_strtoupper("\n\n". $matches[2] ."\n\n");
575 case 'a':
576 return $this->_build_link_list($matches[3], $matches[4]);
581 * Strtoupper multibyte wrapper function
583 * @param string
584 * @return string
585 * @access private
587 function _strtoupper($str)
589 if (function_exists('mb_strtoupper'))
590 return mb_strtoupper($str);
591 else
592 return strtoupper($str);