Merge branch 'MDL-26365' of git://github.com/timhunt/moodle
[moodle.git] / lib / html2text.php
blob8d143bfb297e9ed3da225a727104692617683e26
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 '/[ ]{2,}/' // Runs of spaces, post-handling
176 * List of pattern replacements corresponding to patterns searched.
178 * @var array $replace
179 * @access public
180 * @see $search
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
189 "\n\n", // <P>
190 "\n", // <br>
191 '_\\1_', // <i>
192 '_\\1_', // <em>
193 "\n\n", // <ul> and </ul>
194 "\n\n", // <ol> and </ol>
195 "\t* \\1\n", // <li> and </li>
196 "\n\t* ", // <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
204 '>',
205 '<',
206 '&',
207 '(c)',
208 '(tm)',
209 '(R)',
210 '--',
211 '-',
212 '*',
213 '£',
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
223 * @access public
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',
230 // <a href="">
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
240 * @access public
241 * @see $pre_replace
243 var $pre_search = array(
244 "/\n/",
245 "/\t/",
246 '/ /',
247 '/<pre[^>]*>/',
248 '/<\/pre>/'
252 * List of pattern replacements corresponding to patterns searched for PRE body.
254 * @var array $pre_replace
255 * @access public
256 * @see $pre_search
258 var $pre_replace = array(
259 '<br>',
260 '&nbsp;&nbsp;&nbsp;&nbsp;',
261 '&nbsp;',
267 * Contains a list of HTML tags to allow in the resulting text.
269 * @var string $allowed_tags
270 * @access public
271 * @see set_allowed_tags()
273 var $allowed_tags = '';
276 * Contains the base URL that relative links should resolve to.
278 * @var string $url
279 * @access public
281 var $url;
284 * Indicates whether content in the $html variable has been converted yet.
286 * @var boolean $_converted
287 * @access private
288 * @see $html, $text
290 var $_converted = false;
293 * Contains URL addresses from links to be rendered in plain text.
295 * @var string $_link_list
296 * @access private
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
306 * @access private
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
315 * @access private
316 * @see html2text()
318 var $_do_links = true;
321 * Constructor.
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
331 * @access public
332 * @return void
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
350 * @access public
351 * @return void
353 function set_html( $source, $from_file = false )
355 if ( $from_file && file_exists($source) ) {
356 $this->html = file_get_contents($source);
358 else
359 $this->html = $source;
361 $this->_converted = false;
365 * Returns the text, converted from HTML.
367 * @access public
368 * @return string
370 function get_text()
372 if ( !$this->_converted ) {
373 $this->_convert();
376 return $this->text;
380 * Prints the text, converted from HTML.
382 * @access public
383 * @return void
385 function print_text()
387 print $this->get_text();
391 * Alias to print_text(), operates identically.
393 * @access public
394 * @return void
395 * @see print_text()
397 function p()
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.
407 * @access public
408 * @return void
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.
420 * @access public
421 * @return void
423 function set_base_url( $url = '' )
425 if ( empty($url) ) {
426 if ( !empty($_SERVER['HTTP_HOST']) ) {
427 $this->url = 'http://' . $_SERVER['HTTP_HOST'];
428 } else {
429 $this->url = '';
431 } else {
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);
437 $this->url = $url;
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
447 * $width characters.
449 * @access private
450 * @return void
452 function _convert()
454 // Variables used for building the link list
455 $this->_link_count = 0;
456 $this->_link_list = '';
458 $text = trim($this->html);
460 // Convert <PRE>
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);
480 // Add link list
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);
492 $this->text = $text;
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
507 * @access private
508 * @return string
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
521 $additional = '';
522 // what about href="#anchor" ?
523 } else {
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
540 * @access private
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
554 * @return string
555 * @access private
557 function _preg_callback($matches)
559 switch($matches[1]) {
560 case 'b':
561 case 'strong':
562 return $this->_strtoupper($matches[2]);
563 case 'hr':
564 return $this->_strtoupper("\t\t". $matches[2] ."\n");
565 case 'h':
566 return $this->_strtoupper("\n\n". $matches[2] ."\n\n");
567 case 'a':
568 return $this->_build_link_list($matches[3], $matches[4]);
569 case 'img':
570 return '[' . $matches[2] . ']';
575 * Strtoupper multibyte wrapper function
577 * @param string $str
578 * @return string
579 * @access private
581 function _strtoupper($str)
583 $tl = textlib_get_instance();
584 return $tl->strtoupper($str);