PageRenderTime 760ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/application/libraries/Html2Text.php

http://github.com/ushahidi/Ushahidi_Web
PHP | 487 lines | 288 code | 20 blank | 179 comment | 15 complexity | 86b4a07607080d842b846ddaa23ef8b4 MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php defined('SYSPATH') or die('No direct script access.');
  2. /*************************************************************************
  3. * *
  4. * class.html2text.inc *
  5. * *
  6. *************************************************************************
  7. * *
  8. * Converts HTML to formatted plain text *
  9. * *
  10. * Copyright (c) 2005-2007 Jon Abernathy <jon@chuggnutt.com> *
  11. * All rights reserved. *
  12. * *
  13. * This script is free software; you can redistribute it and/or modify *
  14. * it under the terms of the GNU General Public License as published by *
  15. * the Free Software Foundation; either version 2 of the License, or *
  16. * (at your option) any later version. *
  17. * *
  18. * The GNU General Public License can be found at *
  19. * http://www.gnu.org/copyleft/gpl.html. *
  20. * *
  21. * This script is distributed in the hope that it will be useful, *
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of *
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
  24. * GNU General Public License for more details. *
  25. * *
  26. * Author(s): Jon Abernathy <jon@chuggnutt.com> *
  27. * *
  28. * Last modified: 08/08/07 *
  29. * *
  30. *************************************************************************/
  31. /**
  32. * Takes HTML and converts it to formatted, plain text.
  33. *
  34. * Thanks to Alexander Krug (http://www.krugar.de/) to pointing out and
  35. * correcting an error in the regexp search array. Fixed 7/30/03.
  36. *
  37. * Updated set_html() function's file reading mechanism, 9/25/03.
  38. *
  39. * Thanks to Joss Sanglier (http://www.dancingbear.co.uk/) for adding
  40. * several more HTML entity codes to the $search and $replace arrays.
  41. * Updated 11/7/03.
  42. *
  43. * Thanks to Darius Kasperavicius (http://www.dar.dar.lt/) for
  44. * suggesting the addition of $allowed_tags and its supporting function
  45. * (which I slightly modified). Updated 3/12/04.
  46. *
  47. * Thanks to Justin Dearing for pointing out that a replacement for the
  48. * <TH> tag was missing, and suggesting an appropriate fix.
  49. * Updated 8/25/04.
  50. *
  51. * Thanks to Mathieu Collas (http://www.myefarm.com/) for finding a
  52. * display/formatting bug in the _build_link_list() function: email
  53. * readers would show the left bracket and number ("[1") as part of the
  54. * rendered email address.
  55. * Updated 12/16/04.
  56. *
  57. * Thanks to Wojciech Bajon (http://histeria.pl/) for submitting code
  58. * to handle relative links, which I hadn't considered. I modified his
  59. * code a bit to handle normal HTTP links and MAILTO links. Also for
  60. * suggesting three additional HTML entity codes to search for.
  61. * Updated 03/02/05.
  62. *
  63. * Thanks to Jacob Chandler for pointing out another link condition
  64. * for the _build_link_list() function: "https".
  65. * Updated 04/06/05.
  66. *
  67. * Thanks to Marc Bertrand (http://www.dresdensky.com/) for
  68. * suggesting a revision to the word wrapping functionality; if you
  69. * specify a $width of 0 or less, word wrapping will be ignored.
  70. * Updated 11/02/06.
  71. *
  72. * *** Big housecleaning updates below:
  73. *
  74. * Thanks to Colin Brown (http://www.sparkdriver.co.uk/) for
  75. * suggesting the fix to handle </li> and blank lines (whitespace).
  76. * Christian Basedau (http://www.movetheweb.de/) also suggested the
  77. * blank lines fix.
  78. *
  79. * Special thanks to Marcus Bointon (http://www.synchromedia.co.uk/),
  80. * Christian Basedau, Norbert Laposa (http://ln5.co.uk/),
  81. * Bas van de Weijer, and Marijn van Butselaar
  82. * for pointing out my glaring error in the <th> handling. Marcus also
  83. * supplied a host of fixes.
  84. *
  85. * Thanks to Jeffrey Silverman (http://www.newtnotes.com/) for pointing
  86. * out that extra spaces should be compressed--a problem addressed with
  87. * Marcus Bointon's fixes but that I had not yet incorporated.
  88. *
  89. * Thanks to Daniel Schledermann (http://www.typoconsult.dk/) for
  90. * suggesting a valuable fix with <a> tag handling.
  91. *
  92. * Thanks to Wojciech Bajon (again!) for suggesting fixes and additions,
  93. * including the <a> tag handling that Daniel Schledermann pointed
  94. * out but that I had not yet incorporated. I haven't (yet)
  95. * incorporated all of Wojciech's changes, though I may at some
  96. * future time.
  97. *
  98. * *** End of the housecleaning updates. Updated 08/08/07.
  99. *
  100. * @author Jon Abernathy <jon@chuggnutt.com>
  101. * @version 1.0.0
  102. * @since PHP 4.0.2
  103. */
  104. class Html2Text
  105. {
  106. /**
  107. * Contains the HTML content to convert.
  108. *
  109. * @var string $html
  110. * @access public
  111. */
  112. var $html;
  113. /**
  114. * Contains the converted, formatted text.
  115. *
  116. * @var string $text
  117. * @access public
  118. */
  119. var $text;
  120. /**
  121. * Maximum width of the formatted text, in columns.
  122. *
  123. * Set this value to 0 (or less) to ignore word wrapping
  124. * and not constrain text to a fixed-width column.
  125. *
  126. * @var integer $width
  127. * @access public
  128. */
  129. var $width = 70;
  130. /**
  131. * List of preg* regular expression patterns to search for,
  132. * used in conjunction with $replace.
  133. *
  134. * @var array $search
  135. * @access public
  136. * @see $replace
  137. */
  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. '/<h[123][^>]*>(.*?)<\/h[123]>/ie', // H1 - H3
  146. '/<h[456][^>]*>(.*?)<\/h[456]>/ie', // H4 - H6
  147. '/<p[^>]*>/i', // <P>
  148. '/<br[^>]*>/i', // <br>
  149. '/<b[^>]*>(.*?)<\/b>/ie', // <b>
  150. '/<strong[^>]*>(.*?)<\/strong>/ie', // <strong>
  151. '/<i[^>]*>(.*?)<\/i>/i', // <i>
  152. '/<em[^>]*>(.*?)<\/em>/i', // <em>
  153. '/(<ul[^>]*>|<\/ul>)/i', // <ul> and </ul>
  154. '/(<ol[^>]*>|<\/ol>)/i', // <ol> and </ol>
  155. '/<li[^>]*>(.*?)<\/li>/i', // <li> and </li>
  156. '/<li[^>]*>/i', // <li>
  157. '/<a [^>]*href="([^"]+)"[^>]*>(.*?)<\/a>/ie',
  158. // <a href="">
  159. '/<hr[^>]*>/i', // <hr>
  160. '/(<table[^>]*>|<\/table>)/i', // <table> and </table>
  161. '/(<tr[^>]*>|<\/tr>)/i', // <tr> and </tr>
  162. '/<td[^>]*>(.*?)<\/td>/i', // <td> and </td>
  163. '/<th[^>]*>(.*?)<\/th>/ie', // <th> and </th>
  164. '/&(nbsp|#160);/i', // Non-breaking space
  165. '/&(quot|rdquo|ldquo|#8220|#8221|#147|#148);/i',
  166. // Double quotes
  167. '/&(apos|rsquo|lsquo|#8216|#8217);/i', // Single quotes
  168. '/&gt;/i', // Greater-than
  169. '/&lt;/i', // Less-than
  170. '/&(amp|#38);/i', // Ampersand
  171. '/&(copy|#169);/i', // Copyright
  172. '/&(trade|#8482|#153);/i', // Trademark
  173. '/&(reg|#174);/i', // Registered
  174. '/&(mdash|#151|#8212);/i', // mdash
  175. '/&(ndash|minus|#8211|#8722);/i', // ndash
  176. '/&(bull|#149|#8226);/i', // Bullet
  177. '/&(pound|#163);/i', // Pound sign
  178. '/&(euro|#8364);/i', // Euro sign
  179. '/&[^&;]+;/i', // Unknown/unhandled entities
  180. '/[ ]{2,}/' // Runs of spaces, post-handling
  181. );
  182. /**
  183. * List of pattern replacements corresponding to patterns searched.
  184. *
  185. * @var array $replace
  186. * @access public
  187. * @see $search
  188. */
  189. var $replace = array(
  190. '', // Non-legal carriage return
  191. ' ', // Newlines and tabs
  192. ' ', // Runs of spaces, pre-handling
  193. '', // <script>s -- which strip_tags supposedly has problems with
  194. '', // <style>s -- which strip_tags supposedly has problems with
  195. //'', // Comments -- which strip_tags might have problem a with
  196. "strtoupper(\"\n\n\\1\n\n\")", // H1 - H3
  197. "ucwords(\"\n\n\\1\n\n\")", // H4 - H6
  198. "\n\n\t", // <P>
  199. "\n", // <br>
  200. 'strtoupper("\\1")', // <b>
  201. 'strtoupper("\\1")', // <strong>
  202. '_\\1_', // <i>
  203. '_\\1_', // <em>
  204. "\n\n", // <ul> and </ul>
  205. "\n\n", // <ol> and </ol>
  206. "\t* \\1\n", // <li> and </li>
  207. "\n\t* ", // <li>
  208. '$this->_build_link_list("\\1", "\\2")',
  209. // <a href="">
  210. "\n-------------------------\n", // <hr>
  211. "\n\n", // <table> and </table>
  212. "\n", // <tr> and </tr>
  213. "\t\t\\1\n", // <td> and </td>
  214. "strtoupper(\"\t\t\\1\n\")", // <th> and </th>
  215. ' ', // Non-breaking space
  216. '"', // Double quotes
  217. "'", // Single quotes
  218. '>',
  219. '<',
  220. '&',
  221. '(c)',
  222. '(tm)',
  223. '(R)',
  224. '--',
  225. '-',
  226. '*',
  227. '£',
  228. 'EUR', // Euro sign. Ä ?
  229. '', // Unknown/unhandled entities
  230. ' ' // Runs of spaces, post-handling
  231. );
  232. /**
  233. * Contains a list of HTML tags to allow in the resulting text.
  234. *
  235. * @var string $allowed_tags
  236. * @access public
  237. * @see set_allowed_tags()
  238. */
  239. var $allowed_tags = '';
  240. /**
  241. * Contains the base URL that relative links should resolve to.
  242. *
  243. * @var string $url
  244. * @access public
  245. */
  246. var $url;
  247. /**
  248. * Indicates whether content in the $html variable has been converted yet.
  249. *
  250. * @var boolean $_converted
  251. * @access private
  252. * @see $html, $text
  253. */
  254. var $_converted = false;
  255. /**
  256. * Contains URL addresses from links to be rendered in plain text.
  257. *
  258. * @var string $_link_list
  259. * @access private
  260. * @see _build_link_list()
  261. */
  262. var $_link_list = '';
  263. /**
  264. * Number of valid links detected in the text, used for plain text
  265. * display (rendered similar to footnotes).
  266. *
  267. * @var integer $_link_count
  268. * @access private
  269. * @see _build_link_list()
  270. */
  271. var $_link_count = 0;
  272. /**
  273. * Constructor.
  274. *
  275. * If the HTML source string (or file) is supplied, the class
  276. * will instantiate with that source propagated, all that has
  277. * to be done it to call get_text().
  278. *
  279. * @param string $source HTML content
  280. * @param boolean $from_file Indicates $source is a file to pull content from
  281. * @access public
  282. * @return void
  283. */
  284. function html2text( $source = '', $from_file = false )
  285. {
  286. if ( !empty($source) ) {
  287. $this->set_html($source, $from_file);
  288. }
  289. $this->set_base_url();
  290. }
  291. /**
  292. * Loads source HTML into memory, either from $source string or a file.
  293. *
  294. * @param string $source HTML content
  295. * @param boolean $from_file Indicates $source is a file to pull content from
  296. * @access public
  297. * @return void
  298. */
  299. function set_html( $source, $from_file = false )
  300. {
  301. $this->html = $source;
  302. if ( $from_file && file_exists($source) ) {
  303. $fp = fopen($source, 'r');
  304. $this->html = fread($fp, filesize($source));
  305. fclose($fp);
  306. }
  307. $this->_converted = false;
  308. }
  309. /**
  310. * Returns the text, converted from HTML.
  311. *
  312. * @access public
  313. * @return string
  314. */
  315. function get_text()
  316. {
  317. if ( !$this->_converted ) {
  318. $this->_convert();
  319. }
  320. return $this->text;
  321. }
  322. /**
  323. * Prints the text, converted from HTML.
  324. *
  325. * @access public
  326. * @return void
  327. */
  328. function print_text()
  329. {
  330. print $this->get_text();
  331. }
  332. /**
  333. * Alias to print_text(), operates identically.
  334. *
  335. * @access public
  336. * @return void
  337. * @see print_text()
  338. */
  339. function p()
  340. {
  341. print $this->get_text();
  342. }
  343. /**
  344. * Sets the allowed HTML tags to pass through to the resulting text.
  345. *
  346. * Tags should be in the form "<p>", with no corresponding closing tag.
  347. *
  348. * @access public
  349. * @return void
  350. */
  351. function set_allowed_tags( $allowed_tags = '' )
  352. {
  353. if ( !empty($allowed_tags) ) {
  354. $this->allowed_tags = $allowed_tags;
  355. }
  356. }
  357. /**
  358. * Sets a base URL to handle relative links.
  359. *
  360. * @access public
  361. * @return void
  362. */
  363. function set_base_url( $url = '' )
  364. {
  365. if ( empty($url) ) {
  366. if ( !empty($_SERVER['HTTP_HOST']) ) {
  367. $this->url = Kohana::config('core.site_protocol').'://' . $_SERVER['HTTP_HOST'];
  368. } else {
  369. $this->url = '';
  370. }
  371. } else {
  372. // Strip any trailing slashes for consistency (relative
  373. // URLs may already start with a slash like "/file.html")
  374. if ( substr($url, -1) == '/' ) {
  375. $url = substr($url, 0, -1);
  376. }
  377. $this->url = $url;
  378. }
  379. }
  380. /**
  381. * Workhorse function that does actual conversion.
  382. *
  383. * First performs custom tag replacement specified by $search and
  384. * $replace arrays. Then strips any remaining HTML tags, reduces whitespace
  385. * and newlines to a readable format, and word wraps the text to
  386. * $width characters.
  387. *
  388. * @access private
  389. * @return void
  390. */
  391. function _convert()
  392. {
  393. // Variables used for building the link list
  394. $this->_link_count = 0;
  395. $this->_link_list = '';
  396. $text = trim(stripslashes($this->html));
  397. // Run our defined search-and-replace
  398. $text = preg_replace($this->search, $this->replace, $text);
  399. // Strip any other HTML tags
  400. $text = strip_tags($text, $this->allowed_tags);
  401. // Bring down number of empty lines to 2 max
  402. $text = preg_replace("/\n\s+\n/", "\n\n", $text);
  403. $text = preg_replace("/[\n]{3,}/", "\n\n", $text);
  404. // Add link list
  405. if ( !empty($this->_link_list) ) {
  406. $text .= "\n\nLinks:\n------\n" . $this->_link_list;
  407. }
  408. // Wrap the text to a readable format
  409. // for PHP versions >= 4.0.2. Default width is 75
  410. // If width is 0 or less, don't wrap the text.
  411. if ( $this->width > 0 ) {
  412. $text = wordwrap($text, $this->width);
  413. }
  414. $this->text = $text;
  415. $this->_converted = true;
  416. }
  417. /**
  418. * Helper function called by preg_replace() on link replacement.
  419. *
  420. * Maintains an internal list of links to be displayed at the end of the
  421. * text, with numeric indices to the original point in the text they
  422. * appeared. Also makes an effort at identifying and handling absolute
  423. * and relative links.
  424. *
  425. * @param string $link URL of the link
  426. * @param string $display Part of the text to associate number with
  427. * @access private
  428. * @return string
  429. */
  430. function _build_link_list( $link, $display )
  431. {
  432. if ( substr($link, 0, 7) == 'http://' || substr($link, 0, 8) == 'https://' ||
  433. substr($link, 0, 7) == 'mailto:' ) {
  434. $this->_link_count++;
  435. $this->_link_list .= "[" . $this->_link_count . "] $link\n";
  436. $additional = ' [' . $this->_link_count . ']';
  437. } elseif ( substr($link, 0, 11) == 'javascript:' ) {
  438. // Don't count the link; ignore it
  439. $additional = '';
  440. // what about href="#anchor" ?
  441. } else {
  442. $this->_link_count++;
  443. $this->_link_list .= "[" . $this->_link_count . "] " . $this->url;
  444. if ( substr($link, 0, 1) != '/' ) {
  445. $this->_link_list .= '/';
  446. }
  447. $this->_link_list .= "$link\n";
  448. $additional = ' [' . $this->_link_count . ']';
  449. }
  450. return $display . $additional;
  451. }
  452. }