PluginProbe ʕ •ᴥ•ʔ
Jetpack – WP Security, Backup, Speed, & Growth / 14.4.2
Jetpack – WP Security, Backup, Speed, & Growth v14.4.2
12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 14.4.2 14.5.1 14.6.1 14.7.1 14.8.1 14.9.2 15.0.3 15.1.2 15.2.1 15.3.2 15.4.1 15.5.1 15.6.1 15.7.2 15.8.1 15.9.2 16.0.2 16.1.3 16.2-a.5 16.2-a.3 16.1.2 16.2-a.1 16.1.1 16.1 16.1-beta 16.1-beta.2 16.1-beta.3 16.1-a.5 16.1-a.3 16.0.1 16.1-a.1 16.0 16.0-beta 16.0-a.7 16.0-a.5 15.9.1 16.0-a.3 16.0-a.1 15.9 15.9-beta 15.9-a.7 15.9-a.5 15.9-a.3 15.9-a.1 15.8 15.8-beta 15.8-a.7 15.8-a.5 5.2.5 5.3.4 5.4.4 5.5.5 5.6.5 5.7.5 5.8.4 5.9.4 6.0.4 6.1 6.1.1 6.1.2 6.1.3 6.1.4 6.1.5 6.2 6.2.1 6.2.2 6.2.3 6.2.4 6.2.5 6.3 6.3.1 6.3.2 6.3.3 6.3.4 6.3.5 6.3.6 6.3.7 6.4 6.4.1 6.4.2 6.4.3 6.4.4 6.4.5 6.4.6 6.5 6.5.1 6.5.2 6.5.3 6.5.4 6.6 6.6.1 6.6.2 6.6.3 6.6.4 6.6.5 6.7 6.7.1 6.7.2 6.7.3 6.7.4 6.8 6.8.1 6.8.2 6.8.3 6.8.4 6.8.5 6.9 6.9.1 6.9.2 6.9.3 6.9.4 7.0 7.0.1 7.0.2 7.0.3 7.0.4 7.0.5 7.1 7.1.1 7.1.2 7.1.3 7.1.4 7.1.5 7.2 7.2.1 7.2.1.1 7.2.2 7.2.3 7.2.4 7.2.5 7.3 7.3.0.1 7.3.1 7.3.1.1 7.3.2 7.3.3 7.3.4 7.3.5 7.4 7.4.1 7.4.2 7.4.3 7.4.4 7.4.5 7.5 7.5.0.1 7.5.1 7.5.2 7.5.3 7.5.4 7.5.5 7.5.6 7.5.7 7.6 7.6.1 7.6.2 7.6.3 7.6.4 7.7 7.7.1 7.7.2 7.7.3 7.7.4 7.7.5 7.7.6 7.8 7.8.1 7.8.2 7.8.3 7.8.4 7.9 7.9.1 7.9.2 7.9.3 7.9.4 8.0 8.0.1 8.0.2 8.0.3 8.1 8.1.1 8.1.2 8.1.3 8.1.4 8.2 8.2.0.1 8.2.1 8.2.2 8.2.3 8.2.4 8.2.5 8.2.6 8.3 8.3.1 8.3.2 8.3.3 8.4 8.4.1 8.4.2 8.4.3 8.4.4 8.4.5 8.5 8.5.1 8.5.2 8.5.3 8.6 8.6.1 8.6.2 8.6.3 8.6.4 8.7 8.7.0.1 8.7.1 8.7.2 8.7.3 8.7.4 8.8 8.8.1 8.8.2 8.8.3 8.8.4 8.8.5 8.9 8.9.1 8.9.2 8.9.3 8.9.4 9.0 9.0.1 9.0.2 9.0.3 9.0.4 9.0.5 9.1 9.1.1 9.1.2 9.1.3 9.2 9.2.1 9.2.2 9.2.3 9.2.4 9.3 9.3.1 9.3.2 9.3.3 9.3.4 9.3.5 9.4 9.4.1 9.4.2 9.4.3 9.4.4 9.5 9.5.1 9.5.2 9.5.3 9.5.4 9.5.5 9.6 9.6.1 9.6.2 9.6.3 9.6.4 9.7 9.7.1 9.7.2 15.7-beta.2 9.7.3 15.7.1 9.8 15.8-a.1 9.8.1 15.8-a.3 9.8.2 2.0.9 9.8.3 2.1.7 9.9 2.2.10 9.9.1 2.3.10 9.9.2 2.4.7 9.9.3 2.5.5 2.6.6 2.7.5 2.8.5 2.9.6 3.0.6 3.1.5 3.2.5 3.3.6 3.4.6 3.5.6 3.6.4 3.7.5 3.8.5 3.9.10 4.0.7 4.1.4 4.2.5 4.3.5 4.4.5 4.5.3 4.6.3 4.7.4 4.8.5 4.9.3 5.0.3 5.1.4 trunk 10.0 10.0.1 10.0.2 10.1 10.1.1 10.1.2 10.2 10.2.1 10.2.2 10.2.3 10.3 10.3.1 10.3.2 10.4 10.4.1 10.4.2 10.5 10.5.1 10.5.2 10.5.3 10.6 10.6.1 10.6.2 10.7 10.7.1 10.7.2 10.8 10.8.1 10.8.2 10.9 10.9.1 10.9.2 10.9.3 11.0 11.0.1 11.0.2 11.1 11.1.1 11.1.2 11.1.3 11.1.4 11.2 11.2.1 11.2.2 11.3 11.3.1 11.3.2 11.3.3 11.3.4 11.4 11.4.1 11.4.2 11.5 11.5.1 11.5.2 11.5.3 11.6 11.6.1 11.6.2 11.7 11.7.1 11.7.2 11.7.3 11.8 11.8.3 11.8.4 11.8.5 11.8.6 11.9 11.9.1 11.9.2 11.9.3 12.0 12.0.1 12.0.2 12.1 12.1.1 12.1.2 12.2 12.2.1 12.2.2 12.3 12.3.1 12.4 12.4.1 12.5 12.5.1 12.6 12.6.1 12.6.2 12.6.3 12.7 12.7.1 12.7.2 12.8 12.8.1 12.8.2 12.9 12.9.1 12.9.2 12.9.3 12.9.4 13.0 13.0.1 13.1 13.1.1 13.1.2 13.1.3 13.1.4 13.2 13.2.1 13.2.2 13.2.3 13.3 13.3.1 13.3.2 13.4 13.4.1 13.4.2 13.4.3 13.4.4 13.5 13.5.1 13.6 13.6.1 13.7 13.7.1 13.8 13.8.1 13.8.2 13.9 13.9.1 14.0 14.1 14.2 14.2.1 14.3 14.4 14.4.1 14.5 14.6 14.7 14.8 14.9 14.9.1 15.0 15.0.1 15.0.2 15.1 15.1.1 15.2 15.3 15.3.1 15.4 15.5 15.6 15.7 15.7-a.1 15.7-a.3 15.7-a.5 15.7-a.7 15.7-beta
jetpack / _inc / lib / markdown / extra.php
jetpack / _inc / lib / markdown Last commit date
README.md 8 years ago extra.php 1 year ago gfm.php 2 years ago
extra.php
3227 lines
1 <?php
2 #
3 # Markdown Extra - A text-to-HTML conversion tool for web writers
4 #
5 # PHP Markdown & Extra
6 # Copyright (c) 2004-2013 Michel Fortin
7 # <http://michelf.ca/projects/php-markdown/>
8 #
9 # Original Markdown
10 # Copyright (c) 2004-2006 John Gruber
11 # <http://daringfireball.net/projects/markdown/>
12 #
13 # Tweaked to remove WordPress interface
14
15
16 define( 'MARKDOWN_VERSION', "1.0.2" ); # 29 Nov 2013
17 define( 'MARKDOWNEXTRA_VERSION', "1.2.8" ); # 29 Nov 2013
18
19
20 #
21 # Global default settings:
22 #
23
24 // phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged
25
26 # Change to ">" for HTML output
27 @define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX', " />");
28
29 # Define the width of a tab for code blocks.
30 @define( 'MARKDOWN_TAB_WIDTH', 4 );
31
32 // Optional title attribute for footnote links and backlinks.
33 @define( 'MARKDOWN_FN_LINK_TITLE', esc_attr__( 'Read footnote.', 'jetpack' ) );
34 @define( 'MARKDOWN_FN_BACKLINK_TITLE', esc_attr__( 'Return to main content.', 'jetpack' ) );
35
36 # Optional class attribute for footnote links and backlinks.
37 @define( 'MARKDOWN_FN_LINK_CLASS', "jetpack-footnote" );
38 @define( 'MARKDOWN_FN_BACKLINK_CLASS', "" );
39
40 # Optional class prefix for fenced code block.
41 @define( 'MARKDOWN_CODE_CLASS_PREFIX', "language-" );
42
43 # Class attribute for code blocks goes on the `code` tag;
44 # setting this to true will put attributes on the `pre` tag instead.
45 @define( 'MARKDOWN_CODE_ATTR_ON_PRE', false );
46
47
48
49 ### Standard Function Interface ###
50
51 @define( 'MARKDOWN_PARSER_CLASS', 'MarkdownExtra_Parser' );
52
53 // phpcs:enable WordPress.PHP.NoSilencedErrors.Discouraged
54
55 function Markdown($text) {
56 #
57 # Initialize the parser and return the result of its transform method.
58 #
59 # Setup static parser variable.
60 static $parser;
61 if (!isset($parser)) {
62 $parser_class = MARKDOWN_PARSER_CLASS;
63 $parser = new $parser_class;
64 }
65
66 # Transform text using parser.
67 return $parser->transform($text);
68 }
69
70 /**
71 * Returns the length of $text loosely counting the number of UTF-8 characters with regular expression.
72 * Used by the Markdown_Parser class when mb_strlen is not available.
73 *
74 * @since 5.9
75 *
76 * @return string Length of the multibyte string
77 *
78 */
79 function jetpack_utf8_strlen( $text ) {
80 return preg_match_all( "/[\\x00-\\xBF]|[\\xC0-\\xFF][\\x80-\\xBF]*/", $text, $m );
81 }
82
83 #
84 # Markdown Parser Class
85 #
86
87 class Markdown_Parser {
88
89 ### Configuration Variables ###
90
91 # Change to ">" for HTML output.
92 public $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX;
93 public $tab_width = MARKDOWN_TAB_WIDTH;
94
95 # Change to `true` to disallow markup or entities.
96 public $no_markup = false;
97 public $no_entities = false;
98
99 # Predefined urls and titles for reference links and images.
100 public $predef_urls = array();
101 public $predef_titles = array();
102
103
104 ### Parser Implementation ###
105
106 # Regex to match balanced [brackets].
107 # Needed to insert a maximum bracked depth while converting to PHP.
108 public $nested_brackets_depth = 6;
109 public $nested_brackets_re;
110
111 public $nested_url_parenthesis_depth = 4;
112 public $nested_url_parenthesis_re;
113
114 # Table of hash values for escaped characters:
115 public $escape_chars = '\`*_{}[]()>#+-.!';
116 public $escape_chars_re;
117
118
119 function __construct() {
120 #
121 # Constructor function. Initialize appropriate member variables.
122 #
123 $this->_initDetab();
124 $this->prepareItalicsAndBold();
125
126 $this->nested_brackets_re =
127 str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth).
128 str_repeat('\])*', $this->nested_brackets_depth);
129
130 $this->nested_url_parenthesis_re =
131 str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth).
132 str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth);
133
134 $this->escape_chars_re = '['.preg_quote($this->escape_chars).']';
135
136 # Sort document, block, and span gamut in ascendent priority order.
137 asort($this->document_gamut);
138 asort($this->block_gamut);
139 asort($this->span_gamut);
140 }
141
142
143 # Internal hashes used during transformation.
144 public $urls = array();
145 public $titles = array();
146 public $html_hashes = array();
147
148 # Status flag to avoid invalid nesting.
149 public $in_anchor = false;
150
151
152 function setup() {
153 #
154 # Called before the transformation process starts to setup parser
155 # states.
156 #
157 # Clear global hashes.
158 $this->urls = $this->predef_urls;
159 $this->titles = $this->predef_titles;
160 $this->html_hashes = array();
161
162 $this->in_anchor = false;
163 }
164
165 function teardown() {
166 #
167 # Called after the transformation process to clear any variable
168 # which may be taking up memory unnecessarly.
169 #
170 $this->urls = array();
171 $this->titles = array();
172 $this->html_hashes = array();
173 }
174
175
176 function transform($text) {
177 #
178 # Main function. Performs some preprocessing on the input text
179 # and pass it through the document gamut.
180 #
181 $this->setup();
182
183 # Remove UTF-8 BOM and marker character in input, if present.
184 $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text);
185
186 # Standardize line endings:
187 # DOS to Unix and Mac to Unix
188 $text = preg_replace('{\r\n?}', "\n", $text);
189
190 # Make sure $text ends with a couple of newlines:
191 $text .= "\n\n";
192
193 # Convert all tabs to spaces.
194 $text = $this->detab($text);
195
196 # Turn block-level HTML blocks into hash entries
197 $text = $this->hashHTMLBlocks($text);
198
199 # Strip any lines consisting only of spaces and tabs.
200 # This makes subsequent regexen easier to write, because we can
201 # match consecutive blank lines with /\n+/ instead of something
202 # contorted like /[ ]*\n+/ .
203 $text = preg_replace('/^[ ]+$/m', '', $text);
204
205 # Run document gamut methods.
206 foreach ($this->document_gamut as $method => $priority) {
207 $text = $this->$method($text);
208 }
209
210 $this->teardown();
211
212 return $text . "\n";
213 }
214
215 public $document_gamut = array(
216 # Strip link definitions, store in hashes.
217 "stripLinkDefinitions" => 20,
218
219 "runBasicBlockGamut" => 30,
220 );
221
222
223 function stripLinkDefinitions($text) {
224 #
225 # Strips link definitions from text, stores the URLs and titles in
226 # hash references.
227 #
228 $less_than_tab = $this->tab_width - 1;
229
230 # Link defs are in the form: ^[id]: url "optional title"
231 $text = preg_replace_callback('{
232 ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1
233 [ ]*
234 \n? # maybe *one* newline
235 [ ]*
236 (?:
237 <(.+?)> # url = $2
238 |
239 (\S+?) # url = $3
240 )
241 [ ]*
242 \n? # maybe one newline
243 [ ]*
244 (?:
245 (?<=\s) # lookbehind for whitespace
246 ["(]
247 (.*?) # title = $4
248 [")]
249 [ ]*
250 )? # title is optional
251 (?:\n+|\Z)
252 }xm',
253 array(&$this, '_stripLinkDefinitions_callback'),
254 $text);
255 return $text;
256 }
257 function _stripLinkDefinitions_callback($matches) {
258 $link_id = strtolower($matches[1]);
259 $url = $matches[2] == '' ? $matches[3] : $matches[2];
260 $this->urls[$link_id] = $url;
261 $this->titles[$link_id] =& $matches[4];
262 return ''; # String that will replace the block
263 }
264
265
266 function hashHTMLBlocks($text) {
267 if ($this->no_markup) return $text;
268
269 $less_than_tab = $this->tab_width - 1;
270
271 # Hashify HTML blocks:
272 # We only want to do this for block-level HTML tags, such as headers,
273 # lists, and tables. That's because we still want to wrap <p>s around
274 # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
275 # phrase emphasis, and spans. The list of tags we're looking for is
276 # hard-coded:
277 #
278 # * List "a" is made of tags which can be both inline or block-level.
279 # These will be treated block-level when the start tag is alone on
280 # its line, otherwise they're not matched here and will be taken as
281 # inline later.
282 # * List "b" is made of tags which are always block-level;
283 #
284 $block_tags_a_re = 'ins|del';
285 $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'.
286 'script|noscript|form|fieldset|iframe|math|svg|'.
287 'article|section|nav|aside|hgroup|header|footer|'.
288 'figure';
289
290 # Regular expression for the content of a block tag.
291 $nested_tags_level = 4;
292 $attr = '
293 (?> # optional tag attributes
294 \s # starts with whitespace
295 (?>
296 [^>"/]+ # text outside quotes
297 |
298 /+(?!>) # slash not followed by ">"
299 |
300 "[^"]*" # text inside double quotes (tolerate ">")
301 |
302 \'[^\']*\' # text inside single quotes (tolerate ">")
303 )*
304 )?
305 ';
306 $content =
307 str_repeat('
308 (?>
309 [^<]+ # content without tag
310 |
311 <\2 # nested opening tag
312 '.$attr.' # attributes
313 (?>
314 />
315 |
316 >', $nested_tags_level). # end of opening tag
317 '.*?'. # last level nested tag content
318 str_repeat('
319 </\2\s*> # closing nested tag
320 )
321 |
322 <(?!/\2\s*> # other tags with a different name
323 )
324 )*',
325 $nested_tags_level);
326 $content2 = str_replace('\2', '\3', $content);
327
328 # First, look for nested blocks, e.g.:
329 # <div>
330 # <div>
331 # tags for inner block must be indented.
332 # </div>
333 # </div>
334 #
335 # The outermost tags must start at the left margin for this to match, and
336 # the inner nested divs must be indented.
337 # We need to do this before the next, more liberal match, because the next
338 # match will start at the first `<div>` and stop at the first `</div>`.
339 $text = preg_replace_callback('{(?>
340 (?>
341 (?<=\n\n) # Starting after a blank line
342 | # or
343 \A\n? # the beginning of the doc
344 )
345 ( # save in $1
346
347 # Match from `\n<tag>` to `</tag>\n`, handling nested tags
348 # in between.
349
350 [ ]{0,'.$less_than_tab.'}
351 <('.$block_tags_b_re.')# start tag = $2
352 '.$attr.'> # attributes followed by > and \n
353 '.$content.' # content, support nesting
354 </\2> # the matching end tag
355 [ ]* # trailing spaces/tabs
356 (?=\n+|\Z) # followed by a newline or end of document
357
358 | # Special version for tags of group a.
359
360 [ ]{0,'.$less_than_tab.'}
361 <('.$block_tags_a_re.')# start tag = $3
362 '.$attr.'>[ ]*\n # attributes followed by >
363 '.$content2.' # content, support nesting
364 </\3> # the matching end tag
365 [ ]* # trailing spaces/tabs
366 (?=\n+|\Z) # followed by a newline or end of document
367
368 | # Special case just for <hr />. It was easier to make a special
369 # case than to make the other regex more complicated.
370
371 [ ]{0,'.$less_than_tab.'}
372 <(hr) # start tag = $2
373 '.$attr.' # attributes
374 /?> # the matching end tag
375 [ ]*
376 (?=\n{2,}|\Z) # followed by a blank line or end of document
377
378 | # Special case for standalone HTML comments:
379
380 [ ]{0,'.$less_than_tab.'}
381 (?s:
382 <!-- .*? -->
383 )
384 [ ]*
385 (?=\n{2,}|\Z) # followed by a blank line or end of document
386
387 | # PHP and ASP-style processor instructions (<? and <%)
388
389 [ ]{0,'.$less_than_tab.'}
390 (?s:
391 <([?%]) # $2
392 .*?
393 \2>
394 )
395 [ ]*
396 (?=\n{2,}|\Z) # followed by a blank line or end of document
397
398 )
399 )}Sxmi',
400 array(&$this, '_hashHTMLBlocks_callback'),
401 $text);
402
403 return $text;
404 }
405 function _hashHTMLBlocks_callback($matches) {
406 $text = $matches[1];
407 $key = $this->hashBlock($text);
408 return "\n\n$key\n\n";
409 }
410
411
412 function hashPart($text, $boundary = 'X') {
413 #
414 # Called whenever a tag must be hashed when a function insert an atomic
415 # element in the text stream. Passing $text to through this function gives
416 # a unique text-token which will be reverted back when calling unhash.
417 #
418 # The $boundary argument specify what character should be used to surround
419 # the token. By convension, "B" is used for block elements that needs not
420 # to be wrapped into paragraph tags at the end, ":" is used for elements
421 # that are word separators and "X" is used in the general case.
422 #
423 # Swap back any tag hash found in $text so we do not have to `unhash`
424 # multiple times at the end.
425 $text = $this->unhash($text);
426
427 # Then hash the block.
428 static $i = 0;
429 $key = "$boundary\x1A" . ++$i . $boundary;
430 $this->html_hashes[$key] = $text;
431 return $key; # String that will replace the tag.
432 }
433
434
435 function hashBlock($text) {
436 #
437 # Shortcut function for hashPart with block-level boundaries.
438 #
439 return $this->hashPart($text, 'B');
440 }
441
442
443 public $block_gamut = array(
444 #
445 # These are all the transformations that form block-level
446 # tags like paragraphs, headers, and list items.
447 #
448 "doHeaders" => 10,
449 "doHorizontalRules" => 20,
450
451 "doLists" => 40,
452 "doCodeBlocks" => 50,
453 "doBlockQuotes" => 60,
454 );
455
456 function runBlockGamut($text) {
457 #
458 # Run block gamut tranformations.
459 #
460 # We need to escape raw HTML in Markdown source before doing anything
461 # else. This need to be done for each block, and not only at the
462 # beginning in the Markdown function since hashed blocks can be part of
463 # list items and could have been indented. Indented blocks would have
464 # been seen as a code block in a previous pass of hashHTMLBlocks.
465 $text = $this->hashHTMLBlocks($text);
466
467 return $this->runBasicBlockGamut($text);
468 }
469
470 function runBasicBlockGamut($text) {
471 #
472 # Run block gamut tranformations, without hashing HTML blocks. This is
473 # useful when HTML blocks are known to be already hashed, like in the first
474 # whole-document pass.
475 #
476 foreach ($this->block_gamut as $method => $priority) {
477 $text = $this->$method($text);
478 }
479
480 # Finally form paragraph and restore hashed blocks.
481 $text = $this->formParagraphs($text);
482
483 return $text;
484 }
485
486
487 function doHorizontalRules($text) {
488 # Do Horizontal Rules:
489 return preg_replace(
490 '{
491 ^[ ]{0,3} # Leading space
492 ([-*_]) # $1: First marker
493 (?> # Repeated marker group
494 [ ]{0,2} # Zero, one, or two spaces.
495 \1 # Marker character
496 ){2,} # Group repeated at least twice
497 [ ]* # Tailing spaces
498 $ # End of line.
499 }mx',
500 "\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n",
501 $text);
502 }
503
504
505 public $span_gamut = array(
506 #
507 # These are all the transformations that occur *within* block-level
508 # tags like paragraphs, headers, and list items.
509 #
510 # Process character escapes, code spans, and inline HTML
511 # in one shot.
512 "parseSpan" => -30,
513
514 # Process anchor and image tags. Images must come first,
515 # because ![foo][f] looks like an anchor.
516 "doImages" => 10,
517 "doAnchors" => 20,
518
519 # Make links out of things like `<http://example.com/>`
520 # Must come after doAnchors, because you can use < and >
521 # delimiters in inline links like [this](<url>).
522 "doAutoLinks" => 30,
523 "encodeAmpsAndAngles" => 40,
524
525 "doItalicsAndBold" => 50,
526 "doHardBreaks" => 60,
527 );
528
529 function runSpanGamut($text) {
530 #
531 # Run span gamut tranformations.
532 #
533 foreach ($this->span_gamut as $method => $priority) {
534 $text = $this->$method($text);
535 }
536
537 return $text;
538 }
539
540
541 function doHardBreaks($text) {
542 # Do hard breaks:
543 return preg_replace_callback('/ {2,}\n/',
544 array(&$this, '_doHardBreaks_callback'), $text);
545 }
546 function _doHardBreaks_callback($matches) {
547 return $this->hashPart("<br$this->empty_element_suffix\n");
548 }
549
550
551 function doAnchors($text) {
552 #
553 # Turn Markdown link shortcuts into XHTML <a> tags.
554 #
555 if ($this->in_anchor) return $text;
556 $this->in_anchor = true;
557
558 #
559 # First, handle reference-style links: [link text] [id]
560 #
561 $text = preg_replace_callback('{
562 ( # wrap whole match in $1
563 \[
564 ('.$this->nested_brackets_re.') # link text = $2
565 \]
566
567 [ ]? # one optional space
568 (?:\n[ ]*)? # one optional newline followed by spaces
569
570 \[
571 (.*?) # id = $3
572 \]
573 )
574 }xs',
575 array(&$this, '_doAnchors_reference_callback'), $text);
576
577 #
578 # Next, inline-style links: [link text](url "optional title")
579 #
580 $text = preg_replace_callback('{
581 ( # wrap whole match in $1
582 \[
583 ('.$this->nested_brackets_re.') # link text = $2
584 \]
585 \( # literal paren
586 [ \n]*
587 (?:
588 <(.+?)> # href = $3
589 |
590 ('.$this->nested_url_parenthesis_re.') # href = $4
591 )
592 [ \n]*
593 ( # $5
594 ([\'"]) # quote char = $6
595 (.*?) # Title = $7
596 \6 # matching quote
597 [ \n]* # ignore any spaces/tabs between closing quote and )
598 )? # title is optional
599 \)
600 )
601 }xs',
602 array(&$this, '_doAnchors_inline_callback'), $text);
603
604 #
605 # Last, handle reference-style shortcuts: [link text]
606 # These must come last in case you've also got [link text][1]
607 # or [link text](/foo)
608 #
609 $text = preg_replace_callback('{
610 ( # wrap whole match in $1
611 \[
612 ([^\[\]]+) # link text = $2; can\'t contain [ or ]
613 \]
614 )
615 }xs',
616 array(&$this, '_doAnchors_reference_callback'), $text);
617
618 $this->in_anchor = false;
619 return $text;
620 }
621 function _doAnchors_reference_callback($matches) {
622 $whole_match = $matches[1];
623 $link_text = $matches[2];
624 $link_id =& $matches[3];
625
626 if ($link_id == "") {
627 # for shortcut links like [this][] or [this].
628 $link_id = $link_text;
629 }
630
631 # lower-case and turn embedded newlines into spaces
632 $link_id = strtolower($link_id);
633 $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
634
635 if (isset($this->urls[$link_id])) {
636 $url = $this->urls[$link_id];
637 $url = $this->encodeAttribute($url);
638
639 $result = "<a href=\"$url\"";
640 if ( isset( $this->titles[$link_id] ) ) {
641 $title = $this->titles[$link_id];
642 $title = $this->encodeAttribute($title);
643 $result .= " title=\"$title\"";
644 }
645
646 $link_text = $this->runSpanGamut($link_text);
647 $result .= ">$link_text</a>";
648 $result = $this->hashPart($result);
649 }
650 else {
651 $result = $whole_match;
652 }
653 return $result;
654 }
655 function _doAnchors_inline_callback($matches) {
656 $whole_match = $matches[1];
657 $link_text = $this->runSpanGamut($matches[2]);
658 $url = $matches[3] == '' ? $matches[4] : $matches[3];
659 $title =& $matches[7];
660
661 $url = $this->encodeAttribute($url);
662
663 $result = "<a href=\"$url\"";
664 if (isset($title)) {
665 $title = $this->encodeAttribute($title);
666 $result .= " title=\"$title\"";
667 }
668
669 $link_text = $this->runSpanGamut($link_text);
670 $result .= ">$link_text</a>";
671
672 return $this->hashPart($result);
673 }
674
675
676 function doImages($text) {
677 #
678 # Turn Markdown image shortcuts into <img> tags.
679 #
680 #
681 # First, handle reference-style labeled images: ![alt text][id]
682 #
683 $text = preg_replace_callback('{
684 ( # wrap whole match in $1
685 !\[
686 ('.$this->nested_brackets_re.') # alt text = $2
687 \]
688
689 [ ]? # one optional space
690 (?:\n[ ]*)? # one optional newline followed by spaces
691
692 \[
693 (.*?) # id = $3
694 \]
695
696 )
697 }xs',
698 array(&$this, '_doImages_reference_callback'), $text);
699
700 #
701 # Next, handle inline images: ![alt text](url "optional title")
702 # Don't forget: encode * and _
703 #
704 $text = preg_replace_callback('{
705 ( # wrap whole match in $1
706 !\[
707 ('.$this->nested_brackets_re.') # alt text = $2
708 \]
709 \s? # One optional whitespace character
710 \( # literal paren
711 [ \n]*
712 (?:
713 <(\S*)> # src url = $3
714 |
715 ('.$this->nested_url_parenthesis_re.') # src url = $4
716 )
717 [ \n]*
718 ( # $5
719 ([\'"]) # quote char = $6
720 (.*?) # title = $7
721 \6 # matching quote
722 [ \n]*
723 )? # title is optional
724 \)
725 )
726 }xs',
727 array(&$this, '_doImages_inline_callback'), $text);
728
729 return $text;
730 }
731 function _doImages_reference_callback($matches) {
732 $whole_match = $matches[1];
733 $alt_text = $matches[2];
734 $link_id = strtolower($matches[3]);
735
736 if ($link_id == "") {
737 $link_id = strtolower($alt_text); # for shortcut links like ![this][].
738 }
739
740 $alt_text = $this->encodeAttribute($alt_text);
741 if (isset($this->urls[$link_id])) {
742 $url = $this->encodeAttribute($this->urls[$link_id]);
743 $result = "<img src=\"$url\" alt=\"$alt_text\"";
744 if (isset($this->titles[$link_id])) {
745 $title = $this->titles[$link_id];
746 $title = $this->encodeAttribute($title);
747 $result .= " title=\"$title\"";
748 }
749 $result .= $this->empty_element_suffix;
750 $result = $this->hashPart($result);
751 }
752 else {
753 # If there's no such link ID, leave intact:
754 $result = $whole_match;
755 }
756
757 return $result;
758 }
759 function _doImages_inline_callback($matches) {
760 $whole_match = $matches[1];
761 $alt_text = $matches[2];
762 $url = $matches[3] == '' ? $matches[4] : $matches[3];
763 $title =& $matches[7];
764
765 $alt_text = $this->encodeAttribute($alt_text);
766 $url = $this->encodeAttribute($url);
767 $result = "<img src=\"$url\" alt=\"$alt_text\"";
768 if (isset($title)) {
769 $title = $this->encodeAttribute($title);
770 $result .= " title=\"$title\""; # $title already quoted
771 }
772 $result .= $this->empty_element_suffix;
773
774 return $this->hashPart($result);
775 }
776
777
778 function doHeaders($text) {
779 # Setext-style headers:
780 # Header 1
781 # ========
782 #
783 # Header 2
784 # --------
785 #
786 $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx',
787 array(&$this, '_doHeaders_callback_setext'), $text);
788
789 # atx-style headers:
790 # # Header 1
791 # ## Header 2
792 # ## Header 2 with closing hashes ##
793 # ...
794 # ###### Header 6
795 #
796 $text = preg_replace_callback('{
797 ^(\#{1,6}) # $1 = string of #\'s
798 [ ]*
799 (.+?) # $2 = Header text
800 [ ]*
801 \#* # optional closing #\'s (not counted)
802 \n+
803 }xm',
804 array(&$this, '_doHeaders_callback_atx'), $text);
805
806 return $text;
807 }
808 function _doHeaders_callback_setext($matches) {
809 # Terrible hack to check we haven't found an empty list item.
810 if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1]))
811 return $matches[0];
812
813 $level = $matches[2][0] == '=' ? 1 : 2;
814 $block = "<h$level>".$this->runSpanGamut($matches[1])."</h$level>";
815 return "\n" . $this->hashBlock($block) . "\n\n";
816 }
817 function _doHeaders_callback_atx($matches) {
818 $level = strlen($matches[1]);
819 $block = "<h$level>".$this->runSpanGamut($matches[2])."</h$level>";
820 return "\n" . $this->hashBlock($block) . "\n\n";
821 }
822
823
824 function doLists($text) {
825 #
826 # Form HTML ordered (numbered) and unordered (bulleted) lists.
827 #
828 $less_than_tab = $this->tab_width - 1;
829
830 # Re-usable patterns to match list item bullets and number markers:
831 $marker_ul_re = '[*+-]';
832 $marker_ol_re = '\d+[\.]';
833 $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
834
835 $markers_relist = array(
836 $marker_ul_re => $marker_ol_re,
837 $marker_ol_re => $marker_ul_re,
838 );
839
840 foreach ($markers_relist as $marker_re => $other_marker_re) {
841 # Re-usable pattern to match any entirel ul or ol list:
842 $whole_list_re = '
843 ( # $1 = whole list
844 ( # $2
845 ([ ]{0,'.$less_than_tab.'}) # $3 = number of spaces
846 ('.$marker_re.') # $4 = first list item marker
847 [ ]+
848 )
849 (?s:.+?)
850 ( # $5
851 \z
852 |
853 \n{2,}
854 (?=\S)
855 (?! # Negative lookahead for another list item marker
856 [ ]*
857 '.$marker_re.'[ ]+
858 )
859 |
860 (?= # Lookahead for another kind of list
861 \n
862 \3 # Must have the same indentation
863 '.$other_marker_re.'[ ]+
864 )
865 )
866 )
867 '; // mx
868
869 # We use a different prefix before nested lists than top-level lists.
870 # See extended comment in _ProcessListItems().
871
872 if ($this->list_level) {
873 $text = preg_replace_callback('{
874 ^
875 '.$whole_list_re.'
876 }mx',
877 array(&$this, '_doLists_callback'), $text);
878 }
879 else {
880 $text = preg_replace_callback('{
881 (?:(?<=\n)\n|\A\n?) # Must eat the newline
882 '.$whole_list_re.'
883 }mx',
884 array(&$this, '_doLists_callback'), $text);
885 }
886 }
887
888 return $text;
889 }
890 function _doLists_callback($matches) {
891 # Re-usable patterns to match list item bullets and number markers:
892 $marker_ul_re = '[*+-]';
893 $marker_ol_re = '\d+[\.]';
894 $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
895
896 $list = $matches[1];
897 $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol";
898
899 $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re );
900
901 $list .= "\n";
902 $result = $this->processListItems($list, $marker_any_re);
903
904 $result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>");
905 return "\n". $result ."\n\n";
906 }
907
908 public $list_level = 0;
909
910 function processListItems($list_str, $marker_any_re) {
911 #
912 # Process the contents of a single ordered or unordered list, splitting it
913 # into individual list items.
914 #
915 # The $this->list_level global keeps track of when we're inside a list.
916 # Each time we enter a list, we increment it; when we leave a list,
917 # we decrement. If it's zero, we're not in a list anymore.
918 #
919 # We do this because when we're not inside a list, we want to treat
920 # something like this:
921 #
922 # I recommend upgrading to version
923 # 8. Oops, now this line is treated
924 # as a sub-list.
925 #
926 # As a single paragraph, despite the fact that the second line starts
927 # with a digit-period-space sequence.
928 #
929 # Whereas when we're inside a list (or sub-list), that line will be
930 # treated as the start of a sub-list. What a kludge, huh? This is
931 # an aspect of Markdown's syntax that's hard to parse perfectly
932 # without resorting to mind-reading. Perhaps the solution is to
933 # change the syntax rules such that sub-lists must start with a
934 # starting cardinal number; e.g. "1." or "a.".
935
936 $this->list_level++;
937
938 # trim trailing blank lines:
939 $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
940
941 $list_str = preg_replace_callback('{
942 (\n)? # leading line = $1
943 (^[ ]*) # leading whitespace = $2
944 ('.$marker_any_re.' # list marker and space = $3
945 (?:[ ]+|(?=\n)) # space only required if item is not empty
946 )
947 ((?s:.*?)) # list item text = $4
948 (?:(\n+(?=\n))|\n) # tailing blank line = $5
949 (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n))))
950 }xm',
951 array(&$this, '_processListItems_callback'), $list_str);
952
953 $this->list_level--;
954 return $list_str;
955 }
956 function _processListItems_callback($matches) {
957 $item = $matches[4];
958 $leading_line =& $matches[1];
959 $leading_space =& $matches[2];
960 $marker_space = $matches[3];
961 $tailing_blank_line =& $matches[5];
962
963 if ($leading_line || $tailing_blank_line ||
964 preg_match('/\n{2,}/', $item))
965 {
966 # Replace marker with the appropriate whitespace indentation
967 $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;
968 $item = $this->runBlockGamut($this->outdent($item)."\n");
969 }
970 else {
971 # Recursion for sub-lists:
972 $item = $this->doLists($this->outdent($item));
973 $item = preg_replace('/\n+$/', '', $item);
974 $item = $this->runSpanGamut($item);
975 }
976
977 return "<li>" . $item . "</li>\n";
978 }
979
980
981 function doCodeBlocks($text) {
982 #
983 # Process Markdown `<pre><code>` blocks.
984 #
985 $text = preg_replace_callback('{
986 (?:\n\n|\A\n?)
987 ( # $1 = the code block -- one or more lines, starting with a space/tab
988 (?>
989 [ ]{'.$this->tab_width.'} # Lines must start with a tab or a tab-width of spaces
990 .*\n+
991 )+
992 )
993 ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
994 }xm',
995 array(&$this, '_doCodeBlocks_callback'), $text);
996
997 return $text;
998 }
999 function _doCodeBlocks_callback($matches) {
1000 $codeblock = $matches[1];
1001
1002 $codeblock = $this->outdent($codeblock);
1003 $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
1004
1005 # trim leading newlines and trailing newlines
1006 $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
1007
1008 $codeblock = "<pre><code>$codeblock\n</code></pre>";
1009 return "\n\n".$this->hashBlock($codeblock)."\n\n";
1010 }
1011
1012
1013 function makeCodeSpan($code) {
1014 #
1015 # Create a code span markup for $code. Called from handleSpanToken.
1016 #
1017 $code = htmlspecialchars(trim($code), ENT_NOQUOTES);
1018 return $this->hashPart("<code>$code</code>");
1019 }
1020
1021
1022 public $em_relist = array(
1023 '' => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S|$)(?![\.,:;]\s)',
1024 '*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
1025 '_' => '(?<=\S|^)(?<!_)_(?!_)',
1026 );
1027 public $strong_relist = array(
1028 '' => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S|$)(?![\.,:;]\s)',
1029 '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
1030 '__' => '(?<=\S|^)(?<!_)__(?!_)',
1031 );
1032 public $em_strong_relist = array(
1033 '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S|$)(?![\.,:;]\s)',
1034 '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
1035 '___' => '(?<=\S|^)(?<!_)___(?!_)',
1036 );
1037 public $em_strong_prepared_relist;
1038
1039 function prepareItalicsAndBold() {
1040 #
1041 # Prepare regular expressions for searching emphasis tokens in any
1042 # context.
1043 #
1044 foreach ($this->em_relist as $em => $em_re) {
1045 foreach ($this->strong_relist as $strong => $strong_re) {
1046 # Construct list of allowed token expressions.
1047 $token_relist = array();
1048 if (isset($this->em_strong_relist["$em$strong"])) {
1049 $token_relist[] = $this->em_strong_relist["$em$strong"];
1050 }
1051 $token_relist[] = $em_re;
1052 $token_relist[] = $strong_re;
1053
1054 # Construct master expression from list.
1055 $token_re = '{('. implode('|', $token_relist) .')}';
1056 $this->em_strong_prepared_relist["$em$strong"] = $token_re;
1057 }
1058 }
1059 }
1060
1061 function doItalicsAndBold($text) {
1062 $token_stack = array('');
1063 $text_stack = array('');
1064 $em = '';
1065 $strong = '';
1066 $tree_char_em = false;
1067
1068 while (1) {
1069 #
1070 # Get prepared regular expression for seraching emphasis tokens
1071 # in current context.
1072 #
1073 $token_re = $this->em_strong_prepared_relist["$em$strong"];
1074
1075 #
1076 # Each loop iteration search for the next emphasis token.
1077 # Each token is then passed to handleSpanToken.
1078 #
1079 $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
1080 $text_stack[0] .= $parts[0];
1081 $token =& $parts[1];
1082 $text =& $parts[2];
1083
1084 if (empty($token)) {
1085 # Reached end of text span: empty stack without emitting.
1086 # any more emphasis.
1087 while ($token_stack[0]) {
1088 $text_stack[1] .= array_shift($token_stack);
1089 $text_stack[0] .= array_shift($text_stack);
1090 }
1091 break;
1092 }
1093
1094 $token_len = strlen($token);
1095 if ($tree_char_em) {
1096 # Reached closing marker while inside a three-char emphasis.
1097 if ($token_len == 3) {
1098 # Three-char closing marker, close em and strong.
1099 array_shift($token_stack);
1100 $span = array_shift($text_stack);
1101 $span = $this->runSpanGamut($span);
1102 $span = "<strong><em>$span</em></strong>";
1103 $text_stack[0] .= $this->hashPart($span);
1104 $em = '';
1105 $strong = '';
1106 } else {
1107 # Other closing marker: close one em or strong and
1108 # change current token state to match the other
1109 $token_stack[0] = str_repeat($token[0], 3-$token_len);
1110 $tag = $token_len == 2 ? "strong" : "em";
1111 $span = $text_stack[0];
1112 $span = $this->runSpanGamut($span);
1113 $span = "<$tag>$span</$tag>";
1114 $text_stack[0] = $this->hashPart($span);
1115 $$tag = ''; # $$tag stands for $em or $strong
1116 }
1117 $tree_char_em = false;
1118 } else if ($token_len == 3) {
1119 if ($em) {
1120 # Reached closing marker for both em and strong.
1121 # Closing strong marker:
1122 for ($i = 0; $i < 2; ++$i) {
1123 $shifted_token = array_shift($token_stack);
1124 $tag = strlen($shifted_token) == 2 ? "strong" : "em";
1125 $span = array_shift($text_stack);
1126 $span = $this->runSpanGamut($span);
1127 $span = "<$tag>$span</$tag>";
1128 $text_stack[0] .= $this->hashPart($span);
1129 $$tag = ''; # $$tag stands for $em or $strong
1130 }
1131 } else {
1132 # Reached opening three-char emphasis marker. Push on token
1133 # stack; will be handled by the special condition above.
1134 $em = $token[0];
1135 $strong = "$em$em";
1136 array_unshift($token_stack, $token);
1137 array_unshift($text_stack, '');
1138 $tree_char_em = true;
1139 }
1140 } else if ($token_len == 2) {
1141 if ($strong) {
1142 # Unwind any dangling emphasis marker:
1143 if (strlen($token_stack[0]) == 1) {
1144 $text_stack[1] .= array_shift($token_stack);
1145 $text_stack[0] .= array_shift($text_stack);
1146 }
1147 # Closing strong marker:
1148 array_shift($token_stack);
1149 $span = array_shift($text_stack);
1150 $span = $this->runSpanGamut($span);
1151 $span = "<strong>$span</strong>";
1152 $text_stack[0] .= $this->hashPart($span);
1153 $strong = '';
1154 } else {
1155 array_unshift($token_stack, $token);
1156 array_unshift($text_stack, '');
1157 $strong = $token;
1158 }
1159 } else {
1160 # Here $token_len == 1
1161 if ($em) {
1162 if (strlen($token_stack[0]) == 1) {
1163 # Closing emphasis marker:
1164 array_shift($token_stack);
1165 $span = array_shift($text_stack);
1166 $span = $this->runSpanGamut($span);
1167 $span = "<em>$span</em>";
1168 $text_stack[0] .= $this->hashPart($span);
1169 $em = '';
1170 } else {
1171 $text_stack[0] .= $token;
1172 }
1173 } else {
1174 array_unshift($token_stack, $token);
1175 array_unshift($text_stack, '');
1176 $em = $token;
1177 }
1178 }
1179 }
1180 return $text_stack[0];
1181 }
1182
1183
1184 function doBlockQuotes($text) {
1185 $text = preg_replace_callback('/
1186 ( # Wrap whole match in $1
1187 (?>
1188 ^[ ]*>[ ]? # ">" at the start of a line
1189 .+\n # rest of the first line
1190 (.+\n)* # subsequent consecutive lines
1191 \n* # blanks
1192 )+
1193 )
1194 /xm',
1195 array(&$this, '_doBlockQuotes_callback'), $text);
1196
1197 return $text;
1198 }
1199 function _doBlockQuotes_callback($matches) {
1200 $bq = $matches[1];
1201 # trim one level of quoting - trim whitespace-only lines
1202 $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
1203 $bq = $this->runBlockGamut($bq); # recurse
1204
1205 $bq = preg_replace('/^/m', " ", $bq);
1206 # These leading spaces cause problem with <pre> content,
1207 # so we need to fix that:
1208 $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx',
1209 array(&$this, '_doBlockQuotes_callback2'), $bq);
1210
1211 return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n";
1212 }
1213 function _doBlockQuotes_callback2($matches) {
1214 $pre = $matches[1];
1215 $pre = preg_replace('/^ /m', '', $pre);
1216 return $pre;
1217 }
1218
1219
1220 function formParagraphs($text) {
1221 #
1222 # Params:
1223 # $text - string to process with html <p> tags
1224 #
1225 # Strip leading and trailing lines:
1226 $text = preg_replace('/\A\n+|\n+\z/', '', $text);
1227
1228 $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
1229
1230 #
1231 # Wrap <p> tags and unhashify HTML blocks
1232 #
1233 foreach ($grafs as $key => $value) {
1234 if (!preg_match('/^B\x1A[0-9]+B$/', $value)) {
1235 # Is a paragraph.
1236 $value = $this->runSpanGamut($value);
1237 $value = preg_replace('/^([ ]*)/', "<p>", $value);
1238 $value .= "</p>";
1239 $grafs[$key] = $this->unhash($value);
1240 }
1241 else {
1242 # Is a block.
1243 # Modify elements of @grafs in-place...
1244 $graf = $value;
1245 $block = $this->html_hashes[$graf];
1246 $graf = $block;
1247 // if (preg_match('{
1248 // \A
1249 // ( # $1 = <div> tag
1250 // <div \s+
1251 // [^>]*
1252 // \b
1253 // markdown\s*=\s* ([\'"]) # $2 = attr quote char
1254 // 1
1255 // \2
1256 // [^>]*
1257 // >
1258 // )
1259 // ( # $3 = contents
1260 // .*
1261 // )
1262 // (</div>) # $4 = closing tag
1263 // \z
1264 // }xs', $block, $matches))
1265 // {
1266 // list(, $div_open, , $div_content, $div_close) = $matches;
1267 //
1268 // # We can't call Markdown(), because that resets the hash;
1269 // # that initialization code should be pulled into its own sub, though.
1270 // $div_content = $this->hashHTMLBlocks($div_content);
1271 //
1272 // # Run document gamut methods on the content.
1273 // foreach ($this->document_gamut as $method => $priority) {
1274 // $div_content = $this->$method($div_content);
1275 // }
1276 //
1277 // $div_open = preg_replace(
1278 // '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open);
1279 //
1280 // $graf = $div_open . "\n" . $div_content . "\n" . $div_close;
1281 // }
1282 $grafs[$key] = $graf;
1283 }
1284 }
1285
1286 return implode("\n\n", $grafs);
1287 }
1288
1289
1290 function encodeAttribute($text) {
1291 #
1292 # Encode text for a double-quoted HTML attribute. This function
1293 # is *not* suitable for attributes enclosed in single quotes.
1294 #
1295 $text = $this->encodeAmpsAndAngles($text);
1296 $text = str_replace('"', '&quot;', $text);
1297 return $text;
1298 }
1299
1300
1301 function encodeAmpsAndAngles($text) {
1302 #
1303 # Smart processing for ampersands and angle brackets that need to
1304 # be encoded. Valid character entities are left alone unless the
1305 # no-entities mode is set.
1306 #
1307 if ($this->no_entities) {
1308 $text = str_replace('&', '&amp;', $text);
1309 } else {
1310 # Ampersand-encoding based entirely on Nat Irons's Amputator
1311 # MT plugin: <http://bumppo.net/projects/amputator/>
1312 $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
1313 '&amp;', $text);;
1314 }
1315 # Encode remaining <'s
1316 $text = str_replace('<', '&lt;', $text);
1317
1318 return $text;
1319 }
1320
1321
1322 function doAutoLinks($text) {
1323 $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i',
1324 array(&$this, '_doAutoLinks_url_callback'), $text);
1325
1326 # Email addresses: <address@domain.foo>
1327 $text = preg_replace_callback('{
1328 <
1329 (?:mailto:)?
1330 (
1331 (?:
1332 [-!#$%&\'*+/=?^_`.{|}~\w\x80-\xFF]+
1333 |
1334 ".*?"
1335 )
1336 \@
1337 (?:
1338 [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+
1339 |
1340 \[[\d.a-fA-F:]+\] # IPv4 & IPv6
1341 )
1342 )
1343 >
1344 }xi',
1345 array(&$this, '_doAutoLinks_email_callback'), $text);
1346 $text = preg_replace_callback('{<(tel:([^\'">\s]+))>}i',array(&$this, '_doAutoLinks_tel_callback'), $text);
1347
1348 return $text;
1349 }
1350 function _doAutoLinks_tel_callback($matches) {
1351 $url = $this->encodeAttribute($matches[1]);
1352 $tel = $this->encodeAttribute($matches[2]);
1353 $link = "<a href=\"$url\">$tel</a>";
1354 return $this->hashPart($link);
1355 }
1356 function _doAutoLinks_url_callback($matches) {
1357 $url = $this->encodeAttribute($matches[1]);
1358 $link = "<a href=\"$url\">$url</a>";
1359 return $this->hashPart($link);
1360 }
1361 function _doAutoLinks_email_callback($matches) {
1362 $address = $matches[1];
1363 $link = $this->encodeEmailAddress($address);
1364 return $this->hashPart($link);
1365 }
1366
1367
1368 function encodeEmailAddress($addr) {
1369 #
1370 # Input: an email address, e.g. "foo@example.com"
1371 #
1372 # Output: the email address as a mailto link, with each character
1373 # of the address encoded as either a decimal or hex entity, in
1374 # the hopes of foiling most address harvesting spam bots. E.g.:
1375 #
1376 # <p><a href="&#109;&#x61;&#105;&#x6c;&#116;&#x6f;&#58;&#x66;o&#111;
1377 # &#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;&#101;&#46;&#x63;&#111;
1378 # &#x6d;">&#x66;o&#111;&#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;
1379 # &#101;&#46;&#x63;&#111;&#x6d;</a></p>
1380 #
1381 # Based by a filter by Matthew Wickline, posted to BBEdit-Talk.
1382 # With some optimizations by Milian Wolff.
1383 #
1384 $addr = "mailto:" . $addr;
1385 $chars = preg_split('/(?<!^)(?!$)/', $addr);
1386 $seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed.
1387
1388 foreach ($chars as $key => $char) {
1389 $ord = ord($char);
1390 # Ignore non-ascii chars.
1391 if ($ord < 128) {
1392 $r = ($seed * (1 + $key)) % 100; # Pseudo-random function.
1393 # roughly 10% raw, 45% hex, 45% dec
1394 # '@' *must* be encoded. I insist.
1395 if ($r > 90 && $char != '@') /* do nothing */;
1396 else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';';
1397 else $chars[$key] = '&#'.$ord.';';
1398 }
1399 }
1400
1401 $addr = implode('', $chars);
1402 $text = implode('', array_slice($chars, 7)); # text without `mailto:`
1403 $addr = "<a href=\"$addr\">$text</a>";
1404
1405 return $addr;
1406 }
1407
1408
1409 function parseSpan($str) {
1410 #
1411 # Take the string $str and parse it into tokens, hashing embedded HTML,
1412 # escaped characters and handling code spans.
1413 #
1414 $output = '';
1415
1416 $span_re = '{
1417 (
1418 \\\\'.$this->escape_chars_re.'
1419 |
1420 (?<![`\\\\])
1421 `+ # code span marker
1422 '.( $this->no_markup ? '' : '
1423 |
1424 <!-- .*? --> # comment
1425 |
1426 <\?.*?\?> | <%.*?%> # processing instruction
1427 |
1428 <[!$]?[-a-zA-Z0-9:_]+ # regular tags
1429 (?>
1430 \s
1431 (?>[^"\'>]+|"[^"]*"|\'[^\']*\')*
1432 )?
1433 >
1434 |
1435 <[-a-zA-Z0-9:_]+\s*/> # xml-style empty tag
1436 |
1437 </[-a-zA-Z0-9:_]+\s*> # closing tag
1438 ').'
1439 )
1440 }xs';
1441
1442 while (1) {
1443 #
1444 # Each loop iteration search for either the next tag, the next
1445 # openning code span marker, or the next escaped character.
1446 # Each token is then passed to handleSpanToken.
1447 #
1448 $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE);
1449
1450 # Create token from text preceding tag.
1451 if ($parts[0] != "") {
1452 $output .= $parts[0];
1453 }
1454
1455 # Check if we reach the end.
1456 if (isset($parts[1])) {
1457 $output .= $this->handleSpanToken($parts[1], $parts[2]);
1458 $str = $parts[2];
1459 }
1460 else {
1461 break;
1462 }
1463 }
1464
1465 return $output;
1466 }
1467
1468
1469 function handleSpanToken($token, &$str) {
1470 #
1471 # Handle $token provided by parseSpan by determining its nature and
1472 # returning the corresponding value that should replace it.
1473 #
1474 switch ($token[0]) {
1475 case "\\":
1476 return $this->hashPart("&#". ord($token[1]). ";");
1477 case "`":
1478 # Search for end marker in remaining text.
1479 if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm',
1480 $str, $matches))
1481 {
1482 $str = $matches[2];
1483 $codespan = $this->makeCodeSpan($matches[1]);
1484 return $this->hashPart($codespan);
1485 }
1486 return $token; // return as text since no ending marker found.
1487 default:
1488 return $this->hashPart($token);
1489 }
1490 }
1491
1492
1493 function outdent($text) {
1494 #
1495 # Remove one level of line-leading tabs or spaces
1496 #
1497 return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text);
1498 }
1499
1500
1501 # String length function for detab. `_initDetab` will create a function to
1502 # hanlde UTF-8 if the default function does not exist.
1503 public $utf8_strlen = 'mb_strlen';
1504
1505 function detab($text) {
1506 #
1507 # Replace tabs with the appropriate amount of space.
1508 #
1509 # For each line we separate the line in blocks delemited by
1510 # tab characters. Then we reconstruct every line by adding the
1511 # appropriate number of space between each blocks.
1512
1513 $text = preg_replace_callback('/^.*\t.*$/m',
1514 array(&$this, '_detab_callback'), $text);
1515
1516 return $text;
1517 }
1518 function _detab_callback($matches) {
1519 $line = $matches[0];
1520 $strlen = $this->utf8_strlen; # strlen function for UTF-8.
1521
1522 # Split in blocks.
1523 $blocks = explode("\t", $line);
1524 # Add each blocks to the line.
1525 $line = $blocks[0];
1526 unset($blocks[0]); # Do not add first block twice.
1527 foreach ($blocks as $block) {
1528 # Calculate amount of space, insert spaces, insert block.
1529 $amount = $this->tab_width -
1530 $strlen($line, 'UTF-8') % $this->tab_width;
1531 $line .= str_repeat(" ", $amount) . $block;
1532 }
1533 return $line;
1534 }
1535
1536 /**
1537 * Check for the availability of the function in the `utf8_strlen` property
1538 * (initially `mb_strlen`). If the function is not available, use jetpack_utf8_strlen
1539 * that will loosely count the number of UTF-8 characters with a regular expression.
1540 */
1541 function _initDetab() {
1542 if ( function_exists( $this->utf8_strlen ) ) {
1543 return;
1544 }
1545 $this->utf8_strlen = 'jetpack_utf8_strlen';
1546 }
1547
1548
1549 function unhash($text) {
1550 #
1551 # Swap back in all the tags hashed by _HashHTMLBlocks.
1552 #
1553 return preg_replace_callback('/(.)\x1A[0-9]+\1/',
1554 array(&$this, '_unhash_callback'), $text);
1555 }
1556 function _unhash_callback($matches) {
1557 return $this->html_hashes[$matches[0]];
1558 }
1559
1560 }
1561
1562
1563 #
1564 # Markdown Extra Parser Class
1565 #
1566
1567 class MarkdownExtra_Parser extends Markdown_Parser {
1568
1569 ### Configuration Variables ###
1570
1571 # Prefix for footnote ids.
1572 public $fn_id_prefix = "";
1573
1574 # Optional title attribute for footnote links and backlinks.
1575 public $fn_link_title = MARKDOWN_FN_LINK_TITLE;
1576 public $fn_backlink_title = MARKDOWN_FN_BACKLINK_TITLE;
1577
1578 # Optional class attribute for footnote links and backlinks.
1579 public $fn_link_class = MARKDOWN_FN_LINK_CLASS;
1580 public $fn_backlink_class = MARKDOWN_FN_BACKLINK_CLASS;
1581
1582 # Optional class prefix for fenced code block.
1583 public $code_class_prefix = MARKDOWN_CODE_CLASS_PREFIX;
1584 # Class attribute for code blocks goes on the `code` tag;
1585 # setting this to true will put attributes on the `pre` tag instead.
1586 public $code_attr_on_pre = MARKDOWN_CODE_ATTR_ON_PRE;
1587
1588 # Predefined abbreviations.
1589 public $predef_abbr = array();
1590
1591 /**
1592 * Reference attribute.
1593 *
1594 * @var array
1595 */
1596 public $ref_attr;
1597
1598 /**
1599 * Parsing mode.
1600 *
1601 * @var string
1602 */
1603 public $mode;
1604
1605
1606 ### Parser Implementation ###
1607
1608 function __construct() {
1609 #
1610 # Constructor function. Initialize the parser object.
1611 #
1612 # Add extra escapable characters before parent constructor
1613 # initialize the table.
1614 $this->escape_chars .= ':|';
1615
1616 # Insert extra document, block, and span transformations.
1617 # Parent constructor will do the sorting.
1618 $this->document_gamut += array(
1619 "doFencedCodeBlocks" => 5,
1620 "stripFootnotes" => 15,
1621 "stripAbbreviations" => 25,
1622 "appendFootnotes" => 50,
1623 );
1624 $this->block_gamut += array(
1625 "doFencedCodeBlocks" => 5,
1626 "doTables" => 15,
1627 "doDefLists" => 45,
1628 );
1629 $this->span_gamut += array(
1630 "doFootnotes" => 5,
1631 "doAbbreviations" => 70,
1632 );
1633
1634 parent::__construct();
1635 }
1636
1637
1638 # Extra variables used during extra transformations.
1639 public $footnotes = array();
1640 public $footnotes_ordered = array();
1641 public $footnotes_ref_count = array();
1642 public $footnotes_numbers = array();
1643 public $abbr_desciptions = array();
1644 public $abbr_word_re = '';
1645
1646 # Give the current footnote number.
1647 public $footnote_counter = 1;
1648
1649
1650 function setup() {
1651 #
1652 # Setting up Extra-specific variables.
1653 #
1654 parent::setup();
1655
1656 $this->footnotes = array();
1657 $this->footnotes_ordered = array();
1658 $this->footnotes_ref_count = array();
1659 $this->footnotes_numbers = array();
1660 $this->abbr_desciptions = array();
1661 $this->abbr_word_re = '';
1662 $this->footnote_counter = 1;
1663
1664 foreach ($this->predef_abbr as $abbr_word => $abbr_desc) {
1665 if ($this->abbr_word_re)
1666 $this->abbr_word_re .= '|';
1667 $this->abbr_word_re .= preg_quote($abbr_word);
1668 $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
1669 }
1670 }
1671
1672 function teardown() {
1673 #
1674 # Clearing Extra-specific variables.
1675 #
1676 $this->footnotes = array();
1677 $this->footnotes_ordered = array();
1678 $this->footnotes_ref_count = array();
1679 $this->footnotes_numbers = array();
1680 $this->abbr_desciptions = array();
1681 $this->abbr_word_re = '';
1682
1683 parent::teardown();
1684 }
1685
1686
1687 ### Extra Attribute Parser ###
1688
1689 # Expression to use to catch attributes (includes the braces)
1690 public $id_class_attr_catch_re = '\{((?:[ ]*[#.][-_:a-zA-Z0-9]+){1,})[ ]*\}';
1691 # Expression to use when parsing in a context when no capture is desired
1692 public $id_class_attr_nocatch_re = '\{(?:[ ]*[#.][-_:a-zA-Z0-9]+){1,}[ ]*\}';
1693
1694 function doExtraAttributes($tag_name, $attr) {
1695 #
1696 # Parse attributes caught by the $this->id_class_attr_catch_re expression
1697 # and return the HTML-formatted list of attributes.
1698 #
1699 # Currently supported attributes are .class and #id.
1700 #
1701 if (empty($attr)) return "";
1702
1703 # Split on components
1704 preg_match_all('/[#.][-_:a-zA-Z0-9]+/', $attr, $matches);
1705 $elements = $matches[0];
1706
1707 # handle classes and ids (only first id taken into account)
1708 $classes = array();
1709 $id = false;
1710 foreach ($elements as $element) {
1711 if ($element[0] == '.') {
1712 $classes[] = substr($element, 1);
1713 } else if ($element[0] == '#') {
1714 if ($id === false) $id = substr($element, 1);
1715 }
1716 }
1717
1718 # compose attributes as string
1719 $attr_str = "";
1720 if (!empty($id)) {
1721 $attr_str .= ' id="'.$id.'"';
1722 }
1723 if (!empty($classes)) {
1724 $attr_str .= ' class="'.implode(" ", $classes).'"';
1725 }
1726 return $attr_str;
1727 }
1728
1729
1730 function stripLinkDefinitions($text) {
1731 #
1732 # Strips link definitions from text, stores the URLs and titles in
1733 # hash references.
1734 #
1735 $less_than_tab = $this->tab_width - 1;
1736
1737 # Link defs are in the form: ^[id]: url "optional title"
1738 $text = preg_replace_callback('{
1739 ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1
1740 [ ]*
1741 \n? # maybe *one* newline
1742 [ ]*
1743 (?:
1744 <(.+?)> # url = $2
1745 |
1746 (\S+?) # url = $3
1747 )
1748 [ ]*
1749 \n? # maybe one newline
1750 [ ]*
1751 (?:
1752 (?<=\s) # lookbehind for whitespace
1753 ["(]
1754 (.*?) # title = $4
1755 [")]
1756 [ ]*
1757 )? # title is optional
1758 (?:[ ]* '.$this->id_class_attr_catch_re.' )? # $5 = extra id & class attr
1759 (?:\n+|\Z)
1760 }xm',
1761 array(&$this, '_stripLinkDefinitions_callback'),
1762 $text);
1763 return $text;
1764 }
1765 function _stripLinkDefinitions_callback($matches) {
1766 $link_id = strtolower($matches[1]);
1767 $url = $matches[2] == '' ? $matches[3] : $matches[2];
1768 $this->urls[$link_id] = $url;
1769 $this->titles[$link_id] =& $matches[4];
1770 $this->ref_attr[$link_id] = $this->doExtraAttributes("", $dummy =& $matches[5]);
1771 return ''; # String that will replace the block
1772 }
1773
1774
1775 ### HTML Block Parser ###
1776
1777 # Tags that are always treated as block tags:
1778 public $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend|article|section|nav|aside|hgroup|header|footer|figcaption';
1779
1780 # Tags treated as block tags only if the opening tag is alone on its line:
1781 public $context_block_tags_re = 'script|noscript|ins|del|iframe|object|source|track|param|math|svg|canvas|audio|video';
1782
1783 # Tags where markdown="1" default to span mode:
1784 public $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address';
1785
1786 # Tags which must not have their contents modified, no matter where
1787 # they appear:
1788 public $clean_tags_re = 'script|math|svg';
1789
1790 # Tags that do not need to be closed.
1791 public $auto_close_tags_re = 'hr|img|param|source|track';
1792
1793
1794 function hashHTMLBlocks($text) {
1795 #
1796 # Hashify HTML Blocks and "clean tags".
1797 #
1798 # We only want to do this for block-level HTML tags, such as headers,
1799 # lists, and tables. That's because we still want to wrap <p>s around
1800 # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
1801 # phrase emphasis, and spans. The list of tags we're looking for is
1802 # hard-coded.
1803 #
1804 # This works by calling _HashHTMLBlocks_InMarkdown, which then calls
1805 # _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1"
1806 # attribute is found within a tag, _HashHTMLBlocks_InHTML calls back
1807 # _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag.
1808 # These two functions are calling each other. It's recursive!
1809 #
1810 if ($this->no_markup) return $text;
1811
1812 #
1813 # Call the HTML-in-Markdown hasher.
1814 #
1815 list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text);
1816
1817 return $text;
1818 }
1819 function _hashHTMLBlocks_inMarkdown($text, $indent = 0,
1820 $enclosing_tag_re = '', $span = false)
1821 {
1822 #
1823 # Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags.
1824 #
1825 # * $indent is the number of space to be ignored when checking for code
1826 # blocks. This is important because if we don't take the indent into
1827 # account, something like this (which looks right) won't work as expected:
1828 #
1829 # <div>
1830 # <div markdown="1">
1831 # Hello World. <-- Is this a Markdown code block or text?
1832 # </div> <-- Is this a Markdown code block or a real tag?
1833 # <div>
1834 #
1835 # If you don't like this, just don't indent the tag on which
1836 # you apply the markdown="1" attribute.
1837 #
1838 # * If $enclosing_tag_re is not empty, stops at the first unmatched closing
1839 # tag with that name. Nested tags supported.
1840 #
1841 # * If $span is true, text inside must treated as span. So any double
1842 # newline will be replaced by a single newline so that it does not create
1843 # paragraphs.
1844 #
1845 # Returns an array of that form: ( processed text , remaining text )
1846 #
1847 if ($text === '') return array('', '');
1848
1849 # Regex to check for the presence of newlines around a block tag.
1850 $newline_before_re = '/(?:^\n?|\n\n)*$/';
1851 $newline_after_re =
1852 '{
1853 ^ # Start of text following the tag.
1854 (?>[ ]*<!--.*?-->)? # Optional comment.
1855 [ ]*\n # Must be followed by newline.
1856 }xs';
1857
1858 # Regex to match any tag.
1859 $block_tag_re =
1860 '{
1861 ( # $2: Capture whole tag.
1862 </? # Any opening or closing tag.
1863 (?> # Tag name.
1864 '.$this->block_tags_re.' |
1865 '.$this->context_block_tags_re.' |
1866 '.$this->clean_tags_re.' |
1867 (?!\s)'.$enclosing_tag_re.'
1868 )
1869 (?:
1870 (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
1871 (?>
1872 ".*?" | # Double quotes (can contain `>`)
1873 \'.*?\' | # Single quotes (can contain `>`)
1874 .+? # Anything but quotes and `>`.
1875 )*?
1876 )?
1877 > # End of tag.
1878 |
1879 <!-- .*? --> # HTML Comment
1880 |
1881 <\?.*?\?> | <%.*?%> # Processing instruction
1882 |
1883 <!\[CDATA\[.*?\]\]> # CData Block
1884 '. ( !$span ? ' # If not in span.
1885 |
1886 # Indented code block
1887 (?: ^[ ]*\n | ^ | \n[ ]*\n )
1888 [ ]{'.($indent+4).'}[^\n]* \n
1889 (?>
1890 (?: [ ]{'.($indent+4).'}[^\n]* | [ ]* ) \n
1891 )*
1892 |
1893 # Fenced code block marker
1894 (?<= ^ | \n )
1895 [ ]{0,'.($indent+3).'}(?:~{3,}|`{3,})
1896 [ ]*
1897 (?:
1898 \.?[-_:a-zA-Z0-9]+ # standalone class name
1899 |
1900 '.$this->id_class_attr_nocatch_re.' # extra attributes
1901 )?
1902 [ ]*
1903 (?= \n )
1904 ' : '' ). ' # End (if not is span).
1905 |
1906 # Code span marker
1907 # Note, this regex needs to go after backtick fenced
1908 # code blocks but it should also be kept outside of the
1909 # "if not in span" condition adding backticks to the parser
1910 `+
1911 )
1912 }xs';
1913
1914
1915 $depth = 0; # Current depth inside the tag tree.
1916 $parsed = ""; # Parsed text that will be returned.
1917
1918 #
1919 # Loop through every tag until we find the closing tag of the parent
1920 # or loop until reaching the end of text if no parent tag specified.
1921 #
1922 do {
1923 #
1924 # Split the text using the first $tag_match pattern found.
1925 # Text before pattern will be first in the array, text after
1926 # pattern will be at the end, and between will be any catches made
1927 # by the pattern.
1928 #
1929 $parts = preg_split($block_tag_re, $text, 2,
1930 PREG_SPLIT_DELIM_CAPTURE);
1931
1932 # If in Markdown span mode, add a empty-string span-level hash
1933 # after each newline to prevent triggering any block element.
1934 if ($span) {
1935 $void = $this->hashPart("", ':');
1936 $newline = "$void\n";
1937 $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void;
1938 }
1939
1940 $parsed .= $parts[0]; # Text before current tag.
1941
1942 # If end of $text has been reached. Stop loop.
1943 if (count($parts) < 3) {
1944 $text = "";
1945 break;
1946 }
1947
1948 $tag = $parts[1]; # Tag to handle.
1949 $text = $parts[2]; # Remaining text after current tag.
1950 $tag_re = preg_quote($tag); # For use in a regular expression.
1951
1952 #
1953 # Check for: Fenced code block marker.
1954 # Note: need to recheck the whole tag to disambiguate backtick
1955 # fences from code spans
1956 #
1957 if (preg_match('{^\n?([ ]{0,'.($indent+3).'})(~{3,}|`{3,})[ ]*(?:\.?[-_:a-zA-Z0-9]+|'.$this->id_class_attr_nocatch_re.')?[ ]*\n?$}', $tag, $capture)) {
1958 # Fenced code block marker: find matching end marker.
1959 $fence_indent = strlen($capture[1]); # use captured indent in re
1960 $fence_re = $capture[2]; # use captured fence in re
1961 if (preg_match('{^(?>.*\n)*?[ ]{'.($fence_indent).'}'.$fence_re.'[ ]*(?:\n|$)}', $text,
1962 $matches))
1963 {
1964 # End marker found: pass text unchanged until marker.
1965 $parsed .= $tag . $matches[0];
1966 $text = substr($text, strlen($matches[0]));
1967 }
1968 else {
1969 # No end marker: just skip it.
1970 $parsed .= $tag;
1971 }
1972 }
1973 #
1974 # Check for: Indented code block.
1975 #
1976 else if ($tag[0] == "\n" || $tag[0] == " ") {
1977 # Indented code block: pass it unchanged, will be handled
1978 # later.
1979 $parsed .= $tag;
1980 }
1981 #
1982 # Check for: Code span marker
1983 # Note: need to check this after backtick fenced code blocks
1984 #
1985 else if ($tag[0] == "`") {
1986 # Find corresponding end marker.
1987 $tag_re = preg_quote($tag);
1988 if (preg_match('{^(?>.+?|\n(?!\n))*?(?<!`)'.$tag_re.'(?!`)}',
1989 $text, $matches))
1990 {
1991 # End marker found: pass text unchanged until marker.
1992 $parsed .= $tag . $matches[0];
1993 $text = substr($text, strlen($matches[0]));
1994 }
1995 else {
1996 # Unmatched marker: just skip it.
1997 $parsed .= $tag;
1998 }
1999 }
2000 #
2001 # Check for: Opening Block level tag or
2002 # Opening Context Block tag (like ins and del)
2003 # used as a block tag (tag is alone on it's line).
2004 #
2005 else if (preg_match('{^<(?:'.$this->block_tags_re.')\b}', $tag) ||
2006 ( preg_match('{^<(?:'.$this->context_block_tags_re.')\b}', $tag) &&
2007 preg_match($newline_before_re, $parsed) &&
2008 preg_match($newline_after_re, $text) )
2009 )
2010 {
2011 # Need to parse tag and following text using the HTML parser.
2012 list($block_text, $text) =
2013 $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true);
2014
2015 # Make sure it stays outside of any paragraph by adding newlines.
2016 $parsed .= "\n\n$block_text\n\n";
2017 }
2018 #
2019 # Check for: Clean tag (like script, math)
2020 # HTML Comments, processing instructions.
2021 #
2022 else if (preg_match('{^<(?:'.$this->clean_tags_re.')\b}', $tag) ||
2023 $tag[1] == '!' || $tag[1] == '?')
2024 {
2025 # Need to parse tag and following text using the HTML parser.
2026 # (don't check for markdown attribute)
2027 list($block_text, $text) =
2028 $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false);
2029
2030 $parsed .= $block_text;
2031 }
2032 #
2033 # Check for: Tag with same name as enclosing tag.
2034 #
2035 else if ($enclosing_tag_re !== '' &&
2036 # Same name as enclosing tag.
2037 preg_match('{^</?(?:'.$enclosing_tag_re.')\b}', $tag))
2038 {
2039 #
2040 # Increase/decrease nested tag count.
2041 #
2042 if ($tag[1] == '/') $depth--;
2043 else if ($tag[strlen($tag)-2] != '/') $depth++;
2044
2045 if ($depth < 0) {
2046 #
2047 # Going out of parent element. Clean up and break so we
2048 # return to the calling function.
2049 #
2050 $text = $tag . $text;
2051 break;
2052 }
2053
2054 $parsed .= $tag;
2055 }
2056 else {
2057 $parsed .= $tag;
2058 }
2059 } while ($depth >= 0);
2060
2061 return array($parsed, $text);
2062 }
2063 function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) {
2064 #
2065 # Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags.
2066 #
2067 # * Calls $hash_method to convert any blocks.
2068 # * Stops when the first opening tag closes.
2069 # * $md_attr indicate if the use of the `markdown="1"` attribute is allowed.
2070 # (it is not inside clean tags)
2071 #
2072 # Returns an array of that form: ( processed text , remaining text )
2073 #
2074 if ($text === '') return array('', '');
2075
2076 # Regex to match `markdown` attribute inside of a tag.
2077 $markdown_attr_re = '
2078 {
2079 \s* # Eat whitespace before the `markdown` attribute
2080 markdown
2081 \s*=\s*
2082 (?>
2083 (["\']) # $1: quote delimiter
2084 (.*?) # $2: attribute value
2085 \1 # matching delimiter
2086 |
2087 ([^\s>]*) # $3: unquoted attribute value
2088 )
2089 () # $4: make $3 always defined (avoid warnings)
2090 }xs';
2091
2092 # Regex to match any tag.
2093 $tag_re = '{
2094 ( # $2: Capture whole tag.
2095 </? # Any opening or closing tag.
2096 [\w:$]+ # Tag name.
2097 (?:
2098 (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
2099 (?>
2100 ".*?" | # Double quotes (can contain `>`)
2101 \'.*?\' | # Single quotes (can contain `>`)
2102 .+? # Anything but quotes and `>`.
2103 )*?
2104 )?
2105 > # End of tag.
2106 |
2107 <!-- .*? --> # HTML Comment
2108 |
2109 <\?.*?\?> | <%.*?%> # Processing instruction
2110 |
2111 <!\[CDATA\[.*?\]\]> # CData Block
2112 )
2113 }xs';
2114
2115 $original_text = $text; # Save original text in case of faliure.
2116
2117 $depth = 0; # Current depth inside the tag tree.
2118 $block_text = ""; # Temporary text holder for current text.
2119 $parsed = ""; # Parsed text that will be returned.
2120
2121 #
2122 # Get the name of the starting tag.
2123 # (This pattern makes $base_tag_name_re safe without quoting.)
2124 #
2125 if (preg_match('/^<([\w:$]*)\b/', $text, $matches))
2126 $base_tag_name_re = $matches[1];
2127
2128 #
2129 # Loop through every tag until we find the corresponding closing tag.
2130 #
2131 do {
2132 #
2133 # Split the text using the first $tag_match pattern found.
2134 # Text before pattern will be first in the array, text after
2135 # pattern will be at the end, and between will be any catches made
2136 # by the pattern.
2137 #
2138 $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
2139
2140 if (count($parts) < 3) {
2141 #
2142 # End of $text reached with unbalenced tag(s).
2143 # In that case, we return original text unchanged and pass the
2144 # first character as filtered to prevent an infinite loop in the
2145 # parent function.
2146 #
2147 return array($original_text[0], substr($original_text, 1));
2148 }
2149
2150 $block_text .= $parts[0]; # Text before current tag.
2151 $tag = $parts[1]; # Tag to handle.
2152 $text = $parts[2]; # Remaining text after current tag.
2153
2154 #
2155 # Check for: Auto-close tag (like <hr/>)
2156 # Comments and Processing Instructions.
2157 #
2158 if (preg_match('{^</?(?:'.$this->auto_close_tags_re.')\b}', $tag) ||
2159 $tag[1] == '!' || $tag[1] == '?')
2160 {
2161 # Just add the tag to the block as if it was text.
2162 $block_text .= $tag;
2163 }
2164 else {
2165 #
2166 # Increase/decrease nested tag count. Only do so if
2167 # the tag's name match base tag's.
2168 #
2169 if (preg_match('{^</?'.$base_tag_name_re.'\b}', $tag)) {
2170 if ($tag[1] == '/') $depth--;
2171 else if ($tag[strlen($tag)-2] != '/') $depth++;
2172 }
2173
2174 #
2175 # Check for `markdown="1"` attribute and handle it.
2176 #
2177 if ($md_attr &&
2178 preg_match($markdown_attr_re, $tag, $attr_m) &&
2179 preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3]))
2180 {
2181 # Remove `markdown` attribute from opening tag.
2182 $tag = preg_replace($markdown_attr_re, '', $tag);
2183
2184 # Check if text inside this tag must be parsed in span mode.
2185 $this->mode = $attr_m[2] . $attr_m[3];
2186 $span_mode = $this->mode == 'span' || $this->mode != 'block' &&
2187 preg_match('{^<(?:'.$this->contain_span_tags_re.')\b}', $tag);
2188
2189 # Calculate indent before tag.
2190 if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) {
2191 $strlen = $this->utf8_strlen;
2192 $indent = $strlen($matches[1], 'UTF-8');
2193 } else {
2194 $indent = 0;
2195 }
2196
2197 # End preceding block with this tag.
2198 $block_text .= $tag;
2199 $parsed .= $this->$hash_method($block_text);
2200
2201 # Get enclosing tag name for the ParseMarkdown function.
2202 # (This pattern makes $tag_name_re safe without quoting.)
2203 preg_match('/^<([\w:$]*)\b/', $tag, $matches);
2204 $tag_name_re = $matches[1];
2205
2206 # Parse the content using the HTML-in-Markdown parser.
2207 list ($block_text, $text)
2208 = $this->_hashHTMLBlocks_inMarkdown($text, $indent,
2209 $tag_name_re, $span_mode);
2210
2211 # Outdent markdown text.
2212 if ($indent > 0) {
2213 $block_text = preg_replace("/^[ ]{1,$indent}/m", "",
2214 $block_text);
2215 }
2216
2217 # Append tag content to parsed text.
2218 if (!$span_mode) $parsed .= "\n\n$block_text\n\n";
2219 else $parsed .= "$block_text";
2220
2221 # Start over with a new block.
2222 $block_text = "";
2223 }
2224 else $block_text .= $tag;
2225 }
2226
2227 } while ($depth > 0);
2228
2229 #
2230 # Hash last block text that wasn't processed inside the loop.
2231 #
2232 $parsed .= $this->$hash_method($block_text);
2233
2234 return array($parsed, $text);
2235 }
2236
2237
2238 function hashClean($text) {
2239 #
2240 # Called whenever a tag must be hashed when a function inserts a "clean" tag
2241 # in $text, it passes through this function and is automaticaly escaped,
2242 # blocking invalid nested overlap.
2243 #
2244 return $this->hashPart($text, 'C');
2245 }
2246
2247
2248 function doAnchors($text) {
2249 #
2250 # Turn Markdown link shortcuts into XHTML <a> tags.
2251 #
2252 if ($this->in_anchor) return $text;
2253 $this->in_anchor = true;
2254
2255 #
2256 # First, handle reference-style links: [link text] [id]
2257 #
2258 $text = preg_replace_callback('{
2259 ( # wrap whole match in $1
2260 \[
2261 ('.$this->nested_brackets_re.') # link text = $2
2262 \]
2263
2264 [ ]? # one optional space
2265 (?:\n[ ]*)? # one optional newline followed by spaces
2266
2267 \[
2268 (.*?) # id = $3
2269 \]
2270 )
2271 }xs',
2272 array(&$this, '_doAnchors_reference_callback'), $text);
2273
2274 #
2275 # Next, inline-style links: [link text](url "optional title")
2276 #
2277 $text = preg_replace_callback('{
2278 ( # wrap whole match in $1
2279 \[
2280 ('.$this->nested_brackets_re.') # link text = $2
2281 \]
2282 \( # literal paren
2283 [ \n]*
2284 (?:
2285 <(.+?)> # href = $3
2286 |
2287 ('.$this->nested_url_parenthesis_re.') # href = $4
2288 )
2289 [ \n]*
2290 ( # $5
2291 ([\'"]) # quote char = $6
2292 (.*?) # Title = $7
2293 \6 # matching quote
2294 [ \n]* # ignore any spaces/tabs between closing quote and )
2295 )? # title is optional
2296 \)
2297 (?:[ ]? '.$this->id_class_attr_catch_re.' )? # $8 = id/class attributes
2298 )
2299 }xs',
2300 array(&$this, '_doAnchors_inline_callback'), $text);
2301
2302 #
2303 # Last, handle reference-style shortcuts: [link text]
2304 # These must come last in case you've also got [link text][1]
2305 # or [link text](/foo)
2306 #
2307 $text = preg_replace_callback('{
2308 ( # wrap whole match in $1
2309 \[
2310 ([^\[\]]+) # link text = $2; can\'t contain [ or ]
2311 \]
2312 )
2313 }xs',
2314 array(&$this, '_doAnchors_reference_callback'), $text);
2315
2316 $this->in_anchor = false;
2317 return $text;
2318 }
2319 function _doAnchors_reference_callback($matches) {
2320 $whole_match = $matches[1];
2321 $link_text = $matches[2];
2322 $link_id =& $matches[3];
2323
2324 if ($link_id == "") {
2325 # for shortcut links like [this][] or [this].
2326 $link_id = $link_text;
2327 }
2328
2329 # lower-case and turn embedded newlines into spaces
2330 $link_id = strtolower($link_id);
2331 $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
2332
2333 if (isset($this->urls[$link_id])) {
2334 $url = $this->urls[$link_id];
2335 $url = $this->encodeAttribute($url);
2336
2337 $result = "<a href=\"$url\"";
2338 if ( isset( $this->titles[$link_id] ) ) {
2339 $title = $this->titles[$link_id];
2340 $title = $this->encodeAttribute($title);
2341 $result .= " title=\"$title\"";
2342 }
2343 if (isset($this->ref_attr[$link_id]))
2344 $result .= $this->ref_attr[$link_id];
2345
2346 $link_text = $this->runSpanGamut($link_text);
2347 $result .= ">$link_text</a>";
2348 $result = $this->hashPart($result);
2349 }
2350 else {
2351 $result = $whole_match;
2352 }
2353 return $result;
2354 }
2355 function _doAnchors_inline_callback($matches) {
2356 $whole_match = $matches[1];
2357 $link_text = $this->runSpanGamut($matches[2]);
2358 $url = $matches[3] == '' ? $matches[4] : $matches[3];
2359 $title =& $matches[7];
2360 $attr = $this->doExtraAttributes("a", $dummy =& $matches[8]);
2361
2362
2363 $url = $this->encodeAttribute($url);
2364
2365 $result = "<a href=\"$url\"";
2366 if (isset($title)) {
2367 $title = $this->encodeAttribute($title);
2368 $result .= " title=\"$title\"";
2369 }
2370 $result .= $attr;
2371
2372 $link_text = $this->runSpanGamut($link_text);
2373 $result .= ">$link_text</a>";
2374
2375 return $this->hashPart($result);
2376 }
2377
2378
2379 function doImages($text) {
2380 #
2381 # Turn Markdown image shortcuts into <img> tags.
2382 #
2383 #
2384 # First, handle reference-style labeled images: ![alt text][id]
2385 #
2386 $text = preg_replace_callback('{
2387 ( # wrap whole match in $1
2388 !\[
2389 ('.$this->nested_brackets_re.') # alt text = $2
2390 \]
2391
2392 [ ]? # one optional space
2393 (?:\n[ ]*)? # one optional newline followed by spaces
2394
2395 \[
2396 (.*?) # id = $3
2397 \]
2398
2399 )
2400 }xs',
2401 array(&$this, '_doImages_reference_callback'), $text);
2402
2403 #
2404 # Next, handle inline images: ![alt text](url "optional title")
2405 # Don't forget: encode * and _
2406 #
2407 $text = preg_replace_callback('{
2408 ( # wrap whole match in $1
2409 !\[
2410 ('.$this->nested_brackets_re.') # alt text = $2
2411 \]
2412 \s? # One optional whitespace character
2413 \( # literal paren
2414 [ \n]*
2415 (?:
2416 <(\S*)> # src url = $3
2417 |
2418 ('.$this->nested_url_parenthesis_re.') # src url = $4
2419 )
2420 [ \n]*
2421 ( # $5
2422 ([\'"]) # quote char = $6
2423 (.*?) # title = $7
2424 \6 # matching quote
2425 [ \n]*
2426 )? # title is optional
2427 \)
2428 (?:[ ]? '.$this->id_class_attr_catch_re.' )? # $8 = id/class attributes
2429 )
2430 }xs',
2431 array(&$this, '_doImages_inline_callback'), $text);
2432
2433 return $text;
2434 }
2435 function _doImages_reference_callback($matches) {
2436 $whole_match = $matches[1];
2437 $alt_text = $matches[2];
2438 $link_id = strtolower($matches[3]);
2439
2440 if ($link_id == "") {
2441 $link_id = strtolower($alt_text); # for shortcut links like ![this][].
2442 }
2443
2444 $alt_text = $this->encodeAttribute($alt_text);
2445 if (isset($this->urls[$link_id])) {
2446 $url = $this->encodeAttribute($this->urls[$link_id]);
2447 $result = "<img src=\"$url\" alt=\"$alt_text\"";
2448 if (isset($this->titles[$link_id])) {
2449 $title = $this->titles[$link_id];
2450 $title = $this->encodeAttribute($title);
2451 $result .= " title=\"$title\"";
2452 }
2453 if (isset($this->ref_attr[$link_id]))
2454 $result .= $this->ref_attr[$link_id];
2455 $result .= $this->empty_element_suffix;
2456 $result = $this->hashPart($result);
2457 }
2458 else {
2459 # If there's no such link ID, leave intact:
2460 $result = $whole_match;
2461 }
2462
2463 return $result;
2464 }
2465 function _doImages_inline_callback($matches) {
2466 $whole_match = $matches[1];
2467 $alt_text = $matches[2];
2468 $url = $matches[3] == '' ? $matches[4] : $matches[3];
2469 $title =& $matches[7];
2470 $attr = $this->doExtraAttributes("img", $dummy =& $matches[8]);
2471
2472 $alt_text = $this->encodeAttribute($alt_text);
2473 $url = $this->encodeAttribute($url);
2474 $result = "<img src=\"$url\" alt=\"$alt_text\"";
2475 if (isset($title)) {
2476 $title = $this->encodeAttribute($title);
2477 $result .= " title=\"$title\""; # $title already quoted
2478 }
2479 $result .= $attr;
2480 $result .= $this->empty_element_suffix;
2481
2482 return $this->hashPart($result);
2483 }
2484
2485
2486 function doHeaders($text) {
2487 #
2488 # Redefined to add id and class attribute support.
2489 #
2490 # Setext-style headers:
2491 # Header 1 {#header1}
2492 # ========
2493 #
2494 # Header 2 {#header2 .class1 .class2}
2495 # --------
2496 #
2497 $text = preg_replace_callback(
2498 '{
2499 (^.+?) # $1: Header text
2500 (?:[ ]+ '.$this->id_class_attr_catch_re.' )? # $3 = id/class attributes
2501 [ ]*\n(=+|-+)[ ]*\n+ # $3: Header footer
2502 }mx',
2503 array(&$this, '_doHeaders_callback_setext'), $text);
2504
2505 # atx-style headers:
2506 # # Header 1 {#header1}
2507 # ## Header 2 {#header2}
2508 # ## Header 2 with closing hashes ## {#header3.class1.class2}
2509 # ...
2510 # ###### Header 6 {.class2}
2511 #
2512 $text = preg_replace_callback('{
2513 ^(\#{1,6}) # $1 = string of #\'s
2514 [ ]*
2515 (.+?) # $2 = Header text
2516 [ ]*
2517 \#* # optional closing #\'s (not counted)
2518 (?:[ ]+ '.$this->id_class_attr_catch_re.' )? # $3 = id/class attributes
2519 [ ]*
2520 \n+
2521 }xm',
2522 array(&$this, '_doHeaders_callback_atx'), $text);
2523
2524 return $text;
2525 }
2526 function _doHeaders_callback_setext($matches) {
2527 if ($matches[3] == '-' && preg_match('{^- }', $matches[1]))
2528 return $matches[0];
2529 $level = $matches[3][0] == '=' ? 1 : 2;
2530 $attr = $this->doExtraAttributes("h$level", $dummy =& $matches[2]);
2531 $block = "<h$level$attr>".$this->runSpanGamut($matches[1])."</h$level>";
2532 return "\n" . $this->hashBlock($block) . "\n\n";
2533 }
2534 function _doHeaders_callback_atx($matches) {
2535 $level = strlen($matches[1]);
2536 $attr = $this->doExtraAttributes("h$level", $dummy =& $matches[3]);
2537 $block = "<h$level$attr>".$this->runSpanGamut($matches[2])."</h$level>";
2538 return "\n" . $this->hashBlock($block) . "\n\n";
2539 }
2540
2541
2542 function doTables($text) {
2543 #
2544 # Form HTML tables.
2545 #
2546 $less_than_tab = $this->tab_width - 1;
2547 #
2548 # Find tables with leading pipe.
2549 #
2550 # | Header 1 | Header 2
2551 # | -------- | --------
2552 # | Cell 1 | Cell 2
2553 # | Cell 3 | Cell 4
2554 #
2555 $text = preg_replace_callback('
2556 {
2557 ^ # Start of a line
2558 [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
2559 [|] # Optional leading pipe (present)
2560 (.+) \n # $1: Header row (at least one pipe)
2561
2562 [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
2563 [|] ([ ]*[-:]+[-| :]*) \n # $2: Header underline
2564
2565 ( # $3: Cells
2566 (?>
2567 [ ]* # Allowed whitespace.
2568 [|] .* \n # Row content.
2569 )*
2570 )
2571 (?=\n|\Z) # Stop at final double newline.
2572 }xm',
2573 array(&$this, '_doTable_leadingPipe_callback'), $text);
2574
2575 #
2576 # Find tables without leading pipe.
2577 #
2578 # Header 1 | Header 2
2579 # -------- | --------
2580 # Cell 1 | Cell 2
2581 # Cell 3 | Cell 4
2582 #
2583 $text = preg_replace_callback('
2584 {
2585 ^ # Start of a line
2586 [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
2587 (\S.*[|].*) \n # $1: Header row (at least one pipe)
2588
2589 [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
2590 ([-:]+[ ]*[|][-| :]*) \n # $2: Header underline
2591
2592 ( # $3: Cells
2593 (?>
2594 .* [|] .* \n # Row content
2595 )*
2596 )
2597 (?=\n|\Z) # Stop at final double newline.
2598 }xm',
2599 array(&$this, '_DoTable_callback'), $text);
2600
2601 return $text;
2602 }
2603 function _doTable_leadingPipe_callback($matches) {
2604 $head = $matches[1];
2605 $underline = $matches[2];
2606 $content = $matches[3];
2607
2608 # Remove leading pipe for each row.
2609 $content = preg_replace('/^ *[|]/m', '', $content);
2610
2611 return $this->_doTable_callback(array($matches[0], $head, $underline, $content));
2612 }
2613 function _doTable_callback($matches) {
2614 $head = $matches[1];
2615 $underline = $matches[2];
2616 $content = $matches[3];
2617
2618 # Remove any tailing pipes for each line.
2619 $head = preg_replace('/[|] *$/m', '', $head);
2620 $underline = preg_replace('/[|] *$/m', '', $underline);
2621 $content = preg_replace('/[|] *$/m', '', $content);
2622
2623 # Reading alignement from header underline.
2624 $separators = preg_split('/ *[|] */', $underline);
2625 $attr = array();
2626 foreach ($separators as $n => $s) {
2627 if (preg_match('/^ *-+: *$/', $s)) $attr[$n] = ' align="right"';
2628 else if (preg_match('/^ *:-+: *$/', $s))$attr[$n] = ' align="center"';
2629 else if (preg_match('/^ *:-+ *$/', $s)) $attr[$n] = ' align="left"';
2630 else $attr[$n] = '';
2631 }
2632
2633 # Parsing span elements, including code spans, character escapes,
2634 # and inline HTML tags, so that pipes inside those gets ignored.
2635 $head = $this->parseSpan($head);
2636 $headers = preg_split('/ *[|] */', $head);
2637 $col_count = count($headers);
2638 $attr = array_pad($attr, $col_count, '');
2639
2640 # Write column headers.
2641 $text = "<table>\n";
2642 $text .= "<thead>\n";
2643 $text .= "<tr>\n";
2644 foreach ($headers as $n => $header)
2645 $text .= " <th$attr[$n]>".$this->runSpanGamut(trim($header))."</th>\n";
2646 $text .= "</tr>\n";
2647 $text .= "</thead>\n";
2648
2649 # Split content by row.
2650 $rows = explode("\n", trim($content, "\n"));
2651
2652 $text .= "<tbody>\n";
2653 foreach ($rows as $row) {
2654 # Parsing span elements, including code spans, character escapes,
2655 # and inline HTML tags, so that pipes inside those gets ignored.
2656 $row = $this->parseSpan($row);
2657
2658 # Split row by cell.
2659 $row_cells = preg_split('/ *[|] */', $row, $col_count);
2660 $row_cells = array_pad($row_cells, $col_count, '');
2661
2662 $text .= "<tr>\n";
2663 foreach ($row_cells as $n => $cell)
2664 $text .= " <td$attr[$n]>".$this->runSpanGamut(trim($cell))."</td>\n";
2665 $text .= "</tr>\n";
2666 }
2667 $text .= "</tbody>\n";
2668 $text .= "</table>";
2669
2670 return $this->hashBlock($text) . "\n";
2671 }
2672
2673
2674 function doDefLists($text) {
2675 #
2676 # Form HTML definition lists.
2677 #
2678 $less_than_tab = $this->tab_width - 1;
2679
2680 # Re-usable pattern to match any entire dl list:
2681 $whole_list_re = '(?>
2682 ( # $1 = whole list
2683 ( # $2
2684 [ ]{0,'.$less_than_tab.'}
2685 ((?>.*\S.*\n)+) # $3 = defined term
2686 \n?
2687 [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
2688 )
2689 (?s:.+?)
2690 ( # $4
2691 \z
2692 |
2693 \n{2,}
2694 (?=\S)
2695 (?! # Negative lookahead for another term
2696 [ ]{0,'.$less_than_tab.'}
2697 (?: \S.*\n )+? # defined term
2698 \n?
2699 [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
2700 )
2701 (?! # Negative lookahead for another definition
2702 [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
2703 )
2704 )
2705 )
2706 )'; // mx
2707
2708 $text = preg_replace_callback('{
2709 (?>\A\n?|(?<=\n\n))
2710 '.$whole_list_re.'
2711 }mx',
2712 array(&$this, '_doDefLists_callback'), $text);
2713
2714 return $text;
2715 }
2716 function _doDefLists_callback($matches) {
2717 # Re-usable patterns to match list item bullets and number markers:
2718 $list = $matches[1];
2719
2720 # Turn double returns into triple returns, so that we can make a
2721 # paragraph for the last item in a list, if necessary:
2722 $result = trim($this->processDefListItems($list));
2723 $result = "<dl>\n" . $result . "\n</dl>";
2724 return $this->hashBlock($result) . "\n\n";
2725 }
2726
2727
2728 function processDefListItems($list_str) {
2729 #
2730 # Process the contents of a single definition list, splitting it
2731 # into individual term and definition list items.
2732 #
2733 $less_than_tab = $this->tab_width - 1;
2734
2735 # trim trailing blank lines:
2736 $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
2737
2738 # Process definition terms.
2739 $list_str = preg_replace_callback('{
2740 (?>\A\n?|\n\n+) # leading line
2741 ( # definition terms = $1
2742 [ ]{0,'.$less_than_tab.'} # leading whitespace
2743 (?!\:[ ]|[ ]) # negative lookahead for a definition
2744 # mark (colon) or more whitespace.
2745 (?> \S.* \n)+? # actual term (not whitespace).
2746 )
2747 (?=\n?[ ]{0,3}:[ ]) # lookahead for following line feed
2748 # with a definition mark.
2749 }xm',
2750 array(&$this, '_processDefListItems_callback_dt'), $list_str);
2751
2752 # Process actual definitions.
2753 $list_str = preg_replace_callback('{
2754 \n(\n+)? # leading line = $1
2755 ( # marker space = $2
2756 [ ]{0,'.$less_than_tab.'} # whitespace before colon
2757 \:[ ]+ # definition mark (colon)
2758 )
2759 ((?s:.+?)) # definition text = $3
2760 (?= \n+ # stop at next definition mark,
2761 (?: # next term or end of text
2762 [ ]{0,'.$less_than_tab.'} \:[ ] |
2763 <dt> | \z
2764 )
2765 )
2766 }xm',
2767 array(&$this, '_processDefListItems_callback_dd'), $list_str);
2768
2769 return $list_str;
2770 }
2771 function _processDefListItems_callback_dt($matches) {
2772 $terms = explode("\n", trim($matches[1]));
2773 $text = '';
2774 foreach ($terms as $term) {
2775 $term = $this->runSpanGamut(trim($term));
2776 $text .= "\n<dt>" . $term . "</dt>";
2777 }
2778 return $text . "\n";
2779 }
2780 function _processDefListItems_callback_dd($matches) {
2781 $leading_line = $matches[1];
2782 $marker_space = $matches[2];
2783 $def = $matches[3];
2784
2785 if ($leading_line || preg_match('/\n{2,}/', $def)) {
2786 # Replace marker with the appropriate whitespace indentation
2787 $def = str_repeat(' ', strlen($marker_space)) . $def;
2788 $def = $this->runBlockGamut($this->outdent($def . "\n\n"));
2789 $def = "\n". $def ."\n";
2790 }
2791 else {
2792 $def = rtrim($def);
2793 $def = $this->runSpanGamut($this->outdent($def));
2794 }
2795
2796 return "\n<dd>" . $def . "</dd>\n";
2797 }
2798
2799
2800 function doFencedCodeBlocks($text) {
2801 #
2802 # Adding the fenced code block syntax to regular Markdown:
2803 #
2804 # ~~~
2805 # Code block
2806 # ~~~
2807 #
2808 $less_than_tab = $this->tab_width;
2809
2810 $text = preg_replace_callback('{
2811 (?:\n|\A)
2812 # 1: Opening marker
2813 (
2814 (?:~{3,}|`{3,}) # 3 or more tildes/backticks.
2815 )
2816 [ ]*
2817 (?:
2818 \.?([-_:a-zA-Z0-9]+) # 2: standalone class name
2819 |
2820 '.$this->id_class_attr_catch_re.' # 3: Extra attributes
2821 )?
2822 [ ]* \n # Whitespace and newline following marker.
2823
2824 # 4: Content
2825 (
2826 (?>
2827 (?!\1 [ ]* \n) # Not a closing marker.
2828 .*\n+
2829 )+
2830 )
2831
2832 # Closing marker.
2833 \1 [ ]* (?= \n )
2834 }xm',
2835 array(&$this, '_doFencedCodeBlocks_callback'), $text);
2836
2837 return $text;
2838 }
2839 function _doFencedCodeBlocks_callback($matches) {
2840 $classname =& $matches[2];
2841 $attrs =& $matches[3];
2842 $codeblock = $matches[4];
2843 $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
2844 $codeblock = preg_replace_callback('/^\n+/',
2845 array(&$this, '_doFencedCodeBlocks_newlines'), $codeblock);
2846
2847 if ($classname != "") {
2848 if ($classname[0] == '.')
2849 $classname = substr($classname, 1);
2850 $attr_str = ' class="'.$this->code_class_prefix.$classname.'"';
2851 } else {
2852 $attr_str = $this->doExtraAttributes($this->code_attr_on_pre ? "pre" : "code", $attrs);
2853 }
2854 $pre_attr_str = $this->code_attr_on_pre ? $attr_str : '';
2855 $code_attr_str = $this->code_attr_on_pre ? '' : $attr_str;
2856 $codeblock = "<pre$pre_attr_str><code$code_attr_str>$codeblock</code></pre>";
2857
2858 return "\n\n".$this->hashBlock($codeblock)."\n\n";
2859 }
2860 function _doFencedCodeBlocks_newlines($matches) {
2861 return str_repeat("<br$this->empty_element_suffix",
2862 strlen($matches[0]));
2863 }
2864
2865
2866 #
2867 # Redefining emphasis markers so that emphasis by underscore does not
2868 # work in the middle of a word.
2869 #
2870 public $em_relist = array(
2871 '' => '(?:(?<!\*)\*(?!\*)|(?<![a-zA-Z0-9_])_(?!_))(?=\S|$)(?![\.,:;]\s)',
2872 '*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
2873 '_' => '(?<=\S|^)(?<!_)_(?![a-zA-Z0-9_])',
2874 );
2875 public $strong_relist = array(
2876 '' => '(?:(?<!\*)\*\*(?!\*)|(?<![a-zA-Z0-9_])__(?!_))(?=\S|$)(?![\.,:;]\s)',
2877 '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
2878 '__' => '(?<=\S|^)(?<!_)__(?![a-zA-Z0-9_])',
2879 );
2880 public $em_strong_relist = array(
2881 '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<![a-zA-Z0-9_])___(?!_))(?=\S|$)(?![\.,:;]\s)',
2882 '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
2883 '___' => '(?<=\S|^)(?<!_)___(?![a-zA-Z0-9_])',
2884 );
2885
2886
2887 function formParagraphs($text) {
2888 #
2889 # Params:
2890 # $text - string to process with html <p> tags
2891 #
2892 # Strip leading and trailing lines:
2893 $text = preg_replace('/\A\n+|\n+\z/', '', $text);
2894
2895 $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
2896
2897 #
2898 # Wrap <p> tags and unhashify HTML blocks
2899 #
2900 foreach ($grafs as $key => $value) {
2901 $value = trim($this->runSpanGamut($value));
2902
2903 # Check if this should be enclosed in a paragraph.
2904 # Clean tag hashes & block tag hashes are left alone.
2905 $is_p = !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value);
2906
2907 if ($is_p) {
2908 $value = "<p>$value</p>";
2909 }
2910 $grafs[$key] = $value;
2911 }
2912
2913 # Join grafs in one text, then unhash HTML tags.
2914 $text = implode("\n\n", $grafs);
2915
2916 # Finish by removing any tag hashes still present in $text.
2917 $text = $this->unhash($text);
2918
2919 return $text;
2920 }
2921
2922
2923 ### Footnotes
2924
2925 function stripFootnotes($text) {
2926 #
2927 # Strips link definitions from text, stores the URLs and titles in
2928 # hash references.
2929 #
2930 $less_than_tab = $this->tab_width - 1;
2931
2932 # Link defs are in the form: [^id]: url "optional title"
2933 $text = preg_replace_callback('{
2934 ^[ ]{0,'.$less_than_tab.'}\[\^(.+?)\][ ]?: # note_id = $1
2935 [ ]*
2936 \n? # maybe *one* newline
2937 ( # text = $2 (no blank lines allowed)
2938 (?:
2939 .+ # actual text
2940 |
2941 \n # newlines but
2942 (?!\[\^.+?\]:\s)# negative lookahead for footnote marker.
2943 (?!\n+[ ]{0,3}\S)# ensure line is not blank and followed
2944 # by non-indented content
2945 )*
2946 )
2947 }xm',
2948 array(&$this, '_stripFootnotes_callback'),
2949 $text);
2950 return $text;
2951 }
2952 function _stripFootnotes_callback($matches) {
2953 $note_id = $this->fn_id_prefix . $matches[1];
2954 $this->footnotes[$note_id] = $this->outdent($matches[2]);
2955 return ''; # String that will replace the block
2956 }
2957
2958
2959 function doFootnotes($text) {
2960 #
2961 # Replace footnote references in $text [^id] with a special text-token
2962 # which will be replaced by the actual footnote marker in appendFootnotes.
2963 #
2964 if (!$this->in_anchor) {
2965 $text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text);
2966 }
2967 return $text;
2968 }
2969
2970
2971 function appendFootnotes($text) {
2972 #
2973 # Append footnote list to text.
2974 #
2975 $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
2976 array(&$this, '_appendFootnotes_callback'), $text);
2977
2978 if (!empty($this->footnotes_ordered)) {
2979 $text .= "\n\n";
2980 $text .= "<div class=\"footnotes\">\n";
2981 $text .= "<hr". $this->empty_element_suffix ."\n";
2982 $text .= "<ol>\n\n";
2983
2984 $attr = "";
2985 if ($this->fn_backlink_class != "") {
2986 $class = $this->fn_backlink_class;
2987 $class = $this->encodeAttribute($class);
2988 $attr .= " class=\"$class\"";
2989 }
2990 if ($this->fn_backlink_title != "") {
2991 $title = $this->fn_backlink_title;
2992 $title = $this->encodeAttribute($title);
2993 $attr .= " title=\"$title\"";
2994 }
2995 $num = 0;
2996
2997 while (!empty($this->footnotes_ordered)) {
2998 $footnote = reset($this->footnotes_ordered);
2999 $note_id = key($this->footnotes_ordered);
3000 unset($this->footnotes_ordered[$note_id]);
3001 $ref_count = $this->footnotes_ref_count[$note_id];
3002 unset($this->footnotes_ref_count[$note_id]);
3003 unset($this->footnotes[$note_id]);
3004
3005 $footnote .= "\n"; # Need to append newline before parsing.
3006 $footnote = $this->runBlockGamut("$footnote\n");
3007 $footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
3008 array(&$this, '_appendFootnotes_callback'), $footnote);
3009
3010 $attr = str_replace("%%", ++$num, $attr);
3011 $note_id = $this->encodeAttribute($note_id);
3012
3013 # Prepare backlink, multiple backlinks if multiple references
3014 $backlink = "<a href=\"#fnref:$note_id\"$attr>&#8617;</a>";
3015 for ($ref_num = 2; $ref_num <= $ref_count; ++$ref_num) {
3016 $backlink .= " <a href=\"#fnref$ref_num:$note_id\"$attr>&#8617;</a>";
3017 }
3018 # Add backlink to last paragraph; create new paragraph if needed.
3019 if (preg_match('{</p>$}', $footnote)) {
3020 $footnote = substr($footnote, 0, -4) . "&#160;$backlink</p>";
3021 } else {
3022 $footnote .= "\n\n<p>$backlink</p>";
3023 }
3024
3025 $text .= "<li id=\"fn:$note_id\">\n";
3026 $text .= $footnote . "\n";
3027 $text .= "</li>\n\n";
3028 }
3029
3030 $text .= "</ol>\n";
3031 $text .= "</div>";
3032 }
3033 return $text;
3034 }
3035 function _appendFootnotes_callback($matches) {
3036 $node_id = $this->fn_id_prefix . $matches[1];
3037
3038 # Create footnote marker only if it has a corresponding footnote *and*
3039 # the footnote hasn't been used by another marker.
3040 if (isset($this->footnotes[$node_id])) {
3041 $num =& $this->footnotes_numbers[$node_id];
3042 if (!isset($num)) {
3043 # Transfer footnote content to the ordered list and give it its
3044 # number
3045 $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id];
3046 $this->footnotes_ref_count[$node_id] = 1;
3047 $num = $this->footnote_counter++;
3048 $ref_count_mark = '';
3049 } else {
3050 $ref_count_mark = $this->footnotes_ref_count[$node_id] += 1;
3051 }
3052
3053 $attr = "";
3054 if ($this->fn_link_class != "") {
3055 $class = $this->fn_link_class;
3056 $class = $this->encodeAttribute($class);
3057 $attr .= " class=\"$class\"";
3058 }
3059 if ($this->fn_link_title != "") {
3060 $title = $this->fn_link_title;
3061 $title = $this->encodeAttribute($title);
3062 $attr .= " title=\"$title\"";
3063 }
3064
3065 $attr = str_replace("%%", $num, $attr);
3066 $node_id = $this->encodeAttribute($node_id);
3067
3068 return
3069 "<sup id=\"fnref$ref_count_mark:$node_id\">".
3070 "<a href=\"#fn:$node_id\"$attr>$num</a>".
3071 "</sup>";
3072 }
3073
3074 return "[^".$matches[1]."]";
3075 }
3076
3077
3078 ### Abbreviations ###
3079
3080 function stripAbbreviations($text) {
3081 #
3082 # Strips abbreviations from text, stores titles in hash references.
3083 #
3084 $less_than_tab = $this->tab_width - 1;
3085
3086 # Link defs are in the form: [id]*: url "optional title"
3087 $text = preg_replace_callback('{
3088 ^[ ]{0,'.$less_than_tab.'}\*\[(.+?)\][ ]?: # abbr_id = $1
3089 (.*) # text = $2 (no blank lines allowed)
3090 }xm',
3091 array(&$this, '_stripAbbreviations_callback'),
3092 $text);
3093 return $text;
3094 }
3095 function _stripAbbreviations_callback($matches) {
3096 $abbr_word = $matches[1];
3097 $abbr_desc = $matches[2];
3098 if ($this->abbr_word_re)
3099 $this->abbr_word_re .= '|';
3100 $this->abbr_word_re .= preg_quote($abbr_word);
3101 $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
3102 return ''; # String that will replace the block
3103 }
3104
3105
3106 function doAbbreviations($text) {
3107 #
3108 # Find defined abbreviations in text and wrap them in <abbr> elements.
3109 #
3110 if ($this->abbr_word_re) {
3111 // cannot use the /x modifier because abbr_word_re may
3112 // contain significant spaces:
3113 $text = preg_replace_callback('{'.
3114 '(?<![\w\x1A])'.
3115 '(?:'.$this->abbr_word_re.')'.
3116 '(?![\w\x1A])'.
3117 '}',
3118 array(&$this, '_doAbbreviations_callback'), $text);
3119 }
3120 return $text;
3121 }
3122 function _doAbbreviations_callback($matches) {
3123 $abbr = $matches[0];
3124 if (isset($this->abbr_desciptions[$abbr])) {
3125 $desc = $this->abbr_desciptions[$abbr];
3126 if (empty($desc)) {
3127 return $this->hashPart("<abbr>$abbr</abbr>");
3128 } else {
3129 $desc = $this->encodeAttribute($desc);
3130 return $this->hashPart("<abbr title=\"$desc\">$abbr</abbr>");
3131 }
3132 } else {
3133 return $matches[0];
3134 }
3135 }
3136
3137 }
3138
3139
3140 /*
3141
3142 PHP Markdown Extra
3143 ==================
3144
3145 Description
3146 -----------
3147
3148 This is a PHP port of the original Markdown formatter written in Perl
3149 by John Gruber. This special "Extra" version of PHP Markdown features
3150 further enhancements to the syntax for making additional constructs
3151 such as tables and definition list.
3152
3153 Markdown is a text-to-HTML filter; it translates an easy-to-read /
3154 easy-to-write structured text format into HTML. Markdown's text format
3155 is mostly similar to that of plain text email, and supports features such
3156 as headers, *emphasis*, code blocks, blockquotes, and links.
3157
3158 Markdown's syntax is designed not as a generic markup language, but
3159 specifically to serve as a front-end to (X)HTML. You can use span-level
3160 HTML tags anywhere in a Markdown document, and you can use block level
3161 HTML tags (like <div> and <table> as well).
3162
3163 For more information about Markdown's syntax, see:
3164
3165 <http://daringfireball.net/projects/markdown/>
3166
3167
3168 Bugs
3169 ----
3170
3171 To file bug reports please send email to:
3172
3173 <michel.fortin@michelf.ca>
3174
3175 Please include with your report: (1) the example input; (2) the output you
3176 expected; (3) the output Markdown actually produced.
3177
3178
3179 Version History
3180 ---------------
3181
3182 See the readme file for detailed release notes for this version.
3183
3184
3185 Copyright and License
3186 ---------------------
3187
3188 PHP Markdown & Extra
3189 Copyright (c) 2004-2013 Michel Fortin
3190 <http://michelf.ca/>
3191 All rights reserved.
3192
3193 Based on Markdown
3194 Copyright (c) 2003-2006 John Gruber
3195 <http://daringfireball.net/>
3196 All rights reserved.
3197
3198 Redistribution and use in source and binary forms, with or without
3199 modification, are permitted provided that the following conditions are
3200 met:
3201
3202 * Redistributions of source code must retain the above copyright notice,
3203 this list of conditions and the following disclaimer.
3204
3205 * Redistributions in binary form must reproduce the above copyright
3206 notice, this list of conditions and the following disclaimer in the
3207 documentation and/or other materials provided with the distribution.
3208
3209 * Neither the name "Markdown" nor the names of its contributors may
3210 be used to endorse or promote products derived from this software
3211 without specific prior written permission.
3212
3213 This software is provided by the copyright holders and contributors "as
3214 is" and any express or implied warranties, including, but not limited
3215 to, the implied warranties of merchantability and fitness for a
3216 particular purpose are disclaimed. In no event shall the copyright owner
3217 or contributors be liable for any direct, indirect, incidental, special,
3218 exemplary, or consequential damages (including, but not limited to,
3219 procurement of substitute goods or services; loss of use, data, or
3220 profits; or business interruption) however caused and on any theory of
3221 liability, whether in contract, strict liability, or tort (including
3222 negligence or otherwise) arising in any way out of the use of this
3223 software, even if advised of the possibility of such damage.
3224
3225 */
3226 ?>
3227