Advertisement
Guest User

Markdown.php

a guest
Jun 12th, 2012
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 49.13 KB | None | 0 0
  1. <?php
  2. #
  3. # Markdown  -  A text-to-HTML conversion tool for web writers
  4. #
  5. # PHP Markdown
  6. # Copyright (c) 2004-2012 Michel Fortin  
  7. # <http://michelf.com/projects/php-markdown/>
  8. #
  9. # Original Markdown
  10. # Copyright (c) 2004-2006 John Gruber  
  11. # <http://daringfireball.net/projects/markdown/>
  12. #
  13.  
  14.  
  15. define( 'MARKDOWN_VERSION',  "1.0.1o" ); # Sun 8 Jan 2012
  16.  
  17.  
  18. #
  19. # Global default settings:
  20. #
  21.  
  22. # Change to ">" for HTML output
  23. @define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX',  " />");
  24.  
  25. # Define the width of a tab for code blocks.
  26. @define( 'MARKDOWN_TAB_WIDTH',     4 );
  27.  
  28.  
  29. #
  30. # WordPress settings:
  31. #
  32.  
  33. # Change to false to remove Markdown from posts and/or comments.
  34. @define( 'MARKDOWN_WP_POSTS',      true );
  35. @define( 'MARKDOWN_WP_COMMENTS',   true );
  36.  
  37.  
  38.  
  39. ### Standard Function Interface ###
  40.  
  41. @define( 'MARKDOWN_PARSER_CLASS',  'Markdown_Parser' );
  42.  
  43. function Markdown($text) {
  44. #
  45. # Initialize the parser and return the result of its transform method.
  46. #
  47.     # Setup static parser variable.
  48.     static $parser;
  49.     if (!isset($parser)) {
  50.         $parser_class = MARKDOWN_PARSER_CLASS;
  51.         $parser = new $parser_class;
  52.     }
  53.  
  54.     # Transform text using parser.
  55.     return $parser->transform($text);
  56. }
  57.  
  58.  
  59. ### WordPress Plugin Interface ###
  60.  
  61. /*
  62. Plugin Name: Markdown
  63. Plugin URI: http://michelf.com/projects/php-markdown/
  64. Description: <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by <a href="http://daringfireball.net/">John Gruber</a>. <a href="http://michelf.com/projects/php-markdown/">More...</a>
  65. Version: 1.0.1o
  66. Author: Michel Fortin
  67. Author URI: http://michelf.com/
  68. */
  69.  
  70. if (isset($wp_version)) {
  71.     # More details about how it works here:
  72.     # <http://michelf.com/weblog/2005/wordpress-text-flow-vs-markdown/>
  73.    
  74.     # Post content and excerpts
  75.     # - Remove WordPress paragraph generator.
  76.     # - Run Markdown on excerpt, then remove all tags.
  77.     # - Add paragraph tag around the excerpt, but remove it for the excerpt rss.
  78.     if (MARKDOWN_WP_POSTS) {
  79.         remove_filter('the_content',     'wpautop');
  80.         remove_filter('the_content_rss', 'wpautop');
  81.         remove_filter('the_excerpt',     'wpautop');
  82.         add_filter('the_content',     'Markdown', 6);
  83.         add_filter('the_content_rss', 'Markdown', 6);
  84.         add_filter('get_the_excerpt', 'Markdown', 6);
  85.         add_filter('get_the_excerpt', 'trim', 7);
  86.         add_filter('the_excerpt',     'mdwp_add_p');
  87.         add_filter('the_excerpt_rss', 'mdwp_strip_p');
  88.        
  89.         remove_filter('content_save_pre',  'balanceTags', 50);
  90.         remove_filter('excerpt_save_pre',  'balanceTags', 50);
  91.         add_filter('the_content',     'balanceTags', 50);
  92.         add_filter('get_the_excerpt', 'balanceTags', 9);
  93.     }
  94.    
  95.     # Comments
  96.     # - Remove WordPress paragraph generator.
  97.     # - Remove WordPress auto-link generator.
  98.     # - Scramble important tags before passing them to the kses filter.
  99.     # - Run Markdown on excerpt then remove paragraph tags.
  100.     if (MARKDOWN_WP_COMMENTS) {
  101.         remove_filter('comment_text', 'wpautop', 30);
  102.         remove_filter('comment_text', 'make_clickable');
  103.         add_filter('pre_comment_content', 'Markdown', 6);
  104.         add_filter('pre_comment_content', 'mdwp_hide_tags', 8);
  105.         add_filter('pre_comment_content', 'mdwp_show_tags', 12);
  106.         add_filter('get_comment_text',    'Markdown', 6);
  107.         add_filter('get_comment_excerpt', 'Markdown', 6);
  108.         add_filter('get_comment_excerpt', 'mdwp_strip_p', 7);
  109.    
  110.         global $mdwp_hidden_tags, $mdwp_placeholders;
  111.         $mdwp_hidden_tags = explode(' ',
  112.             '<p> </p> <pre> </pre> <ol> </ol> <ul> </ul> <li> </li>');
  113.         $mdwp_placeholders = explode(' ', str_rot13(
  114.             'pEj07ZbbBZ U1kqgh4w4p pre2zmeN6K QTi31t9pre ol0MP1jzJR '.
  115.             'ML5IjmbRol ulANi1NsGY J7zRLJqPul liA8ctl16T K9nhooUHli'));
  116.     }
  117.    
  118.     function mdwp_add_p($text) {
  119.         if (!preg_match('{^$|^<(p|ul|ol|dl|pre|blockquote)>}i', $text)) {
  120.             $text = '<p>'.$text.'</p>';
  121.             $text = preg_replace('{\n{2,}}', "</p><p>", $text);
  122.         }
  123.         return $text;
  124.     }
  125.    
  126.     function mdwp_strip_p($t) { return preg_replace('{</?p>}i', '', $t); }
  127.  
  128.     function mdwp_hide_tags($text) {
  129.         global $mdwp_hidden_tags, $mdwp_placeholders;
  130.         return str_replace($mdwp_hidden_tags, $mdwp_placeholders, $text);
  131.     }
  132.     function mdwp_show_tags($text) {
  133.         global $mdwp_hidden_tags, $mdwp_placeholders;
  134.         return str_replace($mdwp_placeholders, $mdwp_hidden_tags, $text);
  135.     }
  136. }
  137.  
  138.  
  139. ### bBlog Plugin Info ###
  140.  
  141. function identify_modifier_markdown() {
  142.     return array(
  143.         'name'          => 'markdown',
  144.         'type'          => 'modifier',
  145.         'nicename'      => 'Markdown',
  146.         'description'   => 'A text-to-HTML conversion tool for web writers',
  147.         'authors'       => 'Michel Fortin and John Gruber',
  148.         'licence'       => 'BSD-like',
  149.         'version'       => MARKDOWN_VERSION,
  150.         'help'          => '<a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by <a href="http://daringfireball.net/">John Gruber</a>. <a href="http://michelf.com/projects/php-markdown/">More...</a>'
  151.     );
  152. }
  153.  
  154.  
  155. ### Smarty Modifier Interface ###
  156.  
  157. function smarty_modifier_markdown($text) {
  158.     return Markdown($text);
  159. }
  160.  
  161.  
  162. ### Textile Compatibility Mode ###
  163.  
  164. # Rename this file to "classTextile.php" and it can replace Textile everywhere.
  165.  
  166. if (strcasecmp(substr(__FILE__, -16), "classTextile.php") == 0) {
  167.     # Try to include PHP SmartyPants. Should be in the same directory.
  168.     @include_once 'smartypants.php';
  169.     # Fake Textile class. It calls Markdown instead.
  170.     class Textile {
  171.         function TextileThis($text, $lite='', $encode='') {
  172.             if ($lite == '' && $encode == '')    $text = Markdown($text);
  173.             if (function_exists('SmartyPants'))  $text = SmartyPants($text);
  174.             return $text;
  175.         }
  176.         # Fake restricted version: restrictions are not supported for now.
  177.         function TextileRestricted($text, $lite='', $noimage='') {
  178.             return $this->TextileThis($text, $lite);
  179.         }
  180.         # Workaround to ensure compatibility with TextPattern 4.0.3.
  181.         function blockLite($text) { return $text; }
  182.     }
  183. }
  184.  
  185.  
  186.  
  187. #
  188. # Markdown Parser Class
  189. #
  190.  
  191. class Markdown_Parser {
  192.  
  193.     # Regex to match balanced [brackets].
  194.     # Needed to insert a maximum bracked depth while converting to PHP.
  195.     var $nested_brackets_depth = 6;
  196.     var $nested_brackets_re;
  197.    
  198.     var $nested_url_parenthesis_depth = 4;
  199.     var $nested_url_parenthesis_re;
  200.  
  201.     # Table of hash values for escaped characters:
  202.     var $escape_chars = '\`*_{}[]()>#+-.!';
  203.     var $escape_chars_re;
  204.  
  205.     # Change to ">" for HTML output.
  206.     var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX;
  207.     var $tab_width = MARKDOWN_TAB_WIDTH;
  208.    
  209.     # Change to `true` to disallow markup or entities.
  210.     var $no_markup = false;
  211.     var $no_entities = false;
  212.    
  213.     # Predefined urls and titles for reference links and images.
  214.     var $predef_urls = array();
  215.     var $predef_titles = array();
  216.  
  217.  
  218.     function Markdown_Parser() {
  219.     #
  220.     # Constructor function. Initialize appropriate member variables.
  221.     #
  222.         $this->_initDetab();
  223.         $this->prepareItalicsAndBold();
  224.    
  225.         $this->nested_brackets_re =
  226.             str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth).
  227.             str_repeat('\])*', $this->nested_brackets_depth);
  228.    
  229.         $this->nested_url_parenthesis_re =
  230.             str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth).
  231.             str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth);
  232.        
  233.         $this->escape_chars_re = '['.preg_quote($this->escape_chars).']';
  234.        
  235.         # Sort document, block, and span gamut in ascendent priority order.
  236.         asort($this->document_gamut);
  237.         asort($this->block_gamut);
  238.         asort($this->span_gamut);
  239.     }
  240.  
  241.  
  242.     # Internal hashes used during transformation.
  243.     var $urls = array();
  244.     var $titles = array();
  245.     var $html_hashes = array();
  246.    
  247.     # Status flag to avoid invalid nesting.
  248.     var $in_anchor = false;
  249.    
  250.    
  251.     function setup() {
  252.     #
  253.     # Called before the transformation process starts to setup parser
  254.     # states.
  255.     #
  256.         # Clear global hashes.
  257.         $this->urls = $this->predef_urls;
  258.         $this->titles = $this->predef_titles;
  259.         $this->html_hashes = array();
  260.        
  261.         $in_anchor = false;
  262.     }
  263.    
  264.     function teardown() {
  265.     #
  266.     # Called after the transformation process to clear any variable
  267.     # which may be taking up memory unnecessarly.
  268.     #
  269.         $this->urls = array();
  270.         $this->titles = array();
  271.         $this->html_hashes = array();
  272.     }
  273.  
  274.  
  275.     function transform($text) {
  276.     #
  277.     # Main function. Performs some preprocessing on the input text
  278.     # and pass it through the document gamut.
  279.     #
  280.         $this->setup();
  281.    
  282.         # Remove UTF-8 BOM and marker character in input, if present.
  283.         $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text);
  284.  
  285.         # Standardize line endings:
  286.         #   DOS to Unix and Mac to Unix
  287.         $text = preg_replace('{\r\n?}', "\n", $text);
  288.  
  289.         # Convert all tabs to spaces.
  290.         $text = $this->detab($text);
  291.  
  292.         # Turn block-level HTML blocks into hash entries
  293.         $text = $this->hashHTMLBlocks($text);
  294.  
  295.         # Strip any lines consisting only of spaces and tabs.
  296.         # This makes subsequent regexen easier to write, because we can
  297.         # match consecutive blank lines with /\n+/ instead of something
  298.         # contorted like /[ ]*\n+/ .
  299.         $text = preg_replace('/^[ ]+$/m', '', $text);
  300.  
  301.         # Run document gamut methods.
  302.         foreach ($this->document_gamut as $method => $priority) {
  303.             $text = $this->$method($text);
  304.         }
  305.        
  306.         $this->teardown();
  307.  
  308.         return $text;
  309.     }
  310.    
  311.     var $document_gamut = array(
  312.         # Strip link definitions, store in hashes.
  313.         "stripLinkDefinitions" => 20,
  314.        
  315.         "runBasicBlockGamut"   => 30,
  316.         );
  317.  
  318.  
  319.     function stripLinkDefinitions($text) {
  320.     #
  321.     # Strips link definitions from text, stores the URLs and titles in
  322.     # hash references.
  323.     #
  324.         $less_than_tab = $this->tab_width - 1;
  325.  
  326.         # Link defs are in the form: ^[id]: url "optional title"
  327.         $text = preg_replace_callback('{
  328.                             ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1
  329.                               [ ]*
  330.                               \n?               # maybe *one* newline
  331.                               [ ]*
  332.                             (?:
  333.                               <(.+?)>           # url = $2
  334.                             |
  335.                               (\S+?)            # url = $3
  336.                             )
  337.                               [ ]*
  338.                               \n?               # maybe one newline
  339.                               [ ]*
  340.                             (?:
  341.                                 (?<=\s)         # lookbehind for whitespace
  342.                                 ["(]
  343.                                 (.*?)           # title = $4
  344.                                 [")]
  345.                                 [ ]*
  346.                             )?  # title is optional
  347.                             (?:\n+|\Z)
  348.             }xm',
  349.             array(&$this, '_stripLinkDefinitions_callback'),
  350.             $text);
  351.         return $text;
  352.     }
  353.     function _stripLinkDefinitions_callback($matches) {
  354.         $link_id = strtolower($matches[1]);
  355.         $url = $matches[2] == '' ? $matches[3] : $matches[2];
  356.         $this->urls[$link_id] = $url;
  357.         $this->titles[$link_id] =& $matches[4];
  358.         return ''; # String that will replace the block
  359.     }
  360.  
  361.  
  362.     function hashHTMLBlocks($text) {
  363.         if ($this->no_markup)  return $text;
  364.  
  365.         $less_than_tab = $this->tab_width - 1;
  366.  
  367.         # Hashify HTML blocks:
  368.         # We only want to do this for block-level HTML tags, such as headers,
  369.         # lists, and tables. That's because we still want to wrap <p>s around
  370.         # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  371.         # phrase emphasis, and spans. The list of tags we're looking for is
  372.         # hard-coded:
  373.         #
  374.         # *  List "a" is made of tags which can be both inline or block-level.
  375.         #    These will be treated block-level when the start tag is alone on
  376.         #    its line, otherwise they're not matched here and will be taken as
  377.         #    inline later.
  378.         # *  List "b" is made of tags which are always block-level;
  379.         #
  380.         $block_tags_a_re = 'ins|del';
  381.         $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'.
  382.                            'script|noscript|form|fieldset|iframe|math';
  383.  
  384.         # Regular expression for the content of a block tag.
  385.         $nested_tags_level = 4;
  386.         $attr = '
  387.             (?>             # optional tag attributes
  388.               \s            # starts with whitespace
  389.               (?>
  390.                 [^>"/]+     # text outside quotes
  391.               |
  392.                 /+(?!>)     # slash not followed by ">"
  393.               |
  394.                 "[^"]*"     # text inside double quotes (tolerate ">")
  395.               |
  396.                 \'[^\']*\'  # text inside single quotes (tolerate ">")
  397.               )*
  398.             )? 
  399.             ';
  400.         $content =
  401.             str_repeat('
  402.                 (?>
  403.                   [^<]+         # content without tag
  404.                 |
  405.                   <\2           # nested opening tag
  406.                     '.$attr.'   # attributes
  407.                     (?>
  408.                       />
  409.                     |
  410.                       >', $nested_tags_level).  # end of opening tag
  411.                       '.*?'.                    # last level nested tag content
  412.             str_repeat('
  413.                       </\2\s*>  # closing nested tag
  414.                     )
  415.                   |            
  416.                     <(?!/\2\s*> # other tags with a different name
  417.                   )
  418.                 )*',
  419.                 $nested_tags_level);
  420.         $content2 = str_replace('\2', '\3', $content);
  421.  
  422.         # First, look for nested blocks, e.g.:
  423.         #   <div>
  424.         #       <div>
  425.         #       tags for inner block must be indented.
  426.         #       </div>
  427.         #   </div>
  428.         #
  429.         # The outermost tags must start at the left margin for this to match, and
  430.         # the inner nested divs must be indented.
  431.         # We need to do this before the next, more liberal match, because the next
  432.         # match will start at the first `<div>` and stop at the first `</div>`.
  433.         $text = preg_replace_callback('{(?>
  434.             (?>
  435.                 (?<=\n\n)       # Starting after a blank line
  436.                 |               # or
  437.                 \A\n?           # the beginning of the doc
  438.             )
  439.             (                       # save in $1
  440.  
  441.               # Match from `\n<tag>` to `</tag>\n`, handling nested tags
  442.               # in between.
  443.                    
  444.                         [ ]{0,'.$less_than_tab.'}
  445.                         <('.$block_tags_b_re.')# start tag = $2
  446.                         '.$attr.'>          # attributes followed by > and \n
  447.                         '.$content.'        # content, support nesting
  448.                         </\2>               # the matching end tag
  449.                         [ ]*                # trailing spaces/tabs
  450.                         (?=\n+|\Z)  # followed by a newline or end of document
  451.  
  452.             | # Special version for tags of group a.
  453.  
  454.                         [ ]{0,'.$less_than_tab.'}
  455.                         <('.$block_tags_a_re.')# start tag = $3
  456.                         '.$attr.'>[ ]*\n    # attributes followed by >
  457.                         '.$content2.'       # content, support nesting
  458.                         </\3>               # the matching end tag
  459.                         [ ]*                # trailing spaces/tabs
  460.                         (?=\n+|\Z)  # followed by a newline or end of document
  461.                    
  462.             | # Special case just for <hr />. It was easier to make a special
  463.               # case than to make the other regex more complicated.
  464.            
  465.                         [ ]{0,'.$less_than_tab.'}
  466.                         <(hr)               # start tag = $2
  467.                         '.$attr.'           # attributes
  468.                         /?>                 # the matching end tag
  469.                         [ ]*
  470.                         (?=\n{2,}|\Z)       # followed by a blank line or end of document
  471.            
  472.             | # Special case for standalone HTML comments:
  473.            
  474.                     [ ]{0,'.$less_than_tab.'}
  475.                     (?s:
  476.                         <!-- .*? -->
  477.                     )
  478.                     [ ]*
  479.                     (?=\n{2,}|\Z)       # followed by a blank line or end of document
  480.            
  481.             | # PHP and ASP-style processor instructions (<? and <%)
  482.            
  483.                     [ ]{0,'.$less_than_tab.'}
  484.                     (?s:
  485.                         <([?%])         # $2
  486.                         .*?
  487.                         \2>
  488.                     )
  489.                     [ ]*
  490.                     (?=\n{2,}|\Z)       # followed by a blank line or end of document
  491.                    
  492.             )
  493.             )}Sxmi',
  494.             array(&$this, '_hashHTMLBlocks_callback'),
  495.             $text);
  496.  
  497.         return $text;
  498.     }
  499.     function _hashHTMLBlocks_callback($matches) {
  500.         $text = $matches[1];
  501.         $key  = $this->hashBlock($text);
  502.         return "$key";
  503.     }
  504.    
  505.    
  506.     function hashPart($text, $boundary = 'X') {
  507.     #
  508.     # Called whenever a tag must be hashed when a function insert an atomic
  509.     # element in the text stream. Passing $text to through this function gives
  510.     # a unique text-token which will be reverted back when calling unhash.
  511.     #
  512.     # The $boundary argument specify what character should be used to surround
  513.     # the token. By convension, "B" is used for block elements that needs not
  514.     # to be wrapped into paragraph tags at the end, ":" is used for elements
  515.     # that are word separators and "X" is used in the general case.
  516.     #
  517.         # Swap back any tag hash found in $text so we do not have to `unhash`
  518.         # multiple times at the end.
  519.         $text = $this->unhash($text);
  520.        
  521.         # Then hash the block.
  522.         static $i = 0;
  523.         $key = "$boundary\x1A" . ++$i . $boundary;
  524.         $this->html_hashes[$key] = $text;
  525.         return $key; # String that will replace the tag.
  526.     }
  527.  
  528.  
  529.     function hashBlock($text) {
  530.     #
  531.     # Shortcut function for hashPart with block-level boundaries.
  532.     #
  533.         return $this->hashPart($text, 'B');
  534.     }
  535.  
  536.  
  537.     var $block_gamut = array(
  538.     #
  539.     # These are all the transformations that form block-level
  540.     # tags like paragraphs, headers, and list items.
  541.     #
  542.         "doHeaders"         => 10,
  543.         "doHorizontalRules" => 20,
  544.        
  545.         "doLists"           => 40,
  546.         "doCodeBlocks"      => 50,
  547.         "doBlockQuotes"     => 60,
  548.         );
  549.  
  550.     function runBlockGamut($text) {
  551.     #
  552.     # Run block gamut tranformations.
  553.     #
  554.         # We need to escape raw HTML in Markdown source before doing anything
  555.         # else. This need to be done for each block, and not only at the
  556.         # begining in the Markdown function since hashed blocks can be part of
  557.         # list items and could have been indented. Indented blocks would have
  558.         # been seen as a code block in a previous pass of hashHTMLBlocks.
  559.         $text = $this->hashHTMLBlocks($text);
  560.        
  561.         return $this->runBasicBlockGamut($text);
  562.     }
  563.    
  564.     function runBasicBlockGamut($text) {
  565.     #
  566.     # Run block gamut tranformations, without hashing HTML blocks. This is
  567.     # useful when HTML blocks are known to be already hashed, like in the first
  568.     # whole-document pass.
  569.     #
  570.         foreach ($this->block_gamut as $method => $priority) {
  571.             $text = $this->$method($text);
  572.         }
  573.        
  574.         # Finally form paragraph and restore hashed blocks.
  575.         $text = $this->formParagraphs($text);
  576.  
  577.         return $text;
  578.     }
  579.    
  580.    
  581.     function doHorizontalRules($text) {
  582.         # Do Horizontal Rules:
  583.         return preg_replace(
  584.             '{
  585.                 ^[ ]{0,3}   # Leading space
  586.                 ([-*_])     # $1: First marker
  587.                 (?>         # Repeated marker group
  588.                     [ ]{0,2}    # Zero, one, or two spaces.
  589.                     \1          # Marker character
  590.                 ){2,}       # Group repeated at least twice
  591.                 [ ]*        # Tailing spaces
  592.                 $           # End of line.
  593.             }mx',
  594.             $this->hashBlock("<hr$this->empty_element_suffix"),
  595.             $text);
  596.     }
  597.  
  598.  
  599.     var $span_gamut = array(
  600.     #
  601.     # These are all the transformations that occur *within* block-level
  602.     # tags like paragraphs, headers, and list items.
  603.     #
  604.         # Process character escapes, code spans, and inline HTML
  605.         # in one shot.
  606.         "parseSpan"           => -30,
  607.  
  608.         # Process anchor and image tags. Images must come first,
  609.         # because ![foo][f] looks like an anchor.
  610.         "doImages"            =>  10,
  611.         "doAnchors"           =>  20,
  612.        
  613.         # Make links out of things like `<http://example.com/>`
  614.         # Must come after doAnchors, because you can use < and >
  615.         # delimiters in inline links like [this](<url>).
  616.         "doAutoLinks"         =>  30,
  617.         "encodeAmpsAndAngles" =>  40,
  618.  
  619.         "doItalicsAndBold"    =>  50,
  620.         "doHardBreaks"        =>  60,
  621.         );
  622.  
  623.     function runSpanGamut($text) {
  624.     #
  625.     # Run span gamut tranformations.
  626.     #
  627.         foreach ($this->span_gamut as $method => $priority) {
  628.             $text = $this->$method($text);
  629.         }
  630.  
  631.         return $text;
  632.     }
  633.    
  634.    
  635.     function doHardBreaks($text) {
  636.         # Do hard breaks:
  637.         return preg_replace_callback('/ {2,}\n/',
  638.             array(&$this, '_doHardBreaks_callback'), $text);
  639.     }
  640.     function _doHardBreaks_callback($matches) {
  641.         return $this->hashPart("<br$this->empty_element_suffix");
  642.     }
  643.  
  644.  
  645.     function doAnchors($text) {
  646.     #
  647.     # Turn Markdown link shortcuts into XHTML <a> tags.
  648.     #
  649.         if ($this->in_anchor) return $text;
  650.         $this->in_anchor = true;
  651.        
  652.         #
  653.         # First, handle reference-style links: [link text] [id]
  654.         #
  655.         $text = preg_replace_callback('{
  656.             (                   # wrap whole match in $1
  657.               \[
  658.                 ('.$this->nested_brackets_re.') # link text = $2
  659.               \]
  660.  
  661.               [ ]?              # one optional space
  662.               (?:\n[ ]*)?       # one optional newline followed by spaces
  663.  
  664.               \[
  665.                 (.*?)       # id = $3
  666.               \]
  667.             )
  668.             }xs',
  669.             array(&$this, '_doAnchors_reference_callback'), $text);
  670.  
  671.         #
  672.         # Next, inline-style links: [link text](url "optional title")
  673.         #
  674.         $text = preg_replace_callback('{
  675.             (               # wrap whole match in $1
  676.               \[
  677.                 ('.$this->nested_brackets_re.') # link text = $2
  678.               \]
  679.               \(            # literal paren
  680.                 [ \n]*
  681.                 (?:
  682.                     <(.+?)> # href = $3
  683.                 |
  684.                     ('.$this->nested_url_parenthesis_re.')  # href = $4
  685.                 )
  686.                 [ \n]*
  687.                 (           # $5
  688.                   ([\'"])   # quote char = $6
  689.                   (.*?)     # Title = $7
  690.                   \6        # matching quote
  691.                   [ \n]*    # ignore any spaces/tabs between closing quote and )
  692.                 )?          # title is optional
  693.               \)
  694.             )
  695.             }xs',
  696.             array(&$this, '_doAnchors_inline_callback'), $text);
  697.  
  698.         #
  699.         # Last, handle reference-style shortcuts: [link text]
  700.         # These must come last in case you've also got [link text][1]
  701.         # or [link text](/foo)
  702.         #
  703.         $text = preg_replace_callback('{
  704.             (                   # wrap whole match in $1
  705.               \[
  706.                 ([^\[\]]+)      # link text = $2; can\'t contain [ or ]
  707.               \]
  708.             )
  709.             }xs',
  710.             array(&$this, '_doAnchors_reference_callback'), $text);
  711.  
  712.         $this->in_anchor = false;
  713.         return $text;
  714.     }
  715.     function _doAnchors_reference_callback($matches) {
  716.         $whole_match =  $matches[1];
  717.         $link_text   =  $matches[2];
  718.         $link_id     =& $matches[3];
  719.  
  720.         if ($link_id == "") {
  721.             # for shortcut links like [this][] or [this].
  722.             $link_id = $link_text;
  723.         }
  724.        
  725.         # lower-case and turn embedded newlines into spaces
  726.         $link_id = strtolower($link_id);
  727.         $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
  728.  
  729.         if (isset($this->urls[$link_id])) {
  730.             $url = $this->urls[$link_id];
  731.             $url = $this->encodeAttribute($url);
  732.            
  733.             $result = "<a href=\"$url\"";
  734.             if ( isset( $this->titles[$link_id] ) ) {
  735.                 $title = $this->titles[$link_id];
  736.                 $title = $this->encodeAttribute($title);
  737.                 $result .=  " title=\"$title\"";
  738.             }
  739.        
  740.             $link_text = $this->runSpanGamut($link_text);
  741.             $result .= ">$link_text</a>";
  742.             $result = $this->hashPart($result);
  743.         }
  744.         else {
  745.             $result = $whole_match;
  746.         }
  747.         return $result;
  748.     }
  749.     function _doAnchors_inline_callback($matches) {
  750.         $whole_match    =  $matches[1];
  751.         $link_text      =  $this->runSpanGamut($matches[2]);
  752.         $url            =  $matches[3] == '' ? $matches[4] : $matches[3];
  753.         $title          =& $matches[7];
  754.  
  755.         $url = $this->encodeAttribute($url);
  756.  
  757.         $result = "<a href=\"$url\"";
  758.         if (isset($title)) {
  759.             $title = $this->encodeAttribute($title);
  760.             $result .=  " title=\"$title\"";
  761.         }
  762.        
  763.         $link_text = $this->runSpanGamut($link_text);
  764.         $result .= ">$link_text</a>";
  765.  
  766.         return $this->hashPart($result);
  767.     }
  768.  
  769.  
  770.     function doImages($text) {
  771.     #
  772.     # Turn Markdown image shortcuts into <img> tags.
  773.     #
  774.         #
  775.         # First, handle reference-style labeled images: ![alt text][id]
  776.         #
  777.         $text = preg_replace_callback('{
  778.             (               # wrap whole match in $1
  779.               !\[
  780.                 ('.$this->nested_brackets_re.')     # alt text = $2
  781.               \]
  782.  
  783.               [ ]?              # one optional space
  784.               (?:\n[ ]*)?       # one optional newline followed by spaces
  785.  
  786.               \[
  787.                 (.*?)       # id = $3
  788.               \]
  789.  
  790.             )
  791.             }xs',
  792.             array(&$this, '_doImages_reference_callback'), $text);
  793.  
  794.         #
  795.         # Next, handle inline images:  ![alt text](url "optional title")
  796.         # Don't forget: encode * and _
  797.         #
  798.         $text = preg_replace_callback('{
  799.             (               # wrap whole match in $1
  800.               !\[
  801.                 ('.$this->nested_brackets_re.')     # alt text = $2
  802.               \]
  803.               \s?           # One optional whitespace character
  804.               \(            # literal paren
  805.                 [ \n]*
  806.                 (?:
  807.                     <(\S*)> # src url = $3
  808.                 |
  809.                     ('.$this->nested_url_parenthesis_re.')  # src url = $4
  810.                 )
  811.                 [ \n]*
  812.                 (           # $5
  813.                   ([\'"])   # quote char = $6
  814.                   (.*?)     # title = $7
  815.                   \6        # matching quote
  816.                   [ \n]*
  817.                 )?          # title is optional
  818.               \)
  819.             )
  820.             }xs',
  821.             array(&$this, '_doImages_inline_callback'), $text);
  822.  
  823.         return $text;
  824.     }
  825.     function _doImages_reference_callback($matches) {
  826.         $whole_match = $matches[1];
  827.         $alt_text    = $matches[2];
  828.         $link_id     = strtolower($matches[3]);
  829.  
  830.         if ($link_id == "") {
  831.             $link_id = strtolower($alt_text); # for shortcut links like ![this][].
  832.         }
  833.  
  834.         $alt_text = $this->encodeAttribute($alt_text);
  835.         if (isset($this->urls[$link_id])) {
  836.             $url = $this->encodeAttribute($this->urls[$link_id]);
  837.             $result = "<img src=\"$url\" alt=\"$alt_text\"";
  838.             if (isset($this->titles[$link_id])) {
  839.                 $title = $this->titles[$link_id];
  840.                 $title = $this->encodeAttribute($title);
  841.                 $result .=  " title=\"$title\"";
  842.             }
  843.             $result .= $this->empty_element_suffix;
  844.             $result = $this->hashPart($result);
  845.         }
  846.         else {
  847.             # If there's no such link ID, leave intact:
  848.             $result = $whole_match;
  849.         }
  850.  
  851.         return $result;
  852.     }
  853.     function _doImages_inline_callback($matches) {
  854.         $whole_match    = $matches[1];
  855.         $alt_text       = $matches[2];
  856.         $url            = $matches[3] == '' ? $matches[4] : $matches[3];
  857.         $title          =& $matches[7];
  858.  
  859.         $alt_text = $this->encodeAttribute($alt_text);
  860.         $url = $this->encodeAttribute($url);
  861.         $result = "<img src=\"$url\" alt=\"$alt_text\"";
  862.         if (isset($title)) {
  863.             $title = $this->encodeAttribute($title);
  864.             $result .=  " title=\"$title\""; # $title already quoted
  865.         }
  866.         $result .= $this->empty_element_suffix;
  867.  
  868.         return $this->hashPart($result);
  869.     }
  870.  
  871.  
  872.     function doHeaders($text) {
  873.         # Setext-style headers:
  874.         #     Header 1
  875.         #     ========
  876.         #  
  877.         #     Header 2
  878.         #     --------
  879.         #
  880.         $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx',
  881.             array(&$this, '_doHeaders_callback_setext'), $text);
  882.  
  883.         # atx-style headers:
  884.         #   # Header 1
  885.         #   ## Header 2
  886.         #   ## Header 2 with closing hashes ##
  887.         #   ...
  888.         #   ###### Header 6
  889.         #
  890.         $text = preg_replace_callback('{
  891.                 ^(\#{1,6})  # $1 = string of #\'s
  892.                 [ ]*
  893.                 (.+?)       # $2 = Header text
  894.                 [ ]*
  895.                 \#*         # optional closing #\'s (not counted)
  896.                 \n+
  897.             }xm',
  898.             array(&$this, '_doHeaders_callback_atx'), $text);
  899.  
  900.         return $text;
  901.     }
  902.     function _doHeaders_callback_setext($matches) {
  903.         # Terrible hack to check we haven't found an empty list item.
  904.         if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1]))
  905.             return $matches[0];
  906.        
  907.         $level = $matches[2]{0} == '=' ? 1 : 2;
  908.         $block = "<h$level>".$this->runSpanGamut($matches[1])."</h$level>";
  909.         return $this->hashBlock($block);
  910.     }
  911.     function _doHeaders_callback_atx($matches) {
  912.         $level = strlen($matches[1]);
  913.         $block = "<h$level>".$this->runSpanGamut($matches[2])."</h$level>";
  914.         return $this->hashBlock($block);
  915.     }
  916.  
  917.  
  918.     function doLists($text) {
  919.     #
  920.     # Form HTML ordered (numbered) and unordered (bulleted) lists.
  921.     #
  922.         $less_than_tab = $this->tab_width - 1;
  923.  
  924.         # Re-usable patterns to match list item bullets and number markers:
  925.         $marker_ul_re  = '[*+-]';
  926.         $marker_ol_re  = '\d+[\.]';
  927.         $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  928.  
  929.         $markers_relist = array(
  930.             $marker_ul_re => $marker_ol_re,
  931.             $marker_ol_re => $marker_ul_re,
  932.             );
  933.  
  934.         foreach ($markers_relist as $marker_re => $other_marker_re) {
  935.             # Re-usable pattern to match any entirel ul or ol list:
  936.             $whole_list_re = '
  937.                 (                               # $1 = whole list
  938.                   (                             # $2
  939.                     ([ ]{0,'.$less_than_tab.'}) # $3 = number of spaces
  940.                     ('.$marker_re.')            # $4 = first list item marker
  941.                     [ ]+
  942.                   )
  943.                   (?s:.+?)
  944.                   (                             # $5
  945.                       \z
  946.                     |
  947.                       \n{2,}
  948.                       (?=\S)
  949.                       (?!                       # Negative lookahead for another list item marker
  950.                         [ ]*
  951.                         '.$marker_re.'[ ]+
  952.                       )
  953.                     |
  954.                       (?=                       # Lookahead for another kind of list
  955.                         \n
  956.                         \3                      # Must have the same indentation
  957.                         '.$other_marker_re.'[ ]+
  958.                       )
  959.                   )
  960.                 )
  961.             '; // mx
  962.            
  963.             # We use a different prefix before nested lists than top-level lists.
  964.             # See extended comment in _ProcessListItems().
  965.        
  966.             if ($this->list_level) {
  967.                 $text = preg_replace_callback('{
  968.                         ^
  969.                         '.$whole_list_re.'
  970.                     }mx',
  971.                     array(&$this, '_doLists_callback'), $text);
  972.             }
  973.             else {
  974.                 $text = preg_replace_callback('{
  975.                         (?:(?<=\n)\n|\A\n?) # Must eat the newline
  976.                         '.$whole_list_re.'
  977.                     }mx',
  978.                     array(&$this, '_doLists_callback'), $text);
  979.             }
  980.         }
  981.  
  982.         return $text;
  983.     }
  984.     function _doLists_callback($matches) {
  985.         # Re-usable patterns to match list item bullets and number markers:
  986.         $marker_ul_re  = '[*+-]';
  987.         $marker_ol_re  = '\d+[\.]';
  988.         $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  989.        
  990.         $list = $matches[1];
  991.         $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol";
  992.        
  993.         $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re );
  994.        
  995.         $list .= "\n";
  996.         $result = $this->processListItems($list, $marker_any_re);
  997.        
  998.         $result = $this->hashBlock("<$list_type>" . $result . "</$list_type>");
  999.         return $result;
  1000.     }
  1001.  
  1002.     var $list_level = 0;
  1003.  
  1004.     function processListItems($list_str, $marker_any_re) {
  1005.     #
  1006.     #   Process the contents of a single ordered or unordered list, splitting it
  1007.     #   into individual list items.
  1008.     #
  1009.         # The $this->list_level global keeps track of when we're inside a list.
  1010.         # Each time we enter a list, we increment it; when we leave a list,
  1011.         # we decrement. If it's zero, we're not in a list anymore.
  1012.         #
  1013.         # We do this because when we're not inside a list, we want to treat
  1014.         # something like this:
  1015.         #
  1016.         #       I recommend upgrading to version
  1017.         #       8. Oops, now this line is treated
  1018.         #       as a sub-list.
  1019.         #
  1020.         # As a single paragraph, despite the fact that the second line starts
  1021.         # with a digit-period-space sequence.
  1022.         #
  1023.         # Whereas when we're inside a list (or sub-list), that line will be
  1024.         # treated as the start of a sub-list. What a kludge, huh? This is
  1025.         # an aspect of Markdown's syntax that's hard to parse perfectly
  1026.         # without resorting to mind-reading. Perhaps the solution is to
  1027.         # change the syntax rules such that sub-lists must start with a
  1028.         # starting cardinal number; e.g. "1." or "a.".
  1029.        
  1030.         $this->list_level++;
  1031.  
  1032.         # trim trailing blank lines:
  1033.         $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  1034.  
  1035.         $list_str = preg_replace_callback('{
  1036.             (\n)?                           # leading line = $1
  1037.             (^[ ]*)                         # leading whitespace = $2
  1038.             ('.$marker_any_re.'             # list marker and space = $3
  1039.                 (?:[ ]+|(?=\n)) # space only required if item is not empty
  1040.             )
  1041.             ((?s:.*?))                      # list item text   = $4
  1042.             (?:(\n+(?=\n))|\n)              # tailing blank line = $5
  1043.             (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n))))
  1044.             }xm',
  1045.             array(&$this, '_processListItems_callback'), $list_str);
  1046.  
  1047.         $this->list_level--;
  1048.         return $list_str;
  1049.     }
  1050.     function _processListItems_callback($matches) {
  1051.         $item = $matches[4];
  1052.         $leading_line =& $matches[1];
  1053.         $leading_space =& $matches[2];
  1054.         $marker_space = $matches[3];
  1055.         $tailing_blank_line =& $matches[5];
  1056.  
  1057.         if ($leading_line || $tailing_blank_line ||
  1058.             preg_match('/\n{2,}/', $item))
  1059.         {
  1060.             # Replace marker with the appropriate whitespace indentation
  1061.             $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;
  1062.             $item = $this->runBlockGamut($this->outdent($item)."\n");
  1063.         }
  1064.         else {
  1065.             # Recursion for sub-lists:
  1066.             $item = $this->doLists($this->outdent($item));
  1067.             $item = preg_replace('/\n+$/', '', $item);
  1068.             $item = $this->runSpanGamut($item);
  1069.         }
  1070.  
  1071.         return "<li>" . $item . "</li>";
  1072.     }
  1073.  
  1074.  
  1075.     function doCodeBlocks($text) {
  1076.     #
  1077.     #   Process Markdown `<pre><code>` blocks.
  1078.     #
  1079.         $text = preg_replace_callback('{
  1080.                 (?:\n\n|\A\n?)
  1081.                 (               # $1 = the code block -- one or more lines, starting with a space/tab
  1082.                   (?>
  1083.                     [ ]{'.$this->tab_width.'}  # Lines must start with a tab or a tab-width of spaces
  1084.                     .*\n+
  1085.                   )+
  1086.                 )
  1087.                 ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
  1088.             }xm',
  1089.             array(&$this, '_doCodeBlocks_callback'), $text);
  1090.  
  1091.         return $text;
  1092.     }
  1093.     function _doCodeBlocks_callback($matches) {
  1094.         $codeblock = $matches[1];
  1095.  
  1096.         $codeblock = $this->outdent($codeblock);
  1097.         $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
  1098.  
  1099.         # trim leading newlines and trailing newlines
  1100.         $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
  1101.  
  1102.         $codeblock = "<pre><code>$codeblock</code></pre>";
  1103.         return $this->hashBlock($codeblock);
  1104.     }
  1105.  
  1106.  
  1107.     function makeCodeSpan($code) {
  1108.     #
  1109.     # Create a code span markup for $code. Called from handleSpanToken.
  1110.     #
  1111.         $code = htmlspecialchars(trim($code), ENT_NOQUOTES);
  1112.         return $this->hashPart("<code>$code</code>");
  1113.     }
  1114.  
  1115.  
  1116.     var $em_relist = array(
  1117.         ''  => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S|$)(?![\.,:;]\s)',
  1118.         '*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
  1119.         '_' => '(?<=\S|^)(?<!_)_(?!_)',
  1120.         );
  1121.     var $strong_relist = array(
  1122.         ''   => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S|$)(?![\.,:;]\s)',
  1123.         '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
  1124.         '__' => '(?<=\S|^)(?<!_)__(?!_)',
  1125.         );
  1126.     var $em_strong_relist = array(
  1127.         ''    => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S|$)(?![\.,:;]\s)',
  1128.         '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
  1129.         '___' => '(?<=\S|^)(?<!_)___(?!_)',
  1130.         );
  1131.     var $em_strong_prepared_relist;
  1132.    
  1133.     function prepareItalicsAndBold() {
  1134.     #
  1135.     # Prepare regular expressions for searching emphasis tokens in any
  1136.     # context.
  1137.     #
  1138.         foreach ($this->em_relist as $em => $em_re) {
  1139.             foreach ($this->strong_relist as $strong => $strong_re) {
  1140.                 # Construct list of allowed token expressions.
  1141.                 $token_relist = array();
  1142.                 if (isset($this->em_strong_relist["$em$strong"])) {
  1143.                     $token_relist[] = $this->em_strong_relist["$em$strong"];
  1144.                 }
  1145.                 $token_relist[] = $em_re;
  1146.                 $token_relist[] = $strong_re;
  1147.                
  1148.                 # Construct master expression from list.
  1149.                 $token_re = '{('. implode('|', $token_relist) .')}';
  1150.                 $this->em_strong_prepared_relist["$em$strong"] = $token_re;
  1151.             }
  1152.         }
  1153.     }
  1154.    
  1155.     function doItalicsAndBold($text) {
  1156.         $token_stack = array('');
  1157.         $text_stack = array('');
  1158.         $em = '';
  1159.         $strong = '';
  1160.         $tree_char_em = false;
  1161.        
  1162.         while (1) {
  1163.             #
  1164.             # Get prepared regular expression for seraching emphasis tokens
  1165.             # in current context.
  1166.             #
  1167.             $token_re = $this->em_strong_prepared_relist["$em$strong"];
  1168.            
  1169.             #
  1170.             # Each loop iteration search for the next emphasis token.
  1171.             # Each token is then passed to handleSpanToken.
  1172.             #
  1173.             $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
  1174.             $text_stack[0] .= $parts[0];
  1175.             $token =& $parts[1];
  1176.             $text =& $parts[2];
  1177.            
  1178.             if (empty($token)) {
  1179.                 # Reached end of text span: empty stack without emitting.
  1180.                 # any more emphasis.
  1181.                 while ($token_stack[0]) {
  1182.                     $text_stack[1] .= array_shift($token_stack);
  1183.                     $text_stack[0] .= array_shift($text_stack);
  1184.                 }
  1185.                 break;
  1186.             }
  1187.            
  1188.             $token_len = strlen($token);
  1189.             if ($tree_char_em) {
  1190.                 # Reached closing marker while inside a three-char emphasis.
  1191.                 if ($token_len == 3) {
  1192.                     # Three-char closing marker, close em and strong.
  1193.                     array_shift($token_stack);
  1194.                     $span = array_shift($text_stack);
  1195.                     $span = $this->runSpanGamut($span);
  1196.                     $span = "<strong><em>$span</em></strong>";
  1197.                     $text_stack[0] .= $this->hashPart($span);
  1198.                     $em = '';
  1199.                     $strong = '';
  1200.                 } else {
  1201.                     # Other closing marker: close one em or strong and
  1202.                     # change current token state to match the other
  1203.                     $token_stack[0] = str_repeat($token{0}, 3-$token_len);
  1204.                     $tag = $token_len == 2 ? "strong" : "em";
  1205.                     $span = $text_stack[0];
  1206.                     $span = $this->runSpanGamut($span);
  1207.                     $span = "<$tag>$span</$tag>";
  1208.                     $text_stack[0] = $this->hashPart($span);
  1209.                     $$tag = ''; # $$tag stands for $em or $strong
  1210.                 }
  1211.                 $tree_char_em = false;
  1212.             } else if ($token_len == 3) {
  1213.                 if ($em) {
  1214.                     # Reached closing marker for both em and strong.
  1215.                     # Closing strong marker:
  1216.                     for ($i = 0; $i < 2; ++$i) {
  1217.                         $shifted_token = array_shift($token_stack);
  1218.                         $tag = strlen($shifted_token) == 2 ? "strong" : "em";
  1219.                         $span = array_shift($text_stack);
  1220.                         $span = $this->runSpanGamut($span);
  1221.                         $span = "<$tag>$span</$tag>";
  1222.                         $text_stack[0] .= $this->hashPart($span);
  1223.                         $$tag = ''; # $$tag stands for $em or $strong
  1224.                     }
  1225.                 } else {
  1226.                     # Reached opening three-char emphasis marker. Push on token
  1227.                     # stack; will be handled by the special condition above.
  1228.                     $em = $token{0};
  1229.                     $strong = "$em$em";
  1230.                     array_unshift($token_stack, $token);
  1231.                     array_unshift($text_stack, '');
  1232.                     $tree_char_em = true;
  1233.                 }
  1234.             } else if ($token_len == 2) {
  1235.                 if ($strong) {
  1236.                     # Unwind any dangling emphasis marker:
  1237.                     if (strlen($token_stack[0]) == 1) {
  1238.                         $text_stack[1] .= array_shift($token_stack);
  1239.                         $text_stack[0] .= array_shift($text_stack);
  1240.                     }
  1241.                     # Closing strong marker:
  1242.                     array_shift($token_stack);
  1243.                     $span = array_shift($text_stack);
  1244.                     $span = $this->runSpanGamut($span);
  1245.                     $span = "<strong>$span</strong>";
  1246.                     $text_stack[0] .= $this->hashPart($span);
  1247.                     $strong = '';
  1248.                 } else {
  1249.                     array_unshift($token_stack, $token);
  1250.                     array_unshift($text_stack, '');
  1251.                     $strong = $token;
  1252.                 }
  1253.             } else {
  1254.                 # Here $token_len == 1
  1255.                 if ($em) {
  1256.                     if (strlen($token_stack[0]) == 1) {
  1257.                         # Closing emphasis marker:
  1258.                         array_shift($token_stack);
  1259.                         $span = array_shift($text_stack);
  1260.                         $span = $this->runSpanGamut($span);
  1261.                         $span = "<em>$span</em>";
  1262.                         $text_stack[0] .= $this->hashPart($span);
  1263.                         $em = '';
  1264.                     } else {
  1265.                         $text_stack[0] .= $token;
  1266.                     }
  1267.                 } else {
  1268.                     array_unshift($token_stack, $token);
  1269.                     array_unshift($text_stack, '');
  1270.                     $em = $token;
  1271.                 }
  1272.             }
  1273.         }
  1274.         return $text_stack[0];
  1275.     }
  1276.  
  1277.  
  1278.     function doBlockQuotes($text) {
  1279.         $text = preg_replace_callback('/
  1280.               (                             # Wrap whole match in $1
  1281.                 (?>
  1282.                   ^[ ]*>[ ]?            # ">" at the start of a line
  1283.                     .+\n                    # rest of the first line
  1284.                   (.+\n)*                   # subsequent consecutive lines
  1285.                   \n*                       # blanks
  1286.                 )+
  1287.               )
  1288.             /xm',
  1289.             array(&$this, '_doBlockQuotes_callback'), $text);
  1290.  
  1291.         return $text;
  1292.     }
  1293.     function _doBlockQuotes_callback($matches) {
  1294.         $bq = $matches[1];
  1295.         # trim one level of quoting - trim whitespace-only lines
  1296.         $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
  1297.         $bq = $this->runBlockGamut($bq);        # recurse
  1298.  
  1299.         $bq = preg_replace('/^/m', "  ", $bq);
  1300.         # These leading spaces cause problem with <pre> content,
  1301.         # so we need to fix that:
  1302.         $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx',
  1303.             array(&$this, '_doBlockQuotes_callback2'), $bq);
  1304.  
  1305.         return $this->hashBlock("<blockquote>$bq</blockquote>");
  1306.     }
  1307.     function _doBlockQuotes_callback2($matches) {
  1308.         $pre = $matches[1];
  1309.         $pre = preg_replace('/^  /m', '', $pre);
  1310.         return $pre;
  1311.     }
  1312.  
  1313.  
  1314.     function formParagraphs($text) {
  1315.     #
  1316.     #   Params:
  1317.     #       $text - string to process with html <p> tags
  1318.     #
  1319.         # Strip leading and trailing lines:
  1320.         $text = preg_replace('/\A\n+|\n+\z/', '', $text);
  1321.  
  1322.         $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
  1323.  
  1324.         #
  1325.         # Wrap <p> tags and unhashify HTML blocks
  1326.         #
  1327.         foreach ($grafs as $key => $value) {
  1328.             if (!preg_match('/^B\x1A[0-9]+B$/', $value)) {
  1329.                 # Is a paragraph.
  1330.                 $value = $this->runSpanGamut($value);
  1331.                 $value = preg_replace('/^([ ]*)/', "<p>", $value);
  1332.                 $value .= "</p>";
  1333.                 $grafs[$key] = $this->unhash($value);
  1334.             }
  1335.             else {
  1336.                 # Is a block.
  1337.                 # Modify elements of @grafs in-place...
  1338.                 $graf = $value;
  1339.                 $block = $this->html_hashes[$graf];
  1340.                 $graf = $block;
  1341. //              if (preg_match('{
  1342. //                  \A
  1343. //                  (                           # $1 = <div> tag
  1344. //                    <div  \s+
  1345. //                    [^>]*
  1346. //                    \b
  1347. //                    markdown\s*=\s*  ([\'"])  #   $2 = attr quote char
  1348. //                    1
  1349. //                    \2
  1350. //                    [^>]*
  1351. //                    >
  1352. //                  )
  1353. //                  (                           # $3 = contents
  1354. //                  .*
  1355. //                  )
  1356. //                  (</div>)                    # $4 = closing tag
  1357. //                  \z
  1358. //                  }xs', $block, $matches))
  1359. //              {
  1360. //                  list(, $div_open, , $div_content, $div_close) = $matches;
  1361. //
  1362. //                  # We can't call Markdown(), because that resets the hash;
  1363. //                  # that initialization code should be pulled into its own sub, though.
  1364. //                  $div_content = $this->hashHTMLBlocks($div_content);
  1365. //                 
  1366. //                  # Run document gamut methods on the content.
  1367. //                  foreach ($this->document_gamut as $method => $priority) {
  1368. //                      $div_content = $this->$method($div_content);
  1369. //                  }
  1370. //
  1371. //                  $div_open = preg_replace(
  1372. //                      '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open);
  1373. //
  1374. //                  $graf = $div_open . "\n" . $div_content . "\n" . $div_close;
  1375. //              }
  1376.                 $grafs[$key] = $graf;
  1377.             }
  1378.         }
  1379.  
  1380.         return implode("\n", $grafs);
  1381.     }
  1382.  
  1383.  
  1384.     function encodeAttribute($text) {
  1385.     #
  1386.     # Encode text for a double-quoted HTML attribute. This function
  1387.     # is *not* suitable for attributes enclosed in single quotes.
  1388.     #
  1389.         $text = $this->encodeAmpsAndAngles($text);
  1390.         $text = str_replace('"', '&quot;', $text);
  1391.         return $text;
  1392.     }
  1393.    
  1394.    
  1395.     function encodeAmpsAndAngles($text) {
  1396.     #
  1397.     # Smart processing for ampersands and angle brackets that need to
  1398.     # be encoded. Valid character entities are left alone unless the
  1399.     # no-entities mode is set.
  1400.     #
  1401.         if ($this->no_entities) {
  1402.             $text = str_replace('&', '&amp;', $text);
  1403.         } else {
  1404.             # Ampersand-encoding based entirely on Nat Irons's Amputator
  1405.             # MT plugin: <http://bumppo.net/projects/amputator/>
  1406.             $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
  1407.                                 '&amp;', $text);;
  1408.         }
  1409.         # Encode remaining <'s
  1410.         $text = str_replace('<', '&lt;', $text);
  1411.  
  1412.         return $text;
  1413.     }
  1414.  
  1415.  
  1416.     function doAutoLinks($text) {
  1417.         $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i',
  1418.             array(&$this, '_doAutoLinks_url_callback'), $text);
  1419.  
  1420.         # Email addresses: <address@domain.foo>
  1421.         $text = preg_replace_callback('{
  1422.             <
  1423.             (?:mailto:)?
  1424.             (
  1425.                 (?:
  1426.                     [-!#$%&\'*+/=?^_`.{|}~\w\x80-\xFF]+
  1427.                 |
  1428.                     ".*?"
  1429.                 )
  1430.                 \@
  1431.                 (?:
  1432.                     [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+
  1433.                 |
  1434.                     \[[\d.a-fA-F:]+\]   # IPv4 & IPv6
  1435.                 )
  1436.             )
  1437.             >
  1438.             }xi',
  1439.             array(&$this, '_doAutoLinks_email_callback'), $text);
  1440.  
  1441.         return $text;
  1442.     }
  1443.     function _doAutoLinks_url_callback($matches) {
  1444.         $url = $this->encodeAttribute($matches[1]);
  1445.         $link = "<a href=\"$url\">$url</a>";
  1446.         return $this->hashPart($link);
  1447.     }
  1448.     function _doAutoLinks_email_callback($matches) {
  1449.         $address = $matches[1];
  1450.         $link = $this->encodeEmailAddress($address);
  1451.         return $this->hashPart($link);
  1452.     }
  1453.  
  1454.  
  1455.     function encodeEmailAddress($addr) {
  1456.     #
  1457.     #   Input: an email address, e.g. "foo@example.com"
  1458.     #
  1459.     #   Output: the email address as a mailto link, with each character
  1460.     #       of the address encoded as either a decimal or hex entity, in
  1461.     #       the hopes of foiling most address harvesting spam bots. E.g.:
  1462.     #
  1463.     #     <p><a href="&#109;&#x61;&#105;&#x6c;&#116;&#x6f;&#58;&#x66;o&#111;
  1464.     #        &#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;&#101;&#46;&#x63;&#111;
  1465.     #        &#x6d;">&#x66;o&#111;&#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;
  1466.     #        &#101;&#46;&#x63;&#111;&#x6d;</a></p>
  1467.     #
  1468.     #   Based by a filter by Matthew Wickline, posted to BBEdit-Talk.
  1469.     #   With some optimizations by Milian Wolff.
  1470.     #
  1471.         $addr = "mailto:" . $addr;
  1472.         $chars = preg_split('/(?<!^)(?!$)/', $addr);
  1473.         $seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed.
  1474.        
  1475.         foreach ($chars as $key => $char) {
  1476.             $ord = ord($char);
  1477.             # Ignore non-ascii chars.
  1478.             if ($ord < 128) {
  1479.                 $r = ($seed * (1 + $key)) % 100; # Pseudo-random function.
  1480.                 # roughly 10% raw, 45% hex, 45% dec
  1481.                 # '@' *must* be encoded. I insist.
  1482.                 if ($r > 90 && $char != '@') /* do nothing */;
  1483.                 else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';';
  1484.                 else              $chars[$key] = '&#'.$ord.';';
  1485.             }
  1486.         }
  1487.        
  1488.         $addr = implode('', $chars);
  1489.         $text = implode('', array_slice($chars, 7)); # text without `mailto:`
  1490.         $addr = "<a href=\"$addr\">$text</a>";
  1491.  
  1492.         return $addr;
  1493.     }
  1494.  
  1495.  
  1496.     function parseSpan($str) {
  1497.     #
  1498.     # Take the string $str and parse it into tokens, hashing embeded HTML,
  1499.     # escaped characters and handling code spans.
  1500.     #
  1501.         $output = '';
  1502.        
  1503.         $span_re = '{
  1504.                 (
  1505.                     \\\\'.$this->escape_chars_re.'
  1506.                 |
  1507.                     (?<![`\\\\])
  1508.                     `+                      # code span marker
  1509.             '.( $this->no_markup ? '' : '
  1510.                 |
  1511.                     <!--    .*?     -->     # comment
  1512.                 |
  1513.                     <\?.*?\?> | <%.*?%>     # processing instruction
  1514.                 |
  1515.                     <[/!$]?[-a-zA-Z0-9:_]+  # regular tags
  1516.                     (?>
  1517.                         \s
  1518.                         (?>[^"\'>]+|"[^"]*"|\'[^\']*\')*
  1519.                     )?
  1520.                     >
  1521.             ').'
  1522.                 )
  1523.                 }xs';
  1524.  
  1525.         while (1) {
  1526.             #
  1527.             # Each loop iteration seach for either the next tag, the next
  1528.             # openning code span marker, or the next escaped character.
  1529.             # Each token is then passed to handleSpanToken.
  1530.             #
  1531.             $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE);
  1532.            
  1533.             # Create token from text preceding tag.
  1534.             if ($parts[0] != "") {
  1535.                 $output .= $parts[0];
  1536.             }
  1537.            
  1538.             # Check if we reach the end.
  1539.             if (isset($parts[1])) {
  1540.                 $output .= $this->handleSpanToken($parts[1], $parts[2]);
  1541.                 $str = $parts[2];
  1542.             }
  1543.             else {
  1544.                 break;
  1545.             }
  1546.         }
  1547.        
  1548.         return $output;
  1549.     }
  1550.    
  1551.    
  1552.     function handleSpanToken($token, &$str) {
  1553.     #
  1554.     # Handle $token provided by parseSpan by determining its nature and
  1555.     # returning the corresponding value that should replace it.
  1556.     #
  1557.         switch ($token{0}) {
  1558.             case "\\":
  1559.                 return $this->hashPart("&#". ord($token{1}). ";");
  1560.             case "`":
  1561.                 # Search for end marker in remaining text.
  1562.                 if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm',
  1563.                     $str, $matches))
  1564.                 {
  1565.                     $str = $matches[2];
  1566.                     $codespan = $this->makeCodeSpan($matches[1]);
  1567.                     return $this->hashPart($codespan);
  1568.                 }
  1569.                 return $token; // return as text since no ending marker found.
  1570.             default:
  1571.                 return $this->hashPart($token);
  1572.         }
  1573.     }
  1574.  
  1575.  
  1576.     function outdent($text) {
  1577.     #
  1578.     # Remove one level of line-leading tabs or spaces
  1579.     #
  1580.         return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text);
  1581.     }
  1582.  
  1583.  
  1584.     # String length function for detab. `_initDetab` will create a function to
  1585.     # hanlde UTF-8 if the default function does not exist.
  1586.     var $utf8_strlen = 'mb_strlen';
  1587.    
  1588.     function detab($text) {
  1589.     #
  1590.     # Replace tabs with the appropriate amount of space.
  1591.     #
  1592.         # For each line we separate the line in blocks delemited by
  1593.         # tab characters. Then we reconstruct every line by adding the
  1594.         # appropriate number of space between each blocks.
  1595.        
  1596.         $text = preg_replace_callback('/^.*\t.*$/m',
  1597.             array(&$this, '_detab_callback'), $text);
  1598.  
  1599.         return $text;
  1600.     }
  1601.     function _detab_callback($matches) {
  1602.         $line = $matches[0];
  1603.         $strlen = $this->utf8_strlen; # strlen function for UTF-8.
  1604.        
  1605.         # Split in blocks.
  1606.         $blocks = explode("\t", $line);
  1607.         # Add each blocks to the line.
  1608.         $line = $blocks[0];
  1609.         unset($blocks[0]); # Do not add first block twice.
  1610.         foreach ($blocks as $block) {
  1611.             # Calculate amount of space, insert spaces, insert block.
  1612.             $amount = $this->tab_width -
  1613.                 $strlen($line, 'UTF-8') % $this->tab_width;
  1614.             $line .= str_repeat(" ", $amount) . $block;
  1615.         }
  1616.         return $line;
  1617.     }
  1618.     function _initDetab() {
  1619.     #
  1620.     # Check for the availability of the function in the `utf8_strlen` property
  1621.     # (initially `mb_strlen`). If the function is not available, create a
  1622.     # function that will loosely count the number of UTF-8 characters with a
  1623.     # regular expression.
  1624.     #
  1625.         if (function_exists($this->utf8_strlen)) return;
  1626.         $this->utf8_strlen = create_function('$text', 'return preg_match_all(
  1627.             "/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/",
  1628.             $text, $m);');
  1629.     }
  1630.  
  1631.  
  1632.     function unhash($text) {
  1633.     #
  1634.     # Swap back in all the tags hashed by _HashHTMLBlocks.
  1635.     #
  1636.         return preg_replace_callback('/(.)\x1A[0-9]+\1/',
  1637.             array(&$this, '_unhash_callback'), $text);
  1638.     }
  1639.     function _unhash_callback($matches) {
  1640.         return $this->html_hashes[$matches[0]];
  1641.     }
  1642.  
  1643. }
  1644.  
  1645. /*
  1646.  
  1647. PHP Markdown
  1648. ============
  1649.  
  1650. Description
  1651. -----------
  1652.  
  1653. This is a PHP translation of the original Markdown formatter written in
  1654. Perl by John Gruber.
  1655.  
  1656. Markdown is a text-to-HTML filter; it translates an easy-to-read /
  1657. easy-to-write structured text format into HTML. Markdown's text format
  1658. is most similar to that of plain text email, and supports features such
  1659. as headers, *emphasis*, code blocks, blockquotes, and links.
  1660.  
  1661. Markdown's syntax is designed not as a generic markup language, but
  1662. specifically to serve as a front-end to (X)HTML. You can use span-level
  1663. HTML tags anywhere in a Markdown document, and you can use block level
  1664. HTML tags (like <div> and <table> as well).
  1665.  
  1666. For more information about Markdown's syntax, see:
  1667.  
  1668. <http://daringfireball.net/projects/markdown/>
  1669.  
  1670.  
  1671. Bugs
  1672. ----
  1673.  
  1674. To file bug reports please send email to:
  1675.  
  1676. <michel.fortin@michelf.com>
  1677.  
  1678. Please include with your report: (1) the example input; (2) the output you
  1679. expected; (3) the output Markdown actually produced.
  1680.  
  1681.  
  1682. Version History
  1683. ---------------
  1684.  
  1685. See the readme file for detailed release notes for this version.
  1686.  
  1687.  
  1688. Copyright and License
  1689. ---------------------
  1690.  
  1691. PHP Markdown
  1692. Copyright (c) 2004-2009 Michel Fortin  
  1693. <http://michelf.com/>  
  1694. All rights reserved.
  1695.  
  1696. Based on Markdown
  1697. Copyright (c) 2003-2006 John Gruber  
  1698. <http://daringfireball.net/>  
  1699. All rights reserved.
  1700.  
  1701. Redistribution and use in source and binary forms, with or without
  1702. modification, are permitted provided that the following conditions are
  1703. met:
  1704.  
  1705. *   Redistributions of source code must retain the above copyright notice,
  1706.     this list of conditions and the following disclaimer.
  1707.  
  1708. *   Redistributions in binary form must reproduce the above copyright
  1709.     notice, this list of conditions and the following disclaimer in the
  1710.     documentation and/or other materials provided with the distribution.
  1711.  
  1712. *   Neither the name "Markdown" nor the names of its contributors may
  1713.     be used to endorse or promote products derived from this software
  1714.     without specific prior written permission.
  1715.  
  1716. This software is provided by the copyright holders and contributors "as
  1717. is" and any express or implied warranties, including, but not limited
  1718. to, the implied warranties of merchantability and fitness for a
  1719. particular purpose are disclaimed. In no event shall the copyright owner
  1720. or contributors be liable for any direct, indirect, incidental, special,
  1721. exemplary, or consequential damages (including, but not limited to,
  1722. procurement of substitute goods or services; loss of use, data, or
  1723. profits; or business interruption) however caused and on any theory of
  1724. liability, whether in contract, strict liability, or tort (including
  1725. negligence or otherwise) arising in any way out of the use of this
  1726. software, even if advised of the possibility of such damage.
  1727.  
  1728. */
  1729. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement