Merge branch 'MDL-29276' of git://github.com/mouneyrac/moodle
[moodle.git] / lib / html2text.php
blobe2d0dffddbc54c8d9b0fef3e63dca67c29c390d2
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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>
21 /**
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.
31 * Updated 11/7/03.
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.
39 * Updated 8/25/04.
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.
45 * Updated 12/16/04.
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.
51 * Updated 03/02/05.
53 * Thanks to Jacob Chandler for pointing out another link condition
54 * for the _build_link_list() function: "https".
55 * Updated 04/06/05.
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.
60 * Updated 11/02/06.
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
67 * blank lines fix.
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
86 * future time.
88 * *** End of the housecleaning updates. Updated 08/08/07.
90 * @package moodlecore
91 * @copyright Jon Abernathy <jon@chuggnutt.com>
92 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
95 /**
96 * @package moodlecore
97 * @copyright Jon Abernathy <jon@chuggnutt.com>
98 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
100 class html2text
104 * Contains the HTML content to convert.
106 * @var string $html
107 * @access public
109 var $html;
112 * Contains the converted, formatted text.
114 * @var string $text
115 * @access public
117 var $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
126 * @access public
128 var $width = 70;
131 * List of preg* regular expression patterns to search for,
132 * used in conjunction with $replace.
134 * @var array $search
135 * @access public
136 * @see $replace
138 var $search = array(
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',
159 // Double quotes
160 '/&(apos|rsquo|lsquo|#8216|#8217);/i', // Single quotes
161 '/&gt;/i', // Greater-than
162 '/&lt;/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 '/[ ]+([\n\t])/', // Trailing spaces before newline or tab
173 '/[ ]{2,}/' // Runs of spaces, post-handling
177 * List of pattern replacements corresponding to patterns searched.
179 * @var array $replace
180 * @access public
181 * @see $search
183 var $replace = array(
184 '', // Non-legal carriage return
185 ' ', // Newlines and tabs
186 ' ', // Runs of spaces, pre-handling
187 '', // <script>s -- which strip_tags supposedly has problems with
188 '', // <style>s -- which strip_tags supposedly has problems with
189 //'', // Comments -- which strip_tags might have problem a with
190 "\n\n", // <P>
191 "\n", // <br>
192 '_\\1_', // <i>
193 '_\\1_', // <em>
194 "\n\n", // <ul> and </ul>
195 "\n\n", // <ol> and </ol>
196 "\t* \\1\n", // <li> and </li>
197 "\n\t* ", // <li>
198 "\n-------------------------\n", // <hr>
199 "\n\n", // <table> and </table>
200 "\n", // <tr> and </tr>
201 "\t\t\\1\n", // <td> and </td>
202 ' ', // Non-breaking space
203 '"', // Double quotes
204 "'", // Single quotes
205 '>',
206 '<',
207 '&',
208 '(c)',
209 '(tm)',
210 '(R)',
211 '--',
212 '-',
213 '*',
214 '£',
215 'EUR', // Euro sign. € ?
216 '\\1', // Trailing spaces before newline or tab
217 ' ' // Runs of spaces, post-handling
221 * List of preg* regular expression patterns to search for
222 * and replace using callback function.
224 * @var array $callback_search
225 * @access public
227 var $callback_search = array(
228 '/<(h)[123456][^>]*>(.*?)<\/h[123456]>/i', // H1 - H3
229 '/<(b)[^>]*>(.*?)<\/b>/i', // <b>
230 '/<(strong)[^>]*>(.*?)<\/strong>/i', // <strong>
231 '/<(a) [^>]*href=("|\')([^"\']+)\2[^>]*>(.*?)<\/a>/i',
232 // <a href="">
233 '/<(th)[^>]*>(.*?)<\/th>/i', // <th> and </th>
234 '/<(img)[^>]*alt=\"([^>"]+)\"[^>]*>/i', // <img> with alt
238 * List of preg* regular expression patterns to search for in PRE body,
239 * used in conjunction with $pre_replace.
241 * @var array $pre_search
242 * @access public
243 * @see $pre_replace
245 var $pre_search = array(
246 "/\n/",
247 "/\t/",
248 '/ /',
249 '/<pre[^>]*>/',
250 '/<\/pre>/'
254 * List of pattern replacements corresponding to patterns searched for PRE body.
256 * @var array $pre_replace
257 * @access public
258 * @see $pre_search
260 var $pre_replace = array(
261 '<br>',
262 '&nbsp;&nbsp;&nbsp;&nbsp;',
263 '&nbsp;',
269 * Contains a list of HTML tags to allow in the resulting text.
271 * @var string $allowed_tags
272 * @access public
273 * @see set_allowed_tags()
275 var $allowed_tags = '';
278 * Contains the base URL that relative links should resolve to.
280 * @var string $url
281 * @access public
283 var $url;
286 * Indicates whether content in the $html variable has been converted yet.
288 * @var boolean $_converted
289 * @access private
290 * @see $html, $text
292 var $_converted = false;
295 * Contains URL addresses from links to be rendered in plain text.
297 * @var string $_link_list
298 * @access private
299 * @see _build_link_list()
301 var $_link_list = '';
304 * Number of valid links detected in the text, used for plain text
305 * display (rendered similar to footnotes).
307 * @var integer $_link_count
308 * @access private
309 * @see _build_link_list()
311 var $_link_count = 0;
314 * Boolean flag, true if a table of link URLs should be listed after the text.
316 * @var boolean $_do_links
317 * @access private
318 * @see html2text()
320 var $_do_links = true;
323 * Constructor.
325 * If the HTML source string (or file) is supplied, the class
326 * will instantiate with that source propagated, all that has
327 * to be done it to call get_text().
329 * @param string $source HTML content
330 * @param boolean $from_file Indicates $source is a file to pull content from
331 * @param boolean $do_links Indicate whether a table of link URLs is desired
332 * @param integer $width Maximum width of the formatted text, 0 for no limit
333 * @access public
334 * @return void
336 function html2text( $source = '', $from_file = false, $do_links = true, $width = 75 )
338 if ( !empty($source) ) {
339 $this->set_html($source, $from_file);
342 $this->set_base_url();
343 $this->_do_links = $do_links;
344 $this->width = $width;
348 * Loads source HTML into memory, either from $source string or a file.
350 * @param string $source HTML content
351 * @param boolean $from_file Indicates $source is a file to pull content from
352 * @access public
353 * @return void
355 function set_html( $source, $from_file = false )
357 if ( $from_file && file_exists($source) ) {
358 $this->html = file_get_contents($source);
360 else
361 $this->html = $source;
363 $this->_converted = false;
367 * Returns the text, converted from HTML.
369 * @access public
370 * @return string
372 function get_text()
374 if ( !$this->_converted ) {
375 $this->_convert();
378 return $this->text;
382 * Prints the text, converted from HTML.
384 * @access public
385 * @return void
387 function print_text()
389 print $this->get_text();
393 * Alias to print_text(), operates identically.
395 * @access public
396 * @return void
397 * @see print_text()
399 function p()
401 print $this->get_text();
405 * Sets the allowed HTML tags to pass through to the resulting text.
407 * Tags should be in the form "<p>", with no corresponding closing tag.
409 * @access public
410 * @return void
412 function set_allowed_tags( $allowed_tags = '' )
414 if ( !empty($allowed_tags) ) {
415 $this->allowed_tags = $allowed_tags;
420 * Sets a base URL to handle relative links.
422 * @access public
423 * @return void
425 function set_base_url( $url = '' )
427 if ( empty($url) ) {
428 if ( !empty($_SERVER['HTTP_HOST']) ) {
429 $this->url = 'http://' . $_SERVER['HTTP_HOST'];
430 } else {
431 $this->url = '';
433 } else {
434 // Strip any trailing slashes for consistency (relative
435 // URLs may already start with a slash like "/file.html")
436 if ( substr($url, -1) == '/' ) {
437 $url = substr($url, 0, -1);
439 $this->url = $url;
444 * Workhorse function that does actual conversion.
446 * First performs custom tag replacement specified by $search and
447 * $replace arrays. Then strips any remaining HTML tags, reduces whitespace
448 * and newlines to a readable format, and word wraps the text to
449 * $width characters.
451 * @access private
452 * @return void
454 function _convert()
456 // Variables used for building the link list
457 $this->_link_count = 0;
458 $this->_link_list = '';
460 $text = trim($this->html);
462 // Convert <PRE>
463 $this->_convert_pre($text);
465 // Run our defined search-and-replace
466 $text = preg_replace($this->search, $this->replace, $text);
467 $text = preg_replace_callback($this->callback_search, array('html2text', '_preg_callback'), $text);
469 // Replace known html entities
470 $text = html_entity_decode($text, ENT_COMPAT, 'UTF-8');
472 // Remove unknown/unhandled entities (this cannot be done in search-and-replace block)
473 $text = preg_replace('/&[^&;]+;/i', '', $text);
475 // Strip any other HTML tags
476 $text = strip_tags($text, $this->allowed_tags);
478 // Bring down number of empty lines to 2 max
479 $text = preg_replace("/\n\s+\n/", "\n\n", $text);
480 $text = preg_replace("/[\n]{3,}/", "\n\n", $text);
482 // Add link list
483 if ( !empty($this->_link_list) ) {
484 $text .= "\n\nLinks:\n------\n" . $this->_link_list;
487 // Wrap the text to a readable format
488 // for PHP versions >= 4.0.2. Default width is 75
489 // If width is 0 or less, don't wrap the text.
490 if ( $this->width > 0 ) {
491 $text = wordwrap($text, $this->width);
494 $this->text = $text;
496 $this->_converted = true;
500 * Helper function called by preg_replace() on link replacement.
502 * Maintains an internal list of links to be displayed at the end of the
503 * text, with numeric indices to the original point in the text they
504 * appeared. Also makes an effort at identifying and handling absolute
505 * and relative links.
507 * @param string $link URL of the link
508 * @param string $display Part of the text to associate number with
509 * @access private
510 * @return string
512 function _build_link_list( $link, $display )
514 if ( !$this->_do_links ) return $display;
516 if ( substr($link, 0, 7) == 'http://' || substr($link, 0, 8) == 'https://' ||
517 substr($link, 0, 7) == 'mailto:' ) {
518 $this->_link_count++;
519 $this->_link_list .= "[" . $this->_link_count . "] $link\n";
520 $additional = ' [' . $this->_link_count . ']';
521 } elseif ( substr($link, 0, 11) == 'javascript:' ) {
522 // Don't count the link; ignore it
523 $additional = '';
524 // what about href="#anchor" ?
525 } else {
526 $this->_link_count++;
527 $this->_link_list .= "[" . $this->_link_count . "] " . $this->url;
528 if ( substr($link, 0, 1) != '/' ) {
529 $this->_link_list .= '/';
531 $this->_link_list .= "$link\n";
532 $additional = ' [' . $this->_link_count . ']';
535 return $display . $additional;
539 * Helper function for PRE body conversion.
541 * @param string $text HTML content
542 * @access private
544 function _convert_pre(&$text)
546 while(preg_match('/<pre[^>]*>(.*)<\/pre>/ismU', $text, $matches)) {
547 $result = preg_replace($this->pre_search, $this->pre_replace, $matches[1]);
548 $text = preg_replace('/<pre[^>]*>.*<\/pre>/ismU', '<div><br>' . $result . '<br></div>', $text, 1);
553 * Callback function for preg_replace_callback use.
555 * @param array $matches PREG matches
556 * @return string
557 * @access private
559 function _preg_callback($matches)
561 switch($matches[1]) {
562 case 'b':
563 case 'strong':
564 return $this->_strtoupper($matches[2]);
565 case 'hr':
566 return $this->_strtoupper("\t\t". $matches[2] ."\n");
567 case 'h':
568 return $this->_strtoupper("\n\n". $matches[2] ."\n\n");
569 case 'a':
570 return $this->_build_link_list($matches[3], $matches[4]);
571 case 'img':
572 return '[' . $matches[2] . ']';
577 * Strtoupper multibyte wrapper function
579 * @param string $str
580 * @return string
581 * @access private
583 function _strtoupper($str)
585 $tl = textlib_get_instance();
586 return $tl->strtoupper($str);