]> git.mxchange.org Git - friendica.git/blob - library/html-to-markdown/HTML_To_Markdown.php
1cc86505b6c411cf4fe25211422456dc84d177e6
[friendica.git] / library / html-to-markdown / HTML_To_Markdown.php
1 <?php
2 /**
3  * Class HTML_To_Markdown
4  *
5  * A helper class to convert HTML to Markdown.
6  *
7  * @version 2.1.2
8  * @author Nick Cernis <nick@cern.is>
9  * @link https://github.com/nickcernis/html2markdown/ Latest version on GitHub.
10  * @link http://twitter.com/nickcernis Nick on twitter.
11  * @license http://www.opensource.org/licenses/mit-license.php MIT
12  */
13 class HTML_To_Markdown
14 {
15     /**
16      * @var DOMDocument The root of the document tree that holds our HTML.
17      */
18     private $document;
19
20     /**
21      * @var string|boolean The Markdown version of the original HTML, or false if conversion failed
22      */
23     private $output;
24
25     /**
26      * @var array Class-wide options users can override.
27      */
28     private $options = array(
29         'header_style'    => 'setext', // Set to "atx" to output H1 and H2 headers as # Header1 and ## Header2
30         'suppress_errors' => true, // Set to false to show warnings when loading malformed HTML
31         'strip_tags'      => false, // Set to true to strip tags that don't have markdown equivalents. N.B. Strips tags, not their content. Useful to clean MS Word HTML output.
32         'bold_style'      => '**', // Set to '__' if you prefer the underlined style
33         'italic_style'    => '*', // Set to '_' if you prefer the underlined style
34         'remove_nodes'    => '', // space-separated list of dom nodes that should be removed. example: "meta style script"
35     );
36
37
38     /**
39      * Constructor
40      *
41      * Set up a new DOMDocument from the supplied HTML, convert it to Markdown, and store it in $this->$output.
42      *
43      * @param string $html The HTML to convert to Markdown.
44      * @param array $overrides [optional] List of style and error display overrides.
45      */
46     public function __construct($html = null, $overrides = null)
47     {
48         if ($overrides)
49             $this->options = array_merge($this->options, $overrides);
50
51         if ($html)
52             $this->convert($html);
53     }
54
55
56     /**
57      * Setter for conversion options
58      *
59      * @param $name
60      * @param $value
61      */
62     public function set_option($name, $value)
63     {
64         $this->options[$name] = $value;
65     }
66
67
68     /**
69      * Convert
70      *
71      * Loads HTML and passes to get_markdown()
72      *
73      * @param $html
74      * @return string The Markdown version of the html
75      */
76     public function convert($html)
77     {
78         $html = preg_replace('~>\s+<~', '><', $html); // Strip white space between tags to prevent creation of empty #text nodes
79
80         $this->document = new DOMDocument();
81
82         if ($this->options['suppress_errors'])
83             libxml_use_internal_errors(true); // Suppress conversion errors (from http://bit.ly/pCCRSX )
84
85         $this->document->loadHTML('<?xml encoding="UTF-8">' . $html); // Hack to load utf-8 HTML (from http://bit.ly/pVDyCt )
86         $this->document->encoding = 'UTF-8';
87
88         if ($this->options['suppress_errors'])
89             libxml_clear_errors();
90
91         return $this->get_markdown($html);
92     }
93
94
95     /**
96      * Is Child Of?
97      *
98      * Is the node a child of the given parent tag?
99      *
100      * @param $parent_name string The name of the parent node to search for (e.g. 'code')
101      * @param $node
102      * @return bool
103      */
104     private static function is_child_of($parent_name, $node)
105     {
106         for ($p = $node->parentNode; $p != false; $p = $p->parentNode) {
107             if (is_null($p))
108                 return false;
109
110             if ($p->nodeName == $parent_name)
111                 return true;
112         }
113         return false;
114     }
115
116
117     /**
118      * Convert Children
119      *
120      * Recursive function to drill into the DOM and convert each node into Markdown from the inside out.
121      *
122      * Finds children of each node and convert those to #text nodes containing their Markdown equivalent,
123      * starting with the innermost element and working up to the outermost element.
124      *
125      * @param $node
126      */
127     private function convert_children($node)
128     {
129         // Don't convert HTML code inside <code> and <pre> blocks to Markdown - that should stay as HTML
130         if (self::is_child_of('pre', $node) || self::is_child_of('code', $node))
131             return;
132
133         // If the node has children, convert those to Markdown first
134         if ($node->hasChildNodes()) {
135             $length = $node->childNodes->length;
136
137             for ($i = 0; $i < $length; $i++) {
138                 $child = $node->childNodes->item($i);
139                 $this->convert_children($child);
140             }
141         }
142
143         // Now that child nodes have been converted, convert the original node
144         $markdown = $this->convert_to_markdown($node);
145
146         // Create a DOM text node containing the Markdown equivalent of the original node
147         $markdown_node = $this->document->createTextNode($markdown);
148
149         // Replace the old $node e.g. "<h3>Title</h3>" with the new $markdown_node e.g. "### Title"
150         $node->parentNode->replaceChild($markdown_node, $node);
151     }
152
153
154     /**
155      * Get Markdown
156      *
157      * Sends the body node to convert_children() to change inner nodes to Markdown #text nodes, then saves and
158      * returns the resulting converted document as a string in Markdown format.
159      *
160      * @return string|boolean The converted HTML as Markdown, or false if conversion failed
161      */
162     private function get_markdown()
163     {
164         // Work on the entire DOM tree (including head and body)
165         $input = $this->document->getElementsByTagName("html")->item(0);
166
167         if (!$input)
168             return false;
169
170         // Convert all children of this root element. The DOMDocument stored in $this->doc will
171         // then consist of #text nodes, each containing a Markdown version of the original node
172         // that it replaced.
173         $this->convert_children($input);
174
175         // Sanitize and return the body contents as a string.
176         $markdown = $this->document->saveHTML(); // stores the DOMDocument as a string
177         $markdown = html_entity_decode($markdown, ENT_QUOTES, 'UTF-8');
178         $markdown = html_entity_decode($markdown, ENT_QUOTES, 'UTF-8'); // Double decode to cover cases like &amp;nbsp; http://www.php.net/manual/en/function.htmlentities.php#99984
179         $markdown = preg_replace("/<!DOCTYPE [^>]+>/", "", $markdown); // Strip doctype declaration
180         $unwanted = array('<html>', '</html>', '<body>', '</body>', '<head>', '</head>', '<?xml encoding="UTF-8">', '&#xD;');
181         $markdown = str_replace($unwanted, '', $markdown); // Strip unwanted tags
182         $markdown = trim($markdown, "\n\r\0\x0B");
183
184         $this->output = $markdown;
185
186         return $markdown;
187     }
188
189
190     /**
191      * Convert to Markdown
192      *
193      * Converts an individual node into a #text node containing a string of its Markdown equivalent.
194      *
195      * Example: An <h3> node with text content of "Title" becomes a text node with content of "### Title"
196      *
197      * @param $node
198      * @return string The converted HTML as Markdown
199      */
200     private function convert_to_markdown($node)
201     {
202         $tag = $node->nodeName; // the type of element, e.g. h1
203         $value = $node->nodeValue; // the value of that element, e.g. The Title
204         
205         // Strip nodes named in remove_nodes
206         $tags_to_remove = explode(' ', $this->options['remove_nodes']);
207         if ( in_array($tag, $tags_to_remove) )
208             return false;
209
210         switch ($tag) {
211             case "p":
212                 $markdown = (trim($value)) ? rtrim($value) . PHP_EOL . PHP_EOL : '';
213                 break;
214             case "pre":
215                 $markdown = PHP_EOL . $this->convert_code($node) . PHP_EOL;
216                 break;
217             case "h1":
218             case "h2":
219                 $markdown = $this->convert_header($tag, $node);
220                 break;
221             case "h3":
222                 $markdown = "### " . $value . PHP_EOL . PHP_EOL;
223                 break;
224             case "h4":
225                 $markdown = "#### " . $value . PHP_EOL . PHP_EOL;
226                 break;
227             case "h5":
228                 $markdown = "##### " . $value . PHP_EOL . PHP_EOL;
229                 break;
230             case "h6":
231                 $markdown = "###### " . $value . PHP_EOL . PHP_EOL;
232                 break;
233             case "em":
234             case "i":
235             case "strong":
236             case "b":
237                 $markdown = $this->convert_emphasis($tag, $value);
238                 break;
239             case "hr":
240                 $markdown = "- - - - - -" . PHP_EOL . PHP_EOL;
241                 break;
242             case "br":
243                 $markdown = "  " . PHP_EOL;
244                 break;
245             case "blockquote":
246                 $markdown = $this->convert_blockquote($node);
247                 break;
248             case "code":
249                 $markdown = $this->convert_code($node);
250                 break;
251             case "ol":
252             case "ul":
253                 $markdown = $value . PHP_EOL;
254                 break;
255             case "li":
256                 $markdown = $this->convert_list($node);
257                 break;
258             case "img":
259                 $markdown = $this->convert_image($node);
260                 break;
261             case "a":
262                 $markdown = $this->convert_anchor($node);
263                 break;
264             case "#text":
265                 $markdown = preg_replace('~\s+~', ' ', $value);
266                 $markdown = preg_replace('~^#~', '\\\\#', $markdown);
267                 break;
268             case "#comment":
269                 $markdown = '';
270                 break;
271             case "div":
272                 $markdown = ($this->options['strip_tags']) ? $value . PHP_EOL . PHP_EOL : html_entity_decode($node->C14N());
273                 break;
274             default:
275                 // If strip_tags is false (the default), preserve tags that don't have Markdown equivalents,
276                 // such as <span> nodes on their own. C14N() canonicalizes the node to a string.
277                 // See: http://www.php.net/manual/en/domnode.c14n.php
278                 $markdown = ($this->options['strip_tags']) ? $value : html_entity_decode($node->C14N());
279         }
280
281         return $markdown;
282     }
283
284
285     /**
286      * Convert Header
287      *
288      * Converts h1 and h2 headers to Markdown-style headers in setext style,
289      * matching the number of underscores with the length of the title.
290      *
291      * e.g.     Header 1    Header Two
292      *          ========    ----------
293      *
294      * Returns atx headers instead if $this->options['header_style'] is "atx"
295      *
296      * e.g.    # Header 1   ## Header Two
297      *
298      * @param string $level The header level, including the "h". e.g. h1
299      * @param string $node The node to convert.
300      * @return string The Markdown version of the header.
301      */
302     private function convert_header($level, $node)
303     {
304         $content = $node->nodeValue;
305
306         if (!$this->is_child_of('blockquote', $node) && $this->options['header_style'] == "setext") {
307             $length = (function_exists('mb_strlen')) ? mb_strlen($content, 'utf-8') : strlen($content);
308             $underline = ($level == "h1") ? "=" : "-";
309             $markdown = $content . PHP_EOL . str_repeat($underline, $length) . PHP_EOL . PHP_EOL; // setext style
310         } else {
311             $prefix = ($level == "h1") ? "# " : "## ";
312             $markdown = $prefix . $content . PHP_EOL . PHP_EOL; // atx style
313         }
314
315         return $markdown;
316     }
317
318
319     /**
320      * Converts inline styles
321      * This function is used to render strong and em tags
322      * 
323      * eg <strong>bold text</strong> becomes **bold text** or __bold text__
324      * 
325      * @param string $tag
326      * @param string $value
327      * @return string
328      */
329      private function convert_emphasis($tag, $value)
330      {
331         if ($tag == 'i' || $tag == 'em') {
332             $markdown = $this->options['italic_style'] . $value . $this->options['italic_style'];
333         } else {
334             $markdown = $this->options['bold_style'] . $value . $this->options['bold_style'];
335         }
336         
337         return $markdown;
338      }
339
340
341     /**
342      * Convert Image
343      *
344      * Converts <img /> tags to Markdown.
345      *
346      * e.g.     <img src="/path/img.jpg" alt="alt text" title="Title" />
347      * becomes  ![alt text](/path/img.jpg "Title")
348      *
349      * @param $node
350      * @return string
351      */
352     private function convert_image($node)
353     {
354         $src = $node->getAttribute('src');
355         $alt = $node->getAttribute('alt');
356         $title = $node->getAttribute('title');
357
358         if ($title != "") {
359             $markdown = '![' . $alt . '](' . $src . ' "' . $title . '")'; // No newlines added. <img> should be in a block-level element.
360         } else {
361             $markdown = '![' . $alt . '](' . $src . ')';
362         }
363
364         return $markdown;
365     }
366
367
368     /**
369      * Convert Anchor
370      *
371      * Converts <a> tags to Markdown.
372      *
373      * e.g.     <a href="http://modernnerd.net" title="Title">Modern Nerd</a>
374      * becomes  [Modern Nerd](http://modernnerd.net "Title")
375      *
376      * @param $node
377      * @return string
378      */
379     private function convert_anchor($node)
380     {
381         $href = $node->getAttribute('href');
382         $title = $node->getAttribute('title');
383         $text = $node->nodeValue;
384
385         if ($title != "") {
386             $markdown = '[' . $text . '](' . $href . ' "' . $title . '")';
387         } else {
388             $markdown = '[' . $text . '](' . $href . ')';
389         }
390
391         // Append a space if the node after this one is also an anchor
392         $next_node_name = $this->get_next_node_name($node);
393
394         if ($next_node_name == 'a')
395             $markdown = $markdown . ' ';
396
397         return $markdown;
398     }
399
400
401     /**
402      * Convert List
403      *
404      * Converts <ul> and <ol> lists to Markdown.
405      *
406      * @param $node
407      * @return string
408      */
409     private function convert_list($node)
410     {
411         // If parent is an ol, use numbers, otherwise, use dashes
412         $list_type = $node->parentNode->nodeName;
413         $value = $node->nodeValue;
414
415         if ($list_type == "ul") {
416             $markdown = "- " . trim($value) . PHP_EOL;
417         } else {
418             $number = $this->get_position($node);
419             $markdown = $number . ". " . trim($value) . PHP_EOL;
420         }
421
422         return $markdown;
423     }
424
425
426     /**
427      * Convert Code
428      *
429      * Convert code tags by indenting blocks of code and wrapping single lines in backticks.
430      *
431      * @param DOMNode $node
432      * @return string
433      */
434     private function convert_code($node)
435     {
436         // Store the content of the code block in an array, one entry for each line
437
438         $markdown = '';
439
440         $code_content = html_entity_decode($this->document->saveHTML($node));
441         $code_content = str_replace(array("<code>", "</code>"), "", $code_content);
442         $code_content = str_replace(array("<pre>", "</pre>"), "", $code_content);
443
444         $lines = preg_split('/\r\n|\r|\n/', $code_content);
445         $total = count($lines);
446
447         // If there's more than one line of code, prepend each line with four spaces and no backticks.
448         if ($total > 1 || $node->nodeName === 'pre') {
449
450             // Remove the first and last line if they're empty
451             $first_line = trim($lines[0]);
452             $last_line = trim($lines[$total - 1]);
453             $first_line = trim($first_line, "&#xD;"); //trim XML style carriage returns too
454             $last_line = trim($last_line, "&#xD;");
455
456             if (empty($first_line))
457                 array_shift($lines);
458
459             if (empty($last_line))
460                 array_pop($lines);
461
462             $count = 1;
463             foreach ($lines as $line) {
464                 $line = str_replace('&#xD;', '', $line);
465                 $markdown .= "    " . $line;
466                 // Add newlines, except final line of the code
467                 if ($count != $total)
468                     $markdown .= PHP_EOL;
469                 $count++;
470             }
471             $markdown .= PHP_EOL;
472
473         } else { // There's only one line of code. It's a code span, not a block. Just wrap it with backticks.
474
475             $markdown .= "`" . $lines[0] . "`";
476
477         }
478         
479         return $markdown;
480     }
481
482
483     /**
484      * Convert blockquote
485      *
486      * Prepend blockquotes with > chars.
487      *
488      * @param $node
489      * @return string
490      */
491     private function convert_blockquote($node)
492     {
493         // Contents should have already been converted to Markdown by this point,
494         // so we just need to add ">" symbols to each line.
495
496         $markdown = '';
497
498         $quote_content = trim($node->nodeValue);
499
500         $lines = preg_split('/\r\n|\r|\n/', $quote_content);
501
502         $total_lines = count($lines);
503
504         foreach ($lines as $i => $line) {
505             $markdown .= "> " . $line . PHP_EOL;
506             if ($i + 1 == $total_lines)
507                 $markdown .= PHP_EOL;
508         }
509
510         return $markdown;
511     }
512
513
514     /**
515      * Get Position
516      *
517      * Returns the numbered position of a node inside its parent
518      *
519      * @param $node
520      * @return int The numbered position of the node, starting at 1.
521      */
522     private function get_position($node)
523     {
524         // Get all of the nodes inside the parent
525         $list_nodes = $node->parentNode->childNodes;
526         $total_nodes = $list_nodes->length;
527
528         $position = 1;
529
530         // Loop through all nodes and find the given $node
531         for ($a = 0; $a < $total_nodes; $a++) {
532             $current_node = $list_nodes->item($a);
533
534             if ($current_node->isSameNode($node))
535                 $position = $a + 1;
536         }
537
538         return $position;
539     }
540
541
542     /**
543      * Get Next Node Name
544      *
545      * Return the name of the node immediately after the passed one.
546      *
547      * @param $node
548      * @return string|null The node name (e.g. 'h1') or null.
549      */
550     private function get_next_node_name($node)
551     {
552         $next_node_name = null;
553
554         $current_position = $this->get_position($node);
555         $next_node = $node->parentNode->childNodes->item($current_position);
556
557         if ($next_node)
558             $next_node_name = $next_node->nodeName;
559
560         return $next_node_name;
561     }
562
563
564     /**
565      * To String
566      *
567      * Magic method to return Markdown output when HTML_To_Markdown instance is treated as a string.
568      *
569      * @return string
570      */
571     public function __toString()
572     {
573         return $this->output();
574     }
575
576
577     /**
578      * Output
579      *
580      * Getter for the converted Markdown contents stored in $this->output
581      *
582      * @return string
583      */
584     public function output()
585     {
586         if (!$this->output) {
587             return '';
588         } else {
589             return $this->output;
590         }
591     }
592 }