]> git.mxchange.org Git - friendica.git/blob - include/markdownify/markdownify.php
Merge git://github.com/friendica/friendica
[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     # [This link][id]
739     $link_id = false;
740     if (!empty($this->stack['a'])) {
741       foreach ($this->stack['a'] as $tag) {
742         if ($tag['href'] == $this->parser->tagAttributes['src']
743             && $tag['title'] === $this->parser->tagAttributes['title']) {
744           $link_id = $tag['linkID'];
745           break;
746         }
747       }
748     } else {
749       $this->stack['a'] = array();
750     }
751     if (!$link_id) {
752       $link_id = count($this->stack['a']) + 1;
753       $tag = array(
754         'href' => $this->parser->tagAttributes['src'],
755         'linkID' => $link_id,
756         'title' => $this->parser->tagAttributes['title']
757       );
758       array_push($this->stack['a'], $tag);
759     }
760
761     $this->out('!['.$this->parser->tagAttributes['alt'].']['.$link_id.']', true);
762   }
763   /**
764    * handle <code> tags
765    *
766    * @param void
767    * @return void
768    */
769   function handleTag_code() {
770     if ($this->hasParent('pre')) {
771       # ignore code blocks inside <pre>
772       return;
773     }
774     if ($this->parser->isStartTag) {
775       $this->buffer();
776     } else {
777       $buffer = $this->unbuffer();
778       # use as many backticks as needed
779       preg_match_all('#`+#', $buffer, $matches);
780       if (!empty($matches[0])) {
781         rsort($matches[0]);
782
783         $ticks = '`';
784         while (true) {
785           if (!in_array($ticks, $matches[0])) {
786             break;
787           }
788           $ticks .= '`';
789         }
790       } else {
791         $ticks = '`';
792       }
793       if ($buffer[0] == '`' || substr($buffer, -1) == '`') {
794         $buffer = ' '.$buffer.' ';
795       }
796       $this->out($ticks.$buffer.$ticks, true);
797     }
798   }
799   /**
800    * handle <pre> tags
801    *
802    * @param void
803    * @return void
804    */
805   function handleTag_pre() {
806     if ($this->keepHTML && $this->parser->isStartTag) {
807       # check if a simple <code> follows
808       if (!preg_match('#^\s*<code\s*>#Us', $this->parser->html)) {
809         # this is no standard markdown code block
810         $this->handleTagToText();
811         return;
812       }
813     }
814     $this->indent('    ');
815     if (!$this->parser->isStartTag) {
816       $this->setLineBreaks(2);
817     } else {
818       $this->parser->html = ltrim($this->parser->html);
819     }
820   }
821   /**
822    * handle <blockquote> tags
823    *
824    * @param void
825    * @return void
826    */
827   function handleTag_blockquote() {
828     $this->indent('> ');
829   }
830   /**
831    * handle <ul> tags
832    *
833    * @param void
834    * @return void
835    */
836   function handleTag_ul() {
837     if ($this->parser->isStartTag) {
838       $this->stack();
839       if (!$this->keepHTML && $this->lastClosedTag == $this->parser->tagName) {
840         $this->out("\n".$this->indent.'<!-- -->'."\n".$this->indent."\n".$this->indent);
841       }
842     } else {
843       $this->unstack();
844       if ($this->parent() != 'li' || preg_match('#^\s*(</li\s*>\s*<li\s*>\s*)?<(p|blockquote)\s*>#sU', $this->parser->html)) {
845         # dont make Markdown add unneeded paragraphs
846         $this->setLineBreaks(2);
847       }
848     }
849   }
850   /**
851    * handle <ul> tags
852    *
853    * @param void
854    * @return void
855    */
856   function handleTag_ol() {
857     # same as above
858     $this->parser->tagAttributes['num'] = 0;
859     $this->handleTag_ul();
860   }
861   /**
862    * handle <li> tags
863    *
864    * @param void
865    * @return void
866    */
867   function handleTag_li() {
868     if ($this->parent() == 'ol') {
869       $parent =& $this->getStacked('ol');
870       if ($this->parser->isStartTag) {
871         $parent['num']++;
872         $this->out($parent['num'].'.'.str_repeat(' ', 3 - strlen($parent['num'])), true);
873       }
874       $this->indent('    ', false);
875     } else {
876       if ($this->parser->isStartTag) {
877         $this->out('*   ', true);
878       }
879       $this->indent('    ', false);
880     }
881     if (!$this->parser->isStartTag) {
882       $this->setLineBreaks(1);
883     }
884   }
885   /**
886    * handle <hr /> tags
887    *
888    * @param void
889    * @return void
890    */
891   function handleTag_hr() {
892     if (!$this->parser->isStartTag) {
893       return; # just to be sure this really is an empty tag
894     }
895     $this->out('* * *', true);
896     $this->setLineBreaks(2);
897   }
898   /**
899    * handle <br /> tags
900    *
901    * @param void
902    * @return void
903    */
904   function handleTag_br() {
905     $this->out("  \n".$this->indent, true);
906     $this->parser->html = ltrim($this->parser->html);
907   }
908   /**
909    * node stack, e.g. for <a> and <abbr> tags
910    *
911    * @var array<array>
912    */
913   var $stack = array();
914   /**
915    * add current node to the stack
916    * this only stores the attributes
917    *
918    * @param void
919    * @return void
920    */
921   function stack() {
922     if (!isset($this->stack[$this->parser->tagName])) {
923       $this->stack[$this->parser->tagName] = array();
924     }
925     array_push($this->stack[$this->parser->tagName], $this->parser->tagAttributes);
926   }
927   /**
928    * remove current tag from stack
929    *
930    * @param void
931    * @return array
932    */
933   function unstack() {
934     if (!isset($this->stack[$this->parser->tagName]) || !is_array($this->stack[$this->parser->tagName])) {
935       trigger_error('Trying to unstack from empty stack. This must not happen.', E_USER_ERROR);
936     }
937     return array_pop($this->stack[$this->parser->tagName]);
938   }
939   /**
940    * get last stacked element of type $tagName
941    *
942    * @param string $tagName
943    * @return array
944    */
945   function & getStacked($tagName) {
946     // no end() so it can be referenced
947     return $this->stack[$tagName][count($this->stack[$tagName])-1];
948   }
949   /**
950    * set number of line breaks before next start tag
951    *
952    * @param int $number
953    * @return void
954    */
955   function setLineBreaks($number) {
956     if ($this->lineBreaks < $number) {
957       $this->lineBreaks = $number;
958     }
959   }
960   /**
961    * stores current buffers
962    *
963    * @var array<string>
964    */
965   var $buffer = array();
966   /**
967    * buffer next parser output until unbuffer() is called
968    *
969    * @param void
970    * @return void
971    */
972   function buffer() {
973     array_push($this->buffer, '');
974   }
975   /**
976    * end current buffer and return buffered output
977    *
978    * @param void
979    * @return string
980    */
981   function unbuffer() {
982     return array_pop($this->buffer);
983   }
984   /**
985    * append string to the correct var, either
986    * directly to $this->output or to the current
987    * buffers
988    *
989    * @param string $put
990    * @return void
991    */
992   function out($put, $nowrap = false) {
993     if (empty($put)) {
994       return;
995     }
996     if (!empty($this->buffer)) {
997       $this->buffer[count($this->buffer) - 1] .= $put;
998     } else {
999       if ($this->bodyWidth && !$this->parser->keepWhitespace) { # wrap lines
1000         // get last line
1001         $pos = strrpos($this->output, "\n");
1002         if ($pos === false) {
1003           $line = $this->output;
1004         } else {
1005           $line = substr($this->output, $pos);
1006         }
1007
1008         if ($nowrap) {
1009           if ($put[0] != "\n" && $this->strlen($line) + $this->strlen($put) > $this->bodyWidth) {
1010             $this->output .= "\n".$this->indent.$put;
1011           } else {
1012             $this->output .= $put;
1013           }
1014           return;
1015         } else {
1016           $put .= "\n"; # make sure we get all lines in the while below
1017           $lineLen = $this->strlen($line);
1018           while ($pos = strpos($put, "\n")) {
1019             $putLine = substr($put, 0, $pos+1);
1020             $put = substr($put, $pos+1);
1021             $putLen = $this->strlen($putLine);
1022             if ($lineLen + $putLen < $this->bodyWidth) {
1023               $this->output .= $putLine;
1024               $lineLen = $putLen;
1025             } else {
1026               $split = preg_split('#^(.{0,'.($this->bodyWidth - $lineLen).'})\b#', $putLine, 2, PREG_SPLIT_OFFSET_CAPTURE | PREG_SPLIT_DELIM_CAPTURE);
1027               $this->output .= rtrim($split[1][0])."\n".$this->indent.$this->wordwrap(ltrim($split[2][0]), $this->bodyWidth, "\n".$this->indent, false);
1028             }
1029           }
1030           $this->output = substr($this->output, 0, -1);
1031           return;
1032         }
1033       } else {
1034         $this->output .= $put;
1035       }
1036     }
1037   }
1038   /**
1039    * current indentation
1040    *
1041    * @var string
1042    */
1043   var $indent = '';
1044   /**
1045    * indent next output (start tag) or unindent (end tag)
1046    *
1047    * @param string $str indentation
1048    * @param bool $output add indendation to output
1049    * @return void
1050    */
1051   function indent($str, $output = true) {
1052     if ($this->parser->isStartTag) {
1053       $this->indent .= $str;
1054       if ($output) {
1055         $this->out($str, true);
1056       }
1057     } else {
1058       $this->indent = substr($this->indent, 0, -strlen($str));
1059     }
1060   }
1061   /**
1062    * decode email addresses
1063    *
1064    * @author derernst@gmx.ch <http://www.php.net/manual/en/function.html-entity-decode.php#68536>
1065    * @author Milian Wolff <http://milianw.de>
1066    */
1067   function decode($text, $quote_style = ENT_QUOTES) {
1068     if (version_compare(PHP_VERSION, '5', '>=')) {
1069       # UTF-8 is only supported in PHP 5.x.x and above
1070       $text = html_entity_decode($text, $quote_style, 'UTF-8');
1071     } else {
1072       if (function_exists('html_entity_decode')) {
1073         $text = html_entity_decode($text, $quote_style, 'ISO-8859-1');
1074       } else {
1075         static $trans_tbl;
1076         if (!isset($trans_tbl)) {
1077           $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES, $quote_style));
1078         }
1079         $text = strtr($text, $trans_tbl);
1080       }
1081       $text = preg_replace_callback('~&#x([0-9a-f]+);~i', array(&$this, '_decode_hex'), $text);
1082       $text = preg_replace_callback('~&#(\d{2,5});~', array(&$this, '_decode_numeric'), $text);
1083     }
1084     return $text;
1085   }
1086   /**
1087    * callback for decode() which converts a hexadecimal entity to UTF-8
1088    *
1089    * @param array $matches
1090    * @return string UTF-8 encoded
1091    */
1092   function _decode_hex($matches) {
1093     return $this->unichr(hexdec($matches[1]));
1094   }
1095   /**
1096    * callback for decode() which converts a numerical entity to UTF-8
1097    *
1098    * @param array $matches
1099    * @return string UTF-8 encoded
1100    */
1101   function _decode_numeric($matches) {
1102     return $this->unichr($matches[1]);
1103   }
1104   /**
1105    * UTF-8 chr() which supports numeric entities
1106    *
1107    * @author grey - greywyvern - com <http://www.php.net/manual/en/function.chr.php#55978>
1108    * @param array $matches
1109    * @return string UTF-8 encoded
1110    */
1111   function unichr($dec) {
1112     if ($dec < 128) {
1113       $utf = chr($dec);
1114     } else if ($dec < 2048) {
1115       $utf = chr(192 + (($dec - ($dec % 64)) / 64));
1116       $utf .= chr(128 + ($dec % 64));
1117     } else {
1118       $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
1119       $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
1120       $utf .= chr(128 + ($dec % 64));
1121     }
1122     return $utf;
1123   }
1124   /**
1125    * UTF-8 strlen()
1126    *
1127    * @param string $str
1128    * @return int
1129    *
1130    * @author dtorop 932 at hotmail dot com <http://www.php.net/manual/en/function.strlen.php#37975>
1131    * @author Milian Wolff <http://milianw.de>
1132    */
1133   function strlen($str) {
1134     if (function_exists('mb_strlen')) {
1135       return mb_strlen($str, 'UTF-8');
1136     } else {
1137       return preg_match_all('/[\x00-\x7F\xC0-\xFD]/', $str, $var_empty);
1138     }
1139   }
1140   /**
1141   * wordwrap for utf8 encoded strings
1142   *
1143   * @param string $str
1144   * @param integer $len
1145   * @param string $what
1146   * @return string
1147   */
1148   function wordwrap($str, $width, $break, $cut = false){
1149     if (!$cut) {
1150       $regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){1,'.$width.'}\b#';
1151     } else {
1152       $regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){'.$width.'}#';
1153     }
1154     $return = '';
1155     while (preg_match($regexp, $str, $matches)) {
1156       $string = $matches[0];
1157       $str = ltrim(substr($str, strlen($string)));
1158       if (!$cut && isset($str[0]) && in_array($str[0], array('.', '!', ';', ':', '?', ','))) {
1159         $string .= $str[0];
1160         $str = ltrim(substr($str, 1));
1161       }
1162       $return .= $string.$break;
1163     }
1164     return $return.ltrim($str);
1165   }
1166   /**
1167    * check if current node has a $tagName as parent (somewhere, not only the direct parent)
1168    *
1169    * @param string $tagName
1170    * @return bool
1171    */
1172   function hasParent($tagName) {
1173     return in_array($tagName, $this->parser->openTags);
1174   }
1175   /**
1176    * get tagName of direct parent tag
1177    *
1178    * @param void
1179    * @return string $tagName
1180    */
1181   function parent() {
1182     return end($this->parser->openTags);
1183   }
1184 }