]> git.mxchange.org Git - friendica.git/blob - include/markdownify/markdownify.php
Merge branch 'master' of https://github.com/friendica/friendica into threaded_items
[friendica.git] / include / markdownify / markdownify.php
1 <?php
2 /**
3  * Markdownify converts HTML Markup to [Markdown][1] (by [John Gruber][2]. It
4  * also supports [Markdown Extra][3] by [Michel Fortin][4] via Markdownify_Extra.
5  *
6  * It all started as `html2text.php` - a port of [Aaron Swartz'][5] [`html2text.py`][6] - but
7  * got a long way since. This is far more than a mere port now!
8  * Starting with version 2.0.0 this is a complete rewrite and cannot be
9  * compared to Aaron Swatz' `html2text.py` anylonger. I'm now using a HTML parser
10  * (see `parsehtml.php` which I also wrote) which makes most of the evil
11  * RegEx magic go away and additionally it gives a much cleaner class
12  * structure. Also notably is the fact that I now try to prevent regressions by
13  * utilizing testcases of Michel Fortin's [MDTest][7].
14  *
15  * [1]: http://daringfireball.com/projects/markdown
16  * [2]: http://daringfireball.com/
17  * [3]: http://www.michelf.com/projects/php-markdown/extra/
18  * [4]: http://www.michelf.com/
19  * [5]: http://www.aaronsw.com/
20  * [6]: http://www.aaronsw.com/2002/html2text/
21  * [7]: http://article.gmane.org/gmane.text.markdown.general/2540
22  *
23  * @version 2.0.0 alpha
24  * @author Milian Wolff (<mail@milianw.de>, <http://milianw.de>)
25  * @license LGPL, see LICENSE_LGPL.txt and the summary below
26  * @copyright (C) 2007  Milian Wolff
27  *
28  * This library is free software; you can redistribute it and/or
29  * modify it under the terms of the GNU Lesser General Public
30  * License as published by the Free Software Foundation; either
31  * version 2.1 of the License, or (at your option) any later version.
32  *
33  * This library is distributed in the hope that it will be useful,
34  * but WITHOUT ANY WARRANTY; without even the implied warranty of
35  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
36  * Lesser General Public License for more details.
37  *
38  * You should have received a copy of the GNU Lesser General Public
39  * License along with this library; if not, write to the Free Software
40  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
41  */
42
43 /**
44  * HTML Parser, see http://sf.net/projects/parseHTML
45  */
46 require_once dirname(__FILE__).'/parsehtml/parsehtml.php';
47
48 /**
49  * default configuration
50  */
51 define('MDFY_LINKS_EACH_PARAGRAPH', false);
52 define('MDFY_BODYWIDTH', false);
53 define('MDFY_KEEPHTML', true);
54
55 /**
56  * HTML to Markdown converter class
57  */
58 class Markdownify {
59   /**
60    * html parser object
61    *
62    * @var parseHTML
63    */
64   var $parser;
65   /**
66    * markdown output
67    *
68    * @var string
69    */
70   var $output;
71   /**
72    * stack with tags which where not converted to html
73    *
74    * @var array<string>
75    */
76   var $notConverted = array();
77   /**
78    * skip conversion to markdown
79    *
80    * @var bool
81    */
82   var $skipConversion = false;
83   /* options */
84   /**
85    * keep html tags which cannot be converted to markdown
86    *
87    * @var bool
88    */
89   var $keepHTML = false;
90   /**
91    * wrap output, set to 0 to skip wrapping
92    *
93    * @var int
94    */
95   var $bodyWidth = 0;
96   /**
97    * minimum body width
98    *
99    * @var int
100    */
101   var $minBodyWidth = 25;
102   /**
103    * display links after each paragraph
104    *
105    * @var bool
106    */
107   var $linksAfterEachParagraph = false;
108   /**
109    * constructor, set options, setup parser
110    *
111    * @param bool $linksAfterEachParagraph wether or not to flush stacked links after each paragraph
112    *             defaults to false
113    * @param int $bodyWidth wether or not to wrap the output to the given width
114    *             defaults to false
115    * @param bool $keepHTML wether to keep non markdownable HTML or to discard it
116    *             defaults to true (HTML will be kept)
117    * @return void
118    */
119   function Markdownify($linksAfterEachParagraph = MDFY_LINKS_EACH_PARAGRAPH, $bodyWidth = MDFY_BODYWIDTH, $keepHTML = MDFY_KEEPHTML) {
120     $this->linksAfterEachParagraph = $linksAfterEachParagraph;
121     $this->keepHTML = $keepHTML;
122
123     if ($bodyWidth > $this->minBodyWidth) {
124       $this->bodyWidth = intval($bodyWidth);
125     } else {
126       $this->bodyWidth = false;
127     }
128
129     $this->parser = new parseHTML;
130     $this->parser->noTagsInCode = true;
131
132     # we don't have to do this every time
133     $search = array();
134     $replace = array();
135     foreach ($this->escapeInText as $s => $r) {
136       array_push($search, '#(?<!\\\)'.$s.'#U');
137       array_push($replace, $r);
138     }
139     $this->escapeInText = array(
140       'search' => $search,
141       'replace' => $replace
142     );
143   }
144   /**
145    * parse a HTML string
146    *
147    * @param string $html
148    * @return string markdown formatted
149    */
150   function parseString($html) {
151     $this->parser->html = $html;
152     $this->parse();
153     return $this->output;
154   }
155   /**
156    * tags with elements which can be handled by markdown
157    *
158    * @var array<string>
159    */
160   var $isMarkdownable = array(
161     'p' => array(),
162     'ul' => array(),
163     'ol' => array(),
164     'li' => array(),
165     'br' => array(),
166     'blockquote' => array(),
167     'code' => array(),
168     'pre' => array(),
169     'a' => array(
170       'href' => 'required',
171       'title' => 'optional',
172     ),
173     'strong' => array(),
174     'b' => array(),
175     'em' => array(),
176     'i' => array(),
177     'img' => array(
178       'src' => 'required',
179       'alt' => 'optional',
180       'title' => 'optional',
181     ),
182     'h1' => array(),
183     'h2' => array(),
184     'h3' => array(),
185     'h4' => array(),
186     'h5' => array(),
187     'h6' => array(),
188     'hr' => array(),
189   );
190   /**
191    * html tags to be ignored (contents will be parsed)
192    *
193    * @var array<string>
194    */
195   var $ignore = array(
196     'html',
197     'body',
198   );
199   /**
200    * html tags to be dropped (contents will not be parsed!)
201    *
202    * @var array<string>
203    */
204   var $drop = array(
205     'script',
206     'head',
207     'style',
208     'form',
209     'area',
210     'object',
211     'param',
212     'iframe',
213   );
214   /**
215    * Markdown indents which could be wrapped
216    * @note: use strings in regex format
217    *
218    * @var array<string>
219    */
220   var $wrappableIndents = array(
221     '\*   ', # ul
222     '\d.  ', # ol
223     '\d\d. ', # ol
224     '> ', # blockquote
225     '', # p
226   );
227   /**
228    * list of chars which have to be escaped in normal text
229    * @note: use strings in regex format
230    *
231    * @var array
232    *
233    * TODO: what's with block chars / sequences at the beginning of a block?
234    */
235   var $escapeInText = array(
236     '([-*_])([ ]{0,2}\1){2,}' => '\\\\$0|', # hr
237     '\*\*([^*\s]+)\*\*' => '\*\*$1\*\*', # strong
238     '\*([^*\s]+)\*' => '\*$1\*', # em
239     '__(?! |_)(.+)(?!<_| )__' => '\_\_$1\_\_', # em
240     '_(?! |_)(.+)(?!<_| )_' => '\_$1\_', # em
241     '`(.+)`' => '\`$1\`', # code
242     '\[(.+)\](\s*\()' => '\[$1\]$2', # links: [text] (url) => [text\] (url)
243     '\[(.+)\](\s*)\[(.*)\]' => '\[$1\]$2\[$3\]', # links: [text][id] => [text\][id\]
244   );
245   /**
246    * wether last processed node was a block tag or not
247    *
248    * @var bool
249    */
250   var $lastWasBlockTag = false;
251   /**
252    * name of last closed tag
253    *
254    * @var string
255    */
256   var $lastClosedTag = '';
257   /**
258    * iterate through the nodes and decide what we
259    * shall do with the current node
260    *
261    * @param void
262    * @return void
263    */
264   function parse() {
265     $this->output = '';
266     # drop tags
267     $this->parser->html = preg_replace('#<('.implode('|', $this->drop).')[^>]*>.*</\\1>#sU', '', $this->parser->html);
268     while ($this->parser->nextNode()) {
269       switch ($this->parser->nodeType) {
270         case 'doctype':
271           break;
272         case 'pi':
273         case 'comment':
274           if ($this->keepHTML) {
275             $this->flushLinebreaks();
276             $this->out($this->parser->node);
277             $this->setLineBreaks(2);
278           }
279           # else drop
280           break;
281         case 'text':
282           $this->handleText();
283           break;
284         case 'tag':
285           if (in_array($this->parser->tagName, $this->ignore)) {
286             break;
287           }
288           if ($this->parser->isStartTag) {
289             $this->flushLinebreaks();
290           }
291           if ($this->skipConversion) {
292             $this->isMarkdownable(); # update notConverted
293             $this->handleTagToText();
294             continue;
295           }
296           if (!$this->parser->keepWhitespace && $this->parser->isBlockElement && $this->parser->isStartTag) {
297             $this->parser->html = ltrim($this->parser->html);
298           }
299           if ($this->isMarkdownable()) {
300             if ($this->parser->isBlockElement && $this->parser->isStartTag && !$this->lastWasBlockTag && !empty($this->output)) {
301               if (!empty($this->buffer)) {
302                 $str =& $this->buffer[count($this->buffer) -1];
303               } else {
304                 $str =& $this->output;
305               }
306               if (substr($str, -strlen($this->indent)-1) != "\n".$this->indent) {
307                 $str .= "\n".$this->indent;
308               }
309             }
310             $func = 'handleTag_'.$this->parser->tagName;
311             $this->$func();
312             if ($this->linksAfterEachParagraph && $this->parser->isBlockElement && !$this->parser->isStartTag && empty($this->parser->openTags)) {
313               $this->flushStacked();
314             }
315             if (!$this->parser->isStartTag) {
316               $this->lastClosedTag = $this->parser->tagName;
317             }
318           } else {
319             $this->handleTagToText();
320             $this->lastClosedTag = '';
321           }
322           break;
323         default:
324           trigger_error('invalid node type', E_USER_ERROR);
325           break;
326       }
327       $this->lastWasBlockTag = $this->parser->nodeType == 'tag' && $this->parser->isStartTag && $this->parser->isBlockElement;
328     }
329     if (!empty($this->buffer)) {
330       trigger_error('buffer was not flushed, this is a bug. please report!', E_USER_WARNING);
331       while (!empty($this->buffer)) {
332         $this->out($this->unbuffer());
333       }
334     }
335     ### cleanup
336     $this->output = rtrim(str_replace('&amp;', '&', str_replace('&lt;', '<', str_replace('&gt;', '>', $this->output))));
337     # end parsing, flush stacked tags
338     $this->flushStacked();
339     $this->stack = array();
340   }
341   /**
342    * check if current tag can be converted to Markdown
343    *
344    * @param void
345    * @return bool
346    */
347   function isMarkdownable() {
348     if (!isset($this->isMarkdownable[$this->parser->tagName])) {
349       # simply not markdownable
350       return false;
351     }
352     if ($this->parser->isStartTag) {
353       $return = true;
354       if ($this->keepHTML) {
355         $diff = array_diff(array_keys($this->parser->tagAttributes), array_keys($this->isMarkdownable[$this->parser->tagName]));
356         if (!empty($diff)) {
357           # non markdownable attributes given
358           $return = false;
359         }
360       }
361       if ($return) {
362         foreach ($this->isMarkdownable[$this->parser->tagName] as $attr => $type) {
363           if ($type == 'required' && !isset($this->parser->tagAttributes[$attr])) {
364             # required markdown attribute not given
365             $return = false;
366             break;
367           }
368         }
369       }
370       if (!$return) {
371         array_push($this->notConverted, $this->parser->tagName.'::'.implode('/', $this->parser->openTags));
372       }
373       return $return;
374     } else {
375       if (!empty($this->notConverted) && end($this->notConverted) === $this->parser->tagName.'::'.implode('/', $this->parser->openTags)) {
376         array_pop($this->notConverted);
377         return false;
378       }
379       return true;
380     }
381   }
382   /**
383    * output all stacked tags
384    *
385    * @param void
386    * @return void
387    */
388   function flushStacked() {
389     # links
390     foreach ($this->stack as $tag => $a) {
391       if (!empty($a)) {
392         call_user_func(array(&$this, 'flushStacked_'.$tag));
393       }
394     }
395   }
396   /**
397    * output link references (e.g. [1]: http://example.com "title");
398    *
399    * @param void
400    * @return void
401    */
402   function flushStacked_a() {
403     $out = false;
404     foreach ($this->stack['a'] as $k => $tag) {
405       if (!isset($tag['unstacked'])) {
406         if (!$out) {
407           $out = true;
408           $this->out("\n\n", true);
409         } else {
410           $this->out("\n", true);
411         }
412         $this->out(' ['.$tag['linkID'].']: '.$tag['href'].(isset($tag['title']) ? ' "'.$tag['title'].'"' : ''), true);
413         $tag['unstacked'] = true;
414         $this->stack['a'][$k] = $tag;
415       }
416     }
417   }
418   /**
419    * flush enqued linebreaks
420    *
421    * @param void
422    * @return void
423    */
424   function flushLinebreaks() {
425     if ($this->lineBreaks && !empty($this->output)) {
426       $this->out(str_repeat("\n".$this->indent, $this->lineBreaks), true);
427     }
428     $this->lineBreaks = 0;
429   }
430   /**
431    * handle non Markdownable tags
432    *
433    * @param void
434    * @return void
435    */
436   function handleTagToText() {
437     if (!$this->keepHTML) {
438       if (!$this->parser->isStartTag && $this->parser->isBlockElement) {
439         $this->setLineBreaks(2);
440       }
441     } else {
442       # dont convert to markdown inside this tag
443       /** TODO: markdown extra **/
444       if (!$this->parser->isEmptyTag) {
445         if ($this->parser->isStartTag) {
446           if (!$this->skipConversion) {
447             $this->skipConversion = $this->parser->tagName.'::'.implode('/', $this->parser->openTags);
448           }
449         } else {
450           if ($this->skipConversion == $this->parser->tagName.'::'.implode('/', $this->parser->openTags)) {
451             $this->skipConversion = false;
452           }
453         }
454       }
455
456       if ($this->parser->isBlockElement) {
457         if ($this->parser->isStartTag) {
458           if (in_array($this->parent(), array('ins', 'del'))) {
459             # looks like ins or del are block elements now
460             $this->out("\n", true);
461             $this->indent('  ');
462           }
463           if ($this->parser->tagName != 'pre') {
464             $this->out($this->parser->node."\n".$this->indent);
465             if (!$this->parser->isEmptyTag) {
466               $this->indent('  ');
467             } else {
468               $this->setLineBreaks(1);
469             }
470             $this->parser->html = ltrim($this->parser->html);
471           } else {
472             # don't indent inside <pre> tags
473             $this->out($this->parser->node);
474             static $indent;
475             $indent =  $this->indent;
476             $this->indent = '';
477           }
478         } else {
479           if (!$this->parser->keepWhitespace) {
480             $this->output = rtrim($this->output);
481           }
482           if ($this->parser->tagName != 'pre') {
483             $this->indent('  ');
484             $this->out("\n".$this->indent.$this->parser->node);
485           } else {
486             # reset indentation
487             $this->out($this->parser->node);
488             static $indent;
489             $this->indent = $indent;
490           }
491
492           if (in_array($this->parent(), array('ins', 'del'))) {
493             # ins or del was block element
494             $this->out("\n");
495             $this->indent('  ');
496           }
497           if ($this->parser->tagName == 'li') {
498             $this->setLineBreaks(1);
499           } else {
500             $this->setLineBreaks(2);
501           }
502         }
503       } else {
504         $this->out($this->parser->node);
505       }
506       if (in_array($this->parser->tagName, array('code', 'pre'))) {
507         if ($this->parser->isStartTag) {
508           $this->buffer();
509         } else {
510           # add stuff so cleanup just reverses this
511           $this->out(str_replace('&lt;', '&amp;lt;', str_replace('&gt;', '&amp;gt;', $this->unbuffer())));
512         }
513       }
514     }
515   }
516   /**
517    * handle plain text
518    *
519    * @param void
520    * @return void
521    */
522   function handleText() {
523     if ($this->hasParent('pre') && strpos($this->parser->node, "\n") !== false) {
524       $this->parser->node = str_replace("\n", "\n".$this->indent, $this->parser->node);
525     }
526     if (!$this->hasParent('code') && !$this->hasParent('pre')) {
527       # entity decode
528       $this->parser->node = $this->decode($this->parser->node);
529       if (!$this->skipConversion) {
530         # escape some chars in normal Text
531         $this->parser->node = preg_replace($this->escapeInText['search'], $this->escapeInText['replace'], $this->parser->node);
532       }
533     } else {
534       $this->parser->node = str_replace(array('&quot;', '&apos'), array('"', '\''), $this->parser->node);
535     }
536     $this->out($this->parser->node);
537     $this->lastClosedTag = '';
538   }
539   /**
540    * handle <em> and <i> tags
541    *
542    * @param void
543    * @return void
544    */
545   function handleTag_em() {
546     $this->out('*', true);
547   }
548   function handleTag_i() {
549     $this->handleTag_em();
550   }
551   /**
552    * handle <strong> and <b> tags
553    *
554    * @param void
555    * @return void
556    */
557   function handleTag_strong() {
558     $this->out('**', true);
559   }
560   function handleTag_b() {
561     $this->handleTag_strong();
562   }
563   /**
564    * handle <h1> tags
565    *
566    * @param void
567    * @return void
568    */
569   function handleTag_h1() {
570     $this->handleHeader(1);
571   }
572   /**
573    * handle <h2> tags
574    *
575    * @param void
576    * @return void
577    */
578   function handleTag_h2() {
579     $this->handleHeader(2);
580   }
581   /**
582    * handle <h3> tags
583    *
584    * @param void
585    * @return void
586    */
587   function handleTag_h3() {
588     $this->handleHeader(3);
589   }
590   /**
591    * handle <h4> tags
592    *
593    * @param void
594    * @return void
595    */
596   function handleTag_h4() {
597     $this->handleHeader(4);
598   }
599   /**
600    * handle <h5> tags
601    *
602    * @param void
603    * @return void
604    */
605   function handleTag_h5() {
606     $this->handleHeader(5);
607   }
608   /**
609    * handle <h6> tags
610    *
611    * @param void
612    * @return void
613    */
614   function handleTag_h6() {
615     $this->handleHeader(6);
616   }
617   /**
618    * number of line breaks before next inline output
619    */
620   var $lineBreaks = 0;
621   /**
622    * handle header tags (<h1> - <h6>)
623    *
624    * @param int $level 1-6
625    * @return void
626    */
627   function handleHeader($level) {
628     if ($this->parser->isStartTag) {
629       $this->out(str_repeat('#', $level).' ', true);
630     } else {
631       $this->setLineBreaks(2);
632     }
633   }
634   /**
635    * handle <p> tags
636    *
637    * @param void
638    * @return void
639    */
640   function handleTag_p() {
641     if (!$this->parser->isStartTag) {
642       $this->setLineBreaks(2);
643     }
644   }
645   /**
646    * handle <a> tags
647    *
648    * @param void
649    * @return void
650    */
651   function handleTag_a() {
652     if ($this->parser->isStartTag) {
653       $this->buffer();
654       if (isset($this->parser->tagAttributes['title'])) {
655         $this->parser->tagAttributes['title'] = $this->decode($this->parser->tagAttributes['title']);
656       } else {
657         $this->parser->tagAttributes['title'] = null;
658       }
659       $this->parser->tagAttributes['href'] = $this->decode(trim($this->parser->tagAttributes['href']));
660       $this->stack();
661     } else {
662       $tag = $this->unstack();
663       $buffer = $this->unbuffer();
664
665       if (empty($tag['href']) && empty($tag['title'])) {
666         # empty links... testcase mania, who would possibly do anything like that?!
667         $this->out('['.$buffer.']()', true);
668         return;
669       }
670
671       if ($buffer == $tag['href'] && empty($tag['title'])) {
672         # <http://example.com>
673         $this->out('<'.$buffer.'>', true);
674         return;
675       }
676
677       $bufferDecoded = $this->decode(trim($buffer));
678       if (substr($tag['href'], 0, 7) == 'mailto:' && 'mailto:'.$bufferDecoded == $tag['href']) {
679         if (is_null($tag['title'])) {
680           # <mail@example.com>
681           $this->out('<'.$bufferDecoded.'>', true);
682           return;
683         }
684         # [mail@example.com][1]
685         # ...
686         #  [1]: mailto:mail@example.com Title
687         $tag['href'] = 'mailto:'.$bufferDecoded;
688       }
689       # [This link][id]
690       foreach ($this->stack['a'] as $tag2) {
691         if ($tag2['href'] == $tag['href'] && $tag2['title'] === $tag['title']) {
692           $tag['linkID'] = $tag2['linkID'];
693           break;
694         }
695       }
696       if (!isset($tag['linkID'])) {
697         $tag['linkID'] = count($this->stack['a']) + 1;
698         array_push($this->stack['a'], $tag);
699       }
700
701       $this->out('['.$buffer.']['.$tag['linkID'].']', true);
702     }
703   }
704   /**
705    * handle <img /> tags
706    *
707    * @param void
708    * @return void
709    */
710   function handleTag_img() {
711     if (!$this->parser->isStartTag) {
712       return; # just to be sure this is really an empty tag...
713     }
714
715     if (isset($this->parser->tagAttributes['title'])) {
716       $this->parser->tagAttributes['title'] = $this->decode($this->parser->tagAttributes['title']);
717     } else {
718       $this->parser->tagAttributes['title'] = null;
719     }
720     if (isset($this->parser->tagAttributes['alt'])) {
721       $this->parser->tagAttributes['alt'] = $this->decode($this->parser->tagAttributes['alt']);
722     } else {
723       $this->parser->tagAttributes['alt'] = null;
724     }
725
726     if (empty($this->parser->tagAttributes['src'])) {
727       # support for "empty" images... dunno if this is really needed
728       # but there are some testcases which do that...
729       if (!empty($this->parser->tagAttributes['title'])) {
730         $this->parser->tagAttributes['title'] = ' '.$this->parser->tagAttributes['title'].' ';
731       }
732       $this->out('!['.$this->parser->tagAttributes['alt'].']('.$this->parser->tagAttributes['title'].')', true);
733       return;
734     } else {
735       $this->parser->tagAttributes['src'] = $this->decode($this->parser->tagAttributes['src']);
736     }
737
738 // ![Alt text](/path/to/img.jpg "Optional title")
739     if ($this->parser->tagAttributes['title'] != "")
740       $this->out('!['.$this->parser->tagAttributes['alt'].']('.$this->parser->tagAttributes['src'].'"'.$this->parser->tagAttributes['title'].'")', true);
741     else
742       $this->out('!['.$this->parser->tagAttributes['alt'].']('.$this->parser->tagAttributes['src'].')', true);
743
744 /*
745     # [This link][id]
746     $link_id = false;
747     if (!empty($this->stack['a'])) {
748       foreach ($this->stack['a'] as $tag) {
749         if ($tag['href'] == $this->parser->tagAttributes['src']
750             && $tag['title'] === $this->parser->tagAttributes['title']) {
751           $link_id = $tag['linkID'];
752           break;
753         }
754       }
755     } else {
756       $this->stack['a'] = array();
757     }
758     if (!$link_id) {
759       $link_id = count($this->stack['a']) + 1;
760       $tag = array(
761         'href' => $this->parser->tagAttributes['src'],
762         'linkID' => $link_id,
763         'title' => $this->parser->tagAttributes['title']
764       );
765       array_push($this->stack['a'], $tag);
766     }
767
768     $this->out('!['.$this->parser->tagAttributes['alt'].']['.$link_id.']', true);
769 */
770   }
771   /**
772    * handle <code> tags
773    *
774    * @param void
775    * @return void
776    */
777   function handleTag_code() {
778     if ($this->hasParent('pre')) {
779       # ignore code blocks inside <pre>
780       return;
781     }
782     if ($this->parser->isStartTag) {
783       $this->buffer();
784     } else {
785       $buffer = $this->unbuffer();
786       # use as many backticks as needed
787       preg_match_all('#`+#', $buffer, $matches);
788       if (!empty($matches[0])) {
789         rsort($matches[0]);
790
791         $ticks = '`';
792         while (true) {
793           if (!in_array($ticks, $matches[0])) {
794             break;
795           }
796           $ticks .= '`';
797         }
798       } else {
799         $ticks = '`';
800       }
801       if ($buffer[0] == '`' || substr($buffer, -1) == '`') {
802         $buffer = ' '.$buffer.' ';
803       }
804       $this->out($ticks.$buffer.$ticks, true);
805     }
806   }
807   /**
808    * handle <pre> tags
809    *
810    * @param void
811    * @return void
812    */
813   function handleTag_pre() {
814     if ($this->keepHTML && $this->parser->isStartTag) {
815       # check if a simple <code> follows
816       if (!preg_match('#^\s*<code\s*>#Us', $this->parser->html)) {
817         # this is no standard markdown code block
818         $this->handleTagToText();
819         return;
820       }
821     }
822     $this->indent('    ');
823     if (!$this->parser->isStartTag) {
824       $this->setLineBreaks(2);
825     } else {
826       $this->parser->html = ltrim($this->parser->html);
827     }
828   }
829   /**
830    * handle <blockquote> tags
831    *
832    * @param void
833    * @return void
834    */
835   function handleTag_blockquote() {
836     $this->indent('> ');
837   }
838   /**
839    * handle <ul> tags
840    *
841    * @param void
842    * @return void
843    */
844   function handleTag_ul() {
845     if ($this->parser->isStartTag) {
846       $this->stack();
847       if (!$this->keepHTML && $this->lastClosedTag == $this->parser->tagName) {
848         $this->out("\n".$this->indent.'<!-- -->'."\n".$this->indent."\n".$this->indent);
849       }
850     } else {
851       $this->unstack();
852       if ($this->parent() != 'li' || preg_match('#^\s*(</li\s*>\s*<li\s*>\s*)?<(p|blockquote)\s*>#sU', $this->parser->html)) {
853         # dont make Markdown add unneeded paragraphs
854         $this->setLineBreaks(2);
855       }
856     }
857   }
858   /**
859    * handle <ul> tags
860    *
861    * @param void
862    * @return void
863    */
864   function handleTag_ol() {
865     # same as above
866     $this->parser->tagAttributes['num'] = 0;
867     $this->handleTag_ul();
868   }
869   /**
870    * handle <li> tags
871    *
872    * @param void
873    * @return void
874    */
875   function handleTag_li() {
876     if ($this->parent() == 'ol') {
877       $parent =& $this->getStacked('ol');
878       if ($this->parser->isStartTag) {
879         $parent['num']++;
880         $this->out($parent['num'].'.'.str_repeat(' ', 3 - strlen($parent['num'])), true);
881       }
882       $this->indent('    ', false);
883     } else {
884       if ($this->parser->isStartTag) {
885         $this->out('*   ', true);
886       }
887       $this->indent('    ', false);
888     }
889     if (!$this->parser->isStartTag) {
890       $this->setLineBreaks(1);
891     }
892   }
893   /**
894    * handle <hr /> tags
895    *
896    * @param void
897    * @return void
898    */
899   function handleTag_hr() {
900     if (!$this->parser->isStartTag) {
901       return; # just to be sure this really is an empty tag
902     }
903     $this->out('* * *', true);
904     $this->setLineBreaks(2);
905   }
906   /**
907    * handle <br /> tags
908    *
909    * @param void
910    * @return void
911    */
912   function handleTag_br() {
913     $this->out("  \n".$this->indent, true);
914     $this->parser->html = ltrim($this->parser->html);
915   }
916   /**
917    * node stack, e.g. for <a> and <abbr> tags
918    *
919    * @var array<array>
920    */
921   var $stack = array();
922   /**
923    * add current node to the stack
924    * this only stores the attributes
925    *
926    * @param void
927    * @return void
928    */
929   function stack() {
930     if (!isset($this->stack[$this->parser->tagName])) {
931       $this->stack[$this->parser->tagName] = array();
932     }
933     array_push($this->stack[$this->parser->tagName], $this->parser->tagAttributes);
934   }
935   /**
936    * remove current tag from stack
937    *
938    * @param void
939    * @return array
940    */
941   function unstack() {
942     if (!isset($this->stack[$this->parser->tagName]) || !is_array($this->stack[$this->parser->tagName])) {
943       trigger_error('Trying to unstack from empty stack. This must not happen.', E_USER_ERROR);
944     }
945     return array_pop($this->stack[$this->parser->tagName]);
946   }
947   /**
948    * get last stacked element of type $tagName
949    *
950    * @param string $tagName
951    * @return array
952    */
953   function & getStacked($tagName) {
954     // no end() so it can be referenced
955     return $this->stack[$tagName][count($this->stack[$tagName])-1];
956   }
957   /**
958    * set number of line breaks before next start tag
959    *
960    * @param int $number
961    * @return void
962    */
963   function setLineBreaks($number) {
964     if ($this->lineBreaks < $number) {
965       $this->lineBreaks = $number;
966     }
967   }
968   /**
969    * stores current buffers
970    *
971    * @var array<string>
972    */
973   var $buffer = array();
974   /**
975    * buffer next parser output until unbuffer() is called
976    *
977    * @param void
978    * @return void
979    */
980   function buffer() {
981     array_push($this->buffer, '');
982   }
983   /**
984    * end current buffer and return buffered output
985    *
986    * @param void
987    * @return string
988    */
989   function unbuffer() {
990     return array_pop($this->buffer);
991   }
992   /**
993    * append string to the correct var, either
994    * directly to $this->output or to the current
995    * buffers
996    *
997    * @param string $put
998    * @return void
999    */
1000   function out($put, $nowrap = false) {
1001     if (empty($put)) {
1002       return;
1003     }
1004     if (!empty($this->buffer)) {
1005       $this->buffer[count($this->buffer) - 1] .= $put;
1006     } else {
1007       if ($this->bodyWidth && !$this->parser->keepWhitespace) { # wrap lines
1008         // get last line
1009         $pos = strrpos($this->output, "\n");
1010         if ($pos === false) {
1011           $line = $this->output;
1012         } else {
1013           $line = substr($this->output, $pos);
1014         }
1015
1016         if ($nowrap) {
1017           if ($put[0] != "\n" && $this->strlen($line) + $this->strlen($put) > $this->bodyWidth) {
1018             $this->output .= "\n".$this->indent.$put;
1019           } else {
1020             $this->output .= $put;
1021           }
1022           return;
1023         } else {
1024           $put .= "\n"; # make sure we get all lines in the while below
1025           $lineLen = $this->strlen($line);
1026           while ($pos = strpos($put, "\n")) {
1027             $putLine = substr($put, 0, $pos+1);
1028             $put = substr($put, $pos+1);
1029             $putLen = $this->strlen($putLine);
1030             if ($lineLen + $putLen < $this->bodyWidth) {
1031               $this->output .= $putLine;
1032               $lineLen = $putLen;
1033             } else {
1034               $split = preg_split('#^(.{0,'.($this->bodyWidth - $lineLen).'})\b#', $putLine, 2, PREG_SPLIT_OFFSET_CAPTURE | PREG_SPLIT_DELIM_CAPTURE);
1035               $this->output .= rtrim($split[1][0])."\n".$this->indent.$this->wordwrap(ltrim($split[2][0]), $this->bodyWidth, "\n".$this->indent, false);
1036             }
1037           }
1038           $this->output = substr($this->output, 0, -1);
1039           return;
1040         }
1041       } else {
1042         $this->output .= $put;
1043       }
1044     }
1045   }
1046   /**
1047    * current indentation
1048    *
1049    * @var string
1050    */
1051   var $indent = '';
1052   /**
1053    * indent next output (start tag) or unindent (end tag)
1054    *
1055    * @param string $str indentation
1056    * @param bool $output add indendation to output
1057    * @return void
1058    */
1059   function indent($str, $output = true) {
1060     if ($this->parser->isStartTag) {
1061       $this->indent .= $str;
1062       if ($output) {
1063         $this->out($str, true);
1064       }
1065     } else {
1066       $this->indent = substr($this->indent, 0, -strlen($str));
1067     }
1068   }
1069   /**
1070    * decode email addresses
1071    *
1072    * @author derernst@gmx.ch <http://www.php.net/manual/en/function.html-entity-decode.php#68536>
1073    * @author Milian Wolff <http://milianw.de>
1074    */
1075   function decode($text, $quote_style = ENT_QUOTES) {
1076     if (version_compare(PHP_VERSION, '5', '>=')) {
1077       # UTF-8 is only supported in PHP 5.x.x and above
1078       $text = html_entity_decode($text, $quote_style, 'UTF-8');
1079     } else {
1080       if (function_exists('html_entity_decode')) {
1081         $text = html_entity_decode($text, $quote_style, 'ISO-8859-1');
1082       } else {
1083         static $trans_tbl;
1084         if (!isset($trans_tbl)) {
1085           $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES, $quote_style));
1086         }
1087         $text = strtr($text, $trans_tbl);
1088       }
1089       $text = preg_replace_callback('~&#x([0-9a-f]+);~i', array(&$this, '_decode_hex'), $text);
1090       $text = preg_replace_callback('~&#(\d{2,5});~', array(&$this, '_decode_numeric'), $text);
1091     }
1092     return $text;
1093   }
1094   /**
1095    * callback for decode() which converts a hexadecimal entity to UTF-8
1096    *
1097    * @param array $matches
1098    * @return string UTF-8 encoded
1099    */
1100   function _decode_hex($matches) {
1101     return $this->unichr(hexdec($matches[1]));
1102   }
1103   /**
1104    * callback for decode() which converts a numerical entity to UTF-8
1105    *
1106    * @param array $matches
1107    * @return string UTF-8 encoded
1108    */
1109   function _decode_numeric($matches) {
1110     return $this->unichr($matches[1]);
1111   }
1112   /**
1113    * UTF-8 chr() which supports numeric entities
1114    *
1115    * @author grey - greywyvern - com <http://www.php.net/manual/en/function.chr.php#55978>
1116    * @param array $matches
1117    * @return string UTF-8 encoded
1118    */
1119   function unichr($dec) {
1120     if ($dec < 128) {
1121       $utf = chr($dec);
1122     } else if ($dec < 2048) {
1123       $utf = chr(192 + (($dec - ($dec % 64)) / 64));
1124       $utf .= chr(128 + ($dec % 64));
1125     } else {
1126       $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
1127       $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
1128       $utf .= chr(128 + ($dec % 64));
1129     }
1130     return $utf;
1131   }
1132   /**
1133    * UTF-8 strlen()
1134    *
1135    * @param string $str
1136    * @return int
1137    *
1138    * @author dtorop 932 at hotmail dot com <http://www.php.net/manual/en/function.strlen.php#37975>
1139    * @author Milian Wolff <http://milianw.de>
1140    */
1141   function strlen($str) {
1142     if (function_exists('mb_strlen')) {
1143       return mb_strlen($str, 'UTF-8');
1144     } else {
1145       return preg_match_all('/[\x00-\x7F\xC0-\xFD]/', $str, $var_empty);
1146     }
1147   }
1148   /**
1149   * wordwrap for utf8 encoded strings
1150   *
1151   * @param string $str
1152   * @param integer $len
1153   * @param string $what
1154   * @return string
1155   */
1156   function wordwrap($str, $width, $break, $cut = false){
1157     if (!$cut) {
1158       $regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){1,'.$width.'}\b#';
1159     } else {
1160       $regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){'.$width.'}#';
1161     }
1162     $return = '';
1163     while (preg_match($regexp, $str, $matches)) {
1164       $string = $matches[0];
1165       $str = ltrim(substr($str, strlen($string)));
1166       if (!$cut && isset($str[0]) && in_array($str[0], array('.', '!', ';', ':', '?', ','))) {
1167         $string .= $str[0];
1168         $str = ltrim(substr($str, 1));
1169       }
1170       $return .= $string.$break;
1171     }
1172     return $return.ltrim($str);
1173   }
1174   /**
1175    * check if current node has a $tagName as parent (somewhere, not only the direct parent)
1176    *
1177    * @param string $tagName
1178    * @return bool
1179    */
1180   function hasParent($tagName) {
1181     return in_array($tagName, $this->parser->openTags);
1182   }
1183   /**
1184    * get tagName of direct parent tag
1185    *
1186    * @param void
1187    * @return string $tagName
1188    */
1189   function parent() {
1190     return end($this->parser->openTags);
1191   }
1192 }