]> git.donarmstrong.com Git - roundcube.git/blob - program/lib/html2text.inc
82a254e562fa9a5f36e7681f4fa83c2d957641a9
[roundcube.git] / program / lib / html2text.inc
1 <?php
2
3 /*************************************************************************
4 *                                                                       *
5 * class.html2text.inc                                                   *
6 *                                                                       *
7 *************************************************************************
8 *                                                                       *
9 * Converts HTML to formatted plain text                                 *
10 *                                                                       *
11 * Copyright (c) 2005 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: 04/06/05                                               *
30 * Modified: 2004/05/19 (tbr)                                            *
31 *                                                                       *
32 *************************************************************************/
33
34
35 /**
36 *  Takes HTML and converts it to formatted, plain text.
37 *
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.
40 *
41 *  Updated set_html() function's file reading mechanism, 9/25/03.
42 *
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.
46 *
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.
50 *
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.
54 *
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.
60 *
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.
66 *
67 *  Thanks to Jacob Chandler for pointing out another link condition
68 *  for the _build_link_list() function: "https".
69 *  Updated 04/06/05.
70 *
71 *  @author Jon Abernathy <jon@chuggnutt.com>
72 *  @version 0.6.1
73 *  @since PHP 4.0.2
74 */
75 class html2text
76 {
77
78     /**
79      *  Contains the HTML content to convert.
80      *
81      *  @var string $html
82      *  @access public
83      */
84     var $html;
85
86     /**
87      *  Contains the converted, formatted text.
88      *
89      *  @var string $text
90      *  @access public
91      */
92     var $text;
93
94     /**
95      *  Maximum width of the formatted text, in columns.
96      *
97      *  @var integer $width
98      *  @access public
99      */
100     var $width = 70;
101
102     /**
103      *  List of preg* regular expression patterns to search for,
104      *  used in conjunction with $replace.
105      *
106      *  @var array $search
107      *  @access public
108      *  @see $replace
109      */
110     var $search = array(
111         "/\r/",                                  // Non-legal carriage return
112         "/[\n\t]+/",                             // Newlines and tabs
113         '/<script[^>]*>.*?<\/script>/i',         // <script>s -- which strip_tags supposedly has problems with
114         //'/<!-- .* -->/',                         // Comments -- which strip_tags might have problem a with
115         '/<a href="([^"]+)"[^>]*>(.+?)<\/a>/ie', // <a href="">
116         '/<h[123][^>]*>(.+?)<\/h[123]>/ie',      // H1 - H3
117         '/<h[456][^>]*>(.+?)<\/h[456]>/ie',      // H4 - H6
118         '/<p[^>]*>/i',                           // <P>
119         '/<br[^>]*>/i',                          // <br>
120         '/<b[^>]*>(.+?)<\/b>/ie',                // <b>
121         '/<i[^>]*>(.+?)<\/i>/i',                 // <i>
122         '/(<ul[^>]*>|<\/ul>)/i',                 // <ul> and </ul>
123         '/(<ol[^>]*>|<\/ol>)/i',                 // <ol> and </ol>
124         '/<li[^>]*>/i',                          // <li>
125         '/<hr[^>]*>/i',                          // <hr>
126         '/(<table[^>]*>|<\/table>)/i',           // <table> and </table>
127         '/(<tr[^>]*>|<\/tr>)/i',                 // <tr> and </tr>
128         '/<td[^>]*>(.+?)<\/td>/i',               // <td> and </td>
129         '/<th[^>]*>(.+?)<\/th>/i',               // <th> and </th>
130         '/&nbsp;/i',
131         '/&quot;/i',
132         '/&gt;/i',
133         '/&lt;/i',
134         '/&amp;/i',
135         '/&copy;/i',
136         '/&trade;/i',
137         '/&#8220;/',
138         '/&#8221;/',
139         '/&#8211;/',
140         '/&#8217;/',
141         '/&#38;/',
142         '/&#169;/',
143         '/&#8482;/',
144         '/&#151;/',
145         '/&#147;/',
146         '/&#148;/',
147         '/&#149;/',
148         '/&reg;/i',
149         '/&bull;/i',
150         '/&[&;]+;/i'
151     );
152
153     /**
154      *  List of pattern replacements corresponding to patterns searched.
155      *
156      *  @var array $replace
157      *  @access public
158      *  @see $search
159      */
160     var $replace = array(
161         '',                                     // Non-legal carriage return
162         ' ',                                    // Newlines and tabs
163         '',                                     // <script>s -- which strip_tags supposedly has problems with
164         //'',                                     // Comments -- which strip_tags might have problem a with
165         '$this->_build_link_list("\\1", "\\2")', // <a href="">
166         "strtoupper(\"\n\n\\1\n\n\")",          // H1 - H3
167         "ucwords(\"\n\n\\1\n\n\")",             // H4 - H6
168         "\n\n\t",                               // <P>
169         "\n",                                   // <br>
170         'strtoupper("\\1")',                    // <b>
171         '_\\1_',                                // <i>
172         "\n\n",                                 // <ul> and </ul>
173         "\n\n",                                 // <ol> and </ol>
174         "\t*",                                  // <li>
175         "\n-------------------------\n",        // <hr>
176         "\n\n",                                 // <table> and </table>
177         "\n",                                   // <tr> and </tr>
178         "\t\t\\1\n",                            // <td> and </td>
179         "strtoupper(\"\t\t\\1\n\")",            // <th> and </th>
180         ' ',
181         '"',
182         '>',
183         '<',
184         '&',
185         '(c)',
186         '(tm)',
187         '"',
188         '"',
189         '-',
190         "'",
191         '&',
192         '(c)',
193         '(tm)',
194         '--',
195         '"',
196         '"',
197         '*',
198         '(R)',
199         '*',
200         ''
201     );
202
203     /**
204      *  Contains a list of HTML tags to allow in the resulting text.
205      *
206      *  @var string $allowed_tags
207      *  @access public
208      *  @see set_allowed_tags()
209      */
210     var $allowed_tags = '';
211
212     /**
213      *  Contains the base URL that relative links should resolve to.
214      *
215      *  @var string $url
216      *  @access public
217      */
218     var $url;
219
220     /**
221      *  Indicates whether content in the $html variable has been converted yet.
222      *
223      *  @var boolean $converted
224      *  @access private
225      *  @see $html, $text
226      */
227     var $_converted = false;
228
229     /**
230      *  Contains URL addresses from links to be rendered in plain text.
231      *
232      *  @var string $link_list
233      *  @access private
234      *  @see _build_link_list()
235      */
236     var $_link_list = array();
237
238     /**
239      *  Constructor.
240      *
241      *  If the HTML source string (or file) is supplied, the class
242      *  will instantiate with that source propagated, all that has
243      *  to be done it to call get_text().
244      *
245      *  @param string $source HTML content
246      *  @param boolean $from_file Indicates $source is a file to pull content from
247      *  @access public
248      *  @return void
249      */
250     function html2text( $source = '', $from_file = false )
251     {
252         if ( !empty($source) ) {
253             $this->set_html($source, $from_file);
254         }
255         $this->set_base_url();
256     }
257
258     /**
259      *  Loads source HTML into memory, either from $source string or a file.
260      *
261      *  @param string $source HTML content
262      *  @param boolean $from_file Indicates $source is a file to pull content from
263      *  @access public
264      *  @return void
265      */
266     function set_html( $source, $from_file = false )
267     {
268         $this->html = $source;
269
270         if ( $from_file && file_exists($source) ) {
271             $fp = fopen($source, 'r');
272             $this->html = fread($fp, filesize($source));
273             fclose($fp);
274         }
275
276         $this->_converted = false;
277     }
278
279     /**
280      *  Returns the text, converted from HTML.
281      *
282      *  @access public
283      *  @return string
284      */
285     function get_text()
286     {
287         if ( !$this->_converted ) {
288             $this->_convert();
289         }
290
291         return $this->text;
292     }
293
294     /**
295      *  Prints the text, converted from HTML.
296      *
297      *  @access public
298      *  @return void
299      */
300     function print_text()
301     {
302         print $this->get_text();
303     }
304
305     /**
306      *  Alias to print_text(), operates identically.
307      *
308      *  @access public
309      *  @return void
310      *  @see print_text()
311      */
312     function p()
313     {
314         print $this->get_text();
315     }
316
317     /**
318      *  Sets the allowed HTML tags to pass through to the resulting text.
319      *
320      *  Tags should be in the form "<p>", with no corresponding closing tag.
321      *
322      *  @access public
323      *  @return void
324      */
325     function set_allowed_tags( $allowed_tags = '' )
326     {
327         if ( !empty($allowed_tags) ) {
328             $this->allowed_tags = $allowed_tags;
329         }
330     }
331
332     /**
333      *  Sets a base URL to handle relative links.
334      *
335      *  @access public
336      *  @return void
337      */
338     function set_base_url( $url = '' )
339     {
340         if ( empty($url) ) {
341             $this->url = 'http://' . $_SERVER['HTTP_HOST'];
342         } else {
343             // Strip any trailing slashes for consistency (relative
344             // URLs may already start with a slash like "/file.html")
345             if ( substr($url, -1) == '/' ) {
346                 $url = substr($url, 0, -1);
347             }
348             $this->url = $url;
349         }
350     }
351
352     /**
353      *  Workhorse function that does actual conversion.
354      *
355      *  First performs custom tag replacement specified by $search and
356      *  $replace arrays. Then strips any remaining HTML tags, reduces whitespace
357      *  and newlines to a readable format, and word wraps the text to
358      *  $width characters.
359      *
360      *  @access private
361      *  @return void
362      */
363     function _convert()
364     {
365         // Variables used for building the link list
366         //$link_count = 1;
367         //$this->_link_list = '';
368
369         $text = trim(stripslashes($this->html));
370
371         // Run our defined search-and-replace
372         $text = preg_replace($this->search, $this->replace, $text);
373
374         // Strip any other HTML tags
375         $text = strip_tags($text, $this->allowed_tags);
376
377         // Bring down number of empty lines to 2 max
378         $text = preg_replace("/\n\s+\n/", "\n", $text);
379         $text = preg_replace("/[\n]{3,}/", "\n\n", $text);
380
381         // Add link list
382         if ( sizeof($this->_link_list) ) {
383             $text .= "\n\nLinks:\n------\n";
384             foreach ($this->_link_list as $id => $link) {
385                 $text .= '[' . ($id+1) . '] ' . $link . "\n";
386             }
387         }
388
389         // Wrap the text to a readable format
390         // for PHP versions >= 4.0.2. Default width is 75
391         $text = wordwrap($text, $this->width);
392
393         $this->text = $text;
394
395         $this->_converted = true;
396     }
397
398     /**
399      *  Helper function called by preg_replace() on link replacement.
400      *
401      *  Maintains an internal list of links to be displayed at the end of the
402      *  text, with numeric indices to the original point in the text they
403      *  appeared. Also makes an effort at identifying and handling absolute
404      *  and relative links.
405      *
406      *  @param integer $link_count Counter tracking current link number
407      *  @param string $link URL of the link
408      *  @param string $display Part of the text to associate number with
409      *  @access private
410      *  @return string
411     */
412     function _build_link_list($link, $display)
413       {
414       $link_lc = strtolower($link);
415       
416       if (substr($link_lc, 0, 7) == 'http://' || substr($link_lc, 0, 8) == 'https://' || substr($link_lc, 0, 7) == 'mailto:')
417         {
418         $url = $link;
419         }
420       else
421         {
422         $url = $this->url;
423         if ($link{0} != '/') {
424              $url .= '/';
425             }
426         $url .= $link;
427         }
428
429       $index = array_search($url, $this->_link_list);
430       if ($index===FALSE)
431         {
432         $index = sizeof($this->_link_list);
433         $this->_link_list[$index] = $url;
434         }
435               
436       return $display . ' [' . ($index+1) . ']';
437       }
438 }
439
440 ?>