PluginProbe ʕ •ᴥ•ʔ
Jetpack – WP Security, Backup, Speed, & Growth / 13.9.2
Jetpack – WP Security, Backup, Speed, & Growth v13.9.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 2 years ago gfm.php 2 years ago
extra.php
3213 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 ### Parser Implementation ###
1593
1594 function __construct() {
1595 #
1596 # Constructor function. Initialize the parser object.
1597 #
1598 # Add extra escapable characters before parent constructor
1599 # initialize the table.
1600 $this->escape_chars .= ':|';
1601
1602 # Insert extra document, block, and span transformations.
1603 # Parent constructor will do the sorting.
1604 $this->document_gamut += array(
1605 "doFencedCodeBlocks" => 5,
1606 "stripFootnotes" => 15,
1607 "stripAbbreviations" => 25,
1608 "appendFootnotes" => 50,
1609 );
1610 $this->block_gamut += array(
1611 "doFencedCodeBlocks" => 5,
1612 "doTables" => 15,
1613 "doDefLists" => 45,
1614 );
1615 $this->span_gamut += array(
1616 "doFootnotes" => 5,
1617 "doAbbreviations" => 70,
1618 );
1619
1620 parent::__construct();
1621 }
1622
1623
1624 # Extra variables used during extra transformations.
1625 public $footnotes = array();
1626 public $footnotes_ordered = array();
1627 public $footnotes_ref_count = array();
1628 public $footnotes_numbers = array();
1629 public $abbr_desciptions = array();
1630 public $abbr_word_re = '';
1631
1632 # Give the current footnote number.
1633 public $footnote_counter = 1;
1634
1635
1636 function setup() {
1637 #
1638 # Setting up Extra-specific variables.
1639 #
1640 parent::setup();
1641
1642 $this->footnotes = array();
1643 $this->footnotes_ordered = array();
1644 $this->footnotes_ref_count = array();
1645 $this->footnotes_numbers = array();
1646 $this->abbr_desciptions = array();
1647 $this->abbr_word_re = '';
1648 $this->footnote_counter = 1;
1649
1650 foreach ($this->predef_abbr as $abbr_word => $abbr_desc) {
1651 if ($this->abbr_word_re)
1652 $this->abbr_word_re .= '|';
1653 $this->abbr_word_re .= preg_quote($abbr_word);
1654 $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
1655 }
1656 }
1657
1658 function teardown() {
1659 #
1660 # Clearing Extra-specific variables.
1661 #
1662 $this->footnotes = array();
1663 $this->footnotes_ordered = array();
1664 $this->footnotes_ref_count = array();
1665 $this->footnotes_numbers = array();
1666 $this->abbr_desciptions = array();
1667 $this->abbr_word_re = '';
1668
1669 parent::teardown();
1670 }
1671
1672
1673 ### Extra Attribute Parser ###
1674
1675 # Expression to use to catch attributes (includes the braces)
1676 public $id_class_attr_catch_re = '\{((?:[ ]*[#.][-_:a-zA-Z0-9]+){1,})[ ]*\}';
1677 # Expression to use when parsing in a context when no capture is desired
1678 public $id_class_attr_nocatch_re = '\{(?:[ ]*[#.][-_:a-zA-Z0-9]+){1,}[ ]*\}';
1679
1680 function doExtraAttributes($tag_name, $attr) {
1681 #
1682 # Parse attributes caught by the $this->id_class_attr_catch_re expression
1683 # and return the HTML-formatted list of attributes.
1684 #
1685 # Currently supported attributes are .class and #id.
1686 #
1687 if (empty($attr)) return "";
1688
1689 # Split on components
1690 preg_match_all('/[#.][-_:a-zA-Z0-9]+/', $attr, $matches);
1691 $elements = $matches[0];
1692
1693 # handle classes and ids (only first id taken into account)
1694 $classes = array();
1695 $id = false;
1696 foreach ($elements as $element) {
1697 if ($element[0] == '.') {
1698 $classes[] = substr($element, 1);
1699 } else if ($element[0] == '#') {
1700 if ($id === false) $id = substr($element, 1);
1701 }
1702 }
1703
1704 # compose attributes as string
1705 $attr_str = "";
1706 if (!empty($id)) {
1707 $attr_str .= ' id="'.$id.'"';
1708 }
1709 if (!empty($classes)) {
1710 $attr_str .= ' class="'.implode(" ", $classes).'"';
1711 }
1712 return $attr_str;
1713 }
1714
1715
1716 function stripLinkDefinitions($text) {
1717 #
1718 # Strips link definitions from text, stores the URLs and titles in
1719 # hash references.
1720 #
1721 $less_than_tab = $this->tab_width - 1;
1722
1723 # Link defs are in the form: ^[id]: url "optional title"
1724 $text = preg_replace_callback('{
1725 ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1
1726 [ ]*
1727 \n? # maybe *one* newline
1728 [ ]*
1729 (?:
1730 <(.+?)> # url = $2
1731 |
1732 (\S+?) # url = $3
1733 )
1734 [ ]*
1735 \n? # maybe one newline
1736 [ ]*
1737 (?:
1738 (?<=\s) # lookbehind for whitespace
1739 ["(]
1740 (.*?) # title = $4
1741 [")]
1742 [ ]*
1743 )? # title is optional
1744 (?:[ ]* '.$this->id_class_attr_catch_re.' )? # $5 = extra id & class attr
1745 (?:\n+|\Z)
1746 }xm',
1747 array(&$this, '_stripLinkDefinitions_callback'),
1748 $text);
1749 return $text;
1750 }
1751 function _stripLinkDefinitions_callback($matches) {
1752 $link_id = strtolower($matches[1]);
1753 $url = $matches[2] == '' ? $matches[3] : $matches[2];
1754 $this->urls[$link_id] = $url;
1755 $this->titles[$link_id] =& $matches[4];
1756 $this->ref_attr[$link_id] = $this->doExtraAttributes("", $dummy =& $matches[5]);
1757 return ''; # String that will replace the block
1758 }
1759
1760
1761 ### HTML Block Parser ###
1762
1763 # Tags that are always treated as block tags:
1764 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';
1765
1766 # Tags treated as block tags only if the opening tag is alone on its line:
1767 public $context_block_tags_re = 'script|noscript|ins|del|iframe|object|source|track|param|math|svg|canvas|audio|video';
1768
1769 # Tags where markdown="1" default to span mode:
1770 public $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address';
1771
1772 # Tags which must not have their contents modified, no matter where
1773 # they appear:
1774 public $clean_tags_re = 'script|math|svg';
1775
1776 # Tags that do not need to be closed.
1777 public $auto_close_tags_re = 'hr|img|param|source|track';
1778
1779
1780 function hashHTMLBlocks($text) {
1781 #
1782 # Hashify HTML Blocks and "clean tags".
1783 #
1784 # We only want to do this for block-level HTML tags, such as headers,
1785 # lists, and tables. That's because we still want to wrap <p>s around
1786 # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
1787 # phrase emphasis, and spans. The list of tags we're looking for is
1788 # hard-coded.
1789 #
1790 # This works by calling _HashHTMLBlocks_InMarkdown, which then calls
1791 # _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1"
1792 # attribute is found within a tag, _HashHTMLBlocks_InHTML calls back
1793 # _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag.
1794 # These two functions are calling each other. It's recursive!
1795 #
1796 if ($this->no_markup) return $text;
1797
1798 #
1799 # Call the HTML-in-Markdown hasher.
1800 #
1801 list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text);
1802
1803 return $text;
1804 }
1805 function _hashHTMLBlocks_inMarkdown($text, $indent = 0,
1806 $enclosing_tag_re = '', $span = false)
1807 {
1808 #
1809 # Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags.
1810 #
1811 # * $indent is the number of space to be ignored when checking for code
1812 # blocks. This is important because if we don't take the indent into
1813 # account, something like this (which looks right) won't work as expected:
1814 #
1815 # <div>
1816 # <div markdown="1">
1817 # Hello World. <-- Is this a Markdown code block or text?
1818 # </div> <-- Is this a Markdown code block or a real tag?
1819 # <div>
1820 #
1821 # If you don't like this, just don't indent the tag on which
1822 # you apply the markdown="1" attribute.
1823 #
1824 # * If $enclosing_tag_re is not empty, stops at the first unmatched closing
1825 # tag with that name. Nested tags supported.
1826 #
1827 # * If $span is true, text inside must treated as span. So any double
1828 # newline will be replaced by a single newline so that it does not create
1829 # paragraphs.
1830 #
1831 # Returns an array of that form: ( processed text , remaining text )
1832 #
1833 if ($text === '') return array('', '');
1834
1835 # Regex to check for the presence of newlines around a block tag.
1836 $newline_before_re = '/(?:^\n?|\n\n)*$/';
1837 $newline_after_re =
1838 '{
1839 ^ # Start of text following the tag.
1840 (?>[ ]*<!--.*?-->)? # Optional comment.
1841 [ ]*\n # Must be followed by newline.
1842 }xs';
1843
1844 # Regex to match any tag.
1845 $block_tag_re =
1846 '{
1847 ( # $2: Capture whole tag.
1848 </? # Any opening or closing tag.
1849 (?> # Tag name.
1850 '.$this->block_tags_re.' |
1851 '.$this->context_block_tags_re.' |
1852 '.$this->clean_tags_re.' |
1853 (?!\s)'.$enclosing_tag_re.'
1854 )
1855 (?:
1856 (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
1857 (?>
1858 ".*?" | # Double quotes (can contain `>`)
1859 \'.*?\' | # Single quotes (can contain `>`)
1860 .+? # Anything but quotes and `>`.
1861 )*?
1862 )?
1863 > # End of tag.
1864 |
1865 <!-- .*? --> # HTML Comment
1866 |
1867 <\?.*?\?> | <%.*?%> # Processing instruction
1868 |
1869 <!\[CDATA\[.*?\]\]> # CData Block
1870 '. ( !$span ? ' # If not in span.
1871 |
1872 # Indented code block
1873 (?: ^[ ]*\n | ^ | \n[ ]*\n )
1874 [ ]{'.($indent+4).'}[^\n]* \n
1875 (?>
1876 (?: [ ]{'.($indent+4).'}[^\n]* | [ ]* ) \n
1877 )*
1878 |
1879 # Fenced code block marker
1880 (?<= ^ | \n )
1881 [ ]{0,'.($indent+3).'}(?:~{3,}|`{3,})
1882 [ ]*
1883 (?:
1884 \.?[-_:a-zA-Z0-9]+ # standalone class name
1885 |
1886 '.$this->id_class_attr_nocatch_re.' # extra attributes
1887 )?
1888 [ ]*
1889 (?= \n )
1890 ' : '' ). ' # End (if not is span).
1891 |
1892 # Code span marker
1893 # Note, this regex needs to go after backtick fenced
1894 # code blocks but it should also be kept outside of the
1895 # "if not in span" condition adding backticks to the parser
1896 `+
1897 )
1898 }xs';
1899
1900
1901 $depth = 0; # Current depth inside the tag tree.
1902 $parsed = ""; # Parsed text that will be returned.
1903
1904 #
1905 # Loop through every tag until we find the closing tag of the parent
1906 # or loop until reaching the end of text if no parent tag specified.
1907 #
1908 do {
1909 #
1910 # Split the text using the first $tag_match pattern found.
1911 # Text before pattern will be first in the array, text after
1912 # pattern will be at the end, and between will be any catches made
1913 # by the pattern.
1914 #
1915 $parts = preg_split($block_tag_re, $text, 2,
1916 PREG_SPLIT_DELIM_CAPTURE);
1917
1918 # If in Markdown span mode, add a empty-string span-level hash
1919 # after each newline to prevent triggering any block element.
1920 if ($span) {
1921 $void = $this->hashPart("", ':');
1922 $newline = "$void\n";
1923 $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void;
1924 }
1925
1926 $parsed .= $parts[0]; # Text before current tag.
1927
1928 # If end of $text has been reached. Stop loop.
1929 if (count($parts) < 3) {
1930 $text = "";
1931 break;
1932 }
1933
1934 $tag = $parts[1]; # Tag to handle.
1935 $text = $parts[2]; # Remaining text after current tag.
1936 $tag_re = preg_quote($tag); # For use in a regular expression.
1937
1938 #
1939 # Check for: Fenced code block marker.
1940 # Note: need to recheck the whole tag to disambiguate backtick
1941 # fences from code spans
1942 #
1943 if (preg_match('{^\n?([ ]{0,'.($indent+3).'})(~{3,}|`{3,})[ ]*(?:\.?[-_:a-zA-Z0-9]+|'.$this->id_class_attr_nocatch_re.')?[ ]*\n?$}', $tag, $capture)) {
1944 # Fenced code block marker: find matching end marker.
1945 $fence_indent = strlen($capture[1]); # use captured indent in re
1946 $fence_re = $capture[2]; # use captured fence in re
1947 if (preg_match('{^(?>.*\n)*?[ ]{'.($fence_indent).'}'.$fence_re.'[ ]*(?:\n|$)}', $text,
1948 $matches))
1949 {
1950 # End marker found: pass text unchanged until marker.
1951 $parsed .= $tag . $matches[0];
1952 $text = substr($text, strlen($matches[0]));
1953 }
1954 else {
1955 # No end marker: just skip it.
1956 $parsed .= $tag;
1957 }
1958 }
1959 #
1960 # Check for: Indented code block.
1961 #
1962 else if ($tag[0] == "\n" || $tag[0] == " ") {
1963 # Indented code block: pass it unchanged, will be handled
1964 # later.
1965 $parsed .= $tag;
1966 }
1967 #
1968 # Check for: Code span marker
1969 # Note: need to check this after backtick fenced code blocks
1970 #
1971 else if ($tag[0] == "`") {
1972 # Find corresponding end marker.
1973 $tag_re = preg_quote($tag);
1974 if (preg_match('{^(?>.+?|\n(?!\n))*?(?<!`)'.$tag_re.'(?!`)}',
1975 $text, $matches))
1976 {
1977 # End marker found: pass text unchanged until marker.
1978 $parsed .= $tag . $matches[0];
1979 $text = substr($text, strlen($matches[0]));
1980 }
1981 else {
1982 # Unmatched marker: just skip it.
1983 $parsed .= $tag;
1984 }
1985 }
1986 #
1987 # Check for: Opening Block level tag or
1988 # Opening Context Block tag (like ins and del)
1989 # used as a block tag (tag is alone on it's line).
1990 #
1991 else if (preg_match('{^<(?:'.$this->block_tags_re.')\b}', $tag) ||
1992 ( preg_match('{^<(?:'.$this->context_block_tags_re.')\b}', $tag) &&
1993 preg_match($newline_before_re, $parsed) &&
1994 preg_match($newline_after_re, $text) )
1995 )
1996 {
1997 # Need to parse tag and following text using the HTML parser.
1998 list($block_text, $text) =
1999 $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true);
2000
2001 # Make sure it stays outside of any paragraph by adding newlines.
2002 $parsed .= "\n\n$block_text\n\n";
2003 }
2004 #
2005 # Check for: Clean tag (like script, math)
2006 # HTML Comments, processing instructions.
2007 #
2008 else if (preg_match('{^<(?:'.$this->clean_tags_re.')\b}', $tag) ||
2009 $tag[1] == '!' || $tag[1] == '?')
2010 {
2011 # Need to parse tag and following text using the HTML parser.
2012 # (don't check for markdown attribute)
2013 list($block_text, $text) =
2014 $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false);
2015
2016 $parsed .= $block_text;
2017 }
2018 #
2019 # Check for: Tag with same name as enclosing tag.
2020 #
2021 else if ($enclosing_tag_re !== '' &&
2022 # Same name as enclosing tag.
2023 preg_match('{^</?(?:'.$enclosing_tag_re.')\b}', $tag))
2024 {
2025 #
2026 # Increase/decrease nested tag count.
2027 #
2028 if ($tag[1] == '/') $depth--;
2029 else if ($tag[strlen($tag)-2] != '/') $depth++;
2030
2031 if ($depth < 0) {
2032 #
2033 # Going out of parent element. Clean up and break so we
2034 # return to the calling function.
2035 #
2036 $text = $tag . $text;
2037 break;
2038 }
2039
2040 $parsed .= $tag;
2041 }
2042 else {
2043 $parsed .= $tag;
2044 }
2045 } while ($depth >= 0);
2046
2047 return array($parsed, $text);
2048 }
2049 function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) {
2050 #
2051 # Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags.
2052 #
2053 # * Calls $hash_method to convert any blocks.
2054 # * Stops when the first opening tag closes.
2055 # * $md_attr indicate if the use of the `markdown="1"` attribute is allowed.
2056 # (it is not inside clean tags)
2057 #
2058 # Returns an array of that form: ( processed text , remaining text )
2059 #
2060 if ($text === '') return array('', '');
2061
2062 # Regex to match `markdown` attribute inside of a tag.
2063 $markdown_attr_re = '
2064 {
2065 \s* # Eat whitespace before the `markdown` attribute
2066 markdown
2067 \s*=\s*
2068 (?>
2069 (["\']) # $1: quote delimiter
2070 (.*?) # $2: attribute value
2071 \1 # matching delimiter
2072 |
2073 ([^\s>]*) # $3: unquoted attribute value
2074 )
2075 () # $4: make $3 always defined (avoid warnings)
2076 }xs';
2077
2078 # Regex to match any tag.
2079 $tag_re = '{
2080 ( # $2: Capture whole tag.
2081 </? # Any opening or closing tag.
2082 [\w:$]+ # Tag name.
2083 (?:
2084 (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
2085 (?>
2086 ".*?" | # Double quotes (can contain `>`)
2087 \'.*?\' | # Single quotes (can contain `>`)
2088 .+? # Anything but quotes and `>`.
2089 )*?
2090 )?
2091 > # End of tag.
2092 |
2093 <!-- .*? --> # HTML Comment
2094 |
2095 <\?.*?\?> | <%.*?%> # Processing instruction
2096 |
2097 <!\[CDATA\[.*?\]\]> # CData Block
2098 )
2099 }xs';
2100
2101 $original_text = $text; # Save original text in case of faliure.
2102
2103 $depth = 0; # Current depth inside the tag tree.
2104 $block_text = ""; # Temporary text holder for current text.
2105 $parsed = ""; # Parsed text that will be returned.
2106
2107 #
2108 # Get the name of the starting tag.
2109 # (This pattern makes $base_tag_name_re safe without quoting.)
2110 #
2111 if (preg_match('/^<([\w:$]*)\b/', $text, $matches))
2112 $base_tag_name_re = $matches[1];
2113
2114 #
2115 # Loop through every tag until we find the corresponding closing tag.
2116 #
2117 do {
2118 #
2119 # Split the text using the first $tag_match pattern found.
2120 # Text before pattern will be first in the array, text after
2121 # pattern will be at the end, and between will be any catches made
2122 # by the pattern.
2123 #
2124 $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
2125
2126 if (count($parts) < 3) {
2127 #
2128 # End of $text reached with unbalenced tag(s).
2129 # In that case, we return original text unchanged and pass the
2130 # first character as filtered to prevent an infinite loop in the
2131 # parent function.
2132 #
2133 return array($original_text[0], substr($original_text, 1));
2134 }
2135
2136 $block_text .= $parts[0]; # Text before current tag.
2137 $tag = $parts[1]; # Tag to handle.
2138 $text = $parts[2]; # Remaining text after current tag.
2139
2140 #
2141 # Check for: Auto-close tag (like <hr/>)
2142 # Comments and Processing Instructions.
2143 #
2144 if (preg_match('{^</?(?:'.$this->auto_close_tags_re.')\b}', $tag) ||
2145 $tag[1] == '!' || $tag[1] == '?')
2146 {
2147 # Just add the tag to the block as if it was text.
2148 $block_text .= $tag;
2149 }
2150 else {
2151 #
2152 # Increase/decrease nested tag count. Only do so if
2153 # the tag's name match base tag's.
2154 #
2155 if (preg_match('{^</?'.$base_tag_name_re.'\b}', $tag)) {
2156 if ($tag[1] == '/') $depth--;
2157 else if ($tag[strlen($tag)-2] != '/') $depth++;
2158 }
2159
2160 #
2161 # Check for `markdown="1"` attribute and handle it.
2162 #
2163 if ($md_attr &&
2164 preg_match($markdown_attr_re, $tag, $attr_m) &&
2165 preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3]))
2166 {
2167 # Remove `markdown` attribute from opening tag.
2168 $tag = preg_replace($markdown_attr_re, '', $tag);
2169
2170 # Check if text inside this tag must be parsed in span mode.
2171 $this->mode = $attr_m[2] . $attr_m[3];
2172 $span_mode = $this->mode == 'span' || $this->mode != 'block' &&
2173 preg_match('{^<(?:'.$this->contain_span_tags_re.')\b}', $tag);
2174
2175 # Calculate indent before tag.
2176 if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) {
2177 $strlen = $this->utf8_strlen;
2178 $indent = $strlen($matches[1], 'UTF-8');
2179 } else {
2180 $indent = 0;
2181 }
2182
2183 # End preceding block with this tag.
2184 $block_text .= $tag;
2185 $parsed .= $this->$hash_method($block_text);
2186
2187 # Get enclosing tag name for the ParseMarkdown function.
2188 # (This pattern makes $tag_name_re safe without quoting.)
2189 preg_match('/^<([\w:$]*)\b/', $tag, $matches);
2190 $tag_name_re = $matches[1];
2191
2192 # Parse the content using the HTML-in-Markdown parser.
2193 list ($block_text, $text)
2194 = $this->_hashHTMLBlocks_inMarkdown($text, $indent,
2195 $tag_name_re, $span_mode);
2196
2197 # Outdent markdown text.
2198 if ($indent > 0) {
2199 $block_text = preg_replace("/^[ ]{1,$indent}/m", "",
2200 $block_text);
2201 }
2202
2203 # Append tag content to parsed text.
2204 if (!$span_mode) $parsed .= "\n\n$block_text\n\n";
2205 else $parsed .= "$block_text";
2206
2207 # Start over with a new block.
2208 $block_text = "";
2209 }
2210 else $block_text .= $tag;
2211 }
2212
2213 } while ($depth > 0);
2214
2215 #
2216 # Hash last block text that wasn't processed inside the loop.
2217 #
2218 $parsed .= $this->$hash_method($block_text);
2219
2220 return array($parsed, $text);
2221 }
2222
2223
2224 function hashClean($text) {
2225 #
2226 # Called whenever a tag must be hashed when a function inserts a "clean" tag
2227 # in $text, it passes through this function and is automaticaly escaped,
2228 # blocking invalid nested overlap.
2229 #
2230 return $this->hashPart($text, 'C');
2231 }
2232
2233
2234 function doAnchors($text) {
2235 #
2236 # Turn Markdown link shortcuts into XHTML <a> tags.
2237 #
2238 if ($this->in_anchor) return $text;
2239 $this->in_anchor = true;
2240
2241 #
2242 # First, handle reference-style links: [link text] [id]
2243 #
2244 $text = preg_replace_callback('{
2245 ( # wrap whole match in $1
2246 \[
2247 ('.$this->nested_brackets_re.') # link text = $2
2248 \]
2249
2250 [ ]? # one optional space
2251 (?:\n[ ]*)? # one optional newline followed by spaces
2252
2253 \[
2254 (.*?) # id = $3
2255 \]
2256 )
2257 }xs',
2258 array(&$this, '_doAnchors_reference_callback'), $text);
2259
2260 #
2261 # Next, inline-style links: [link text](url "optional title")
2262 #
2263 $text = preg_replace_callback('{
2264 ( # wrap whole match in $1
2265 \[
2266 ('.$this->nested_brackets_re.') # link text = $2
2267 \]
2268 \( # literal paren
2269 [ \n]*
2270 (?:
2271 <(.+?)> # href = $3
2272 |
2273 ('.$this->nested_url_parenthesis_re.') # href = $4
2274 )
2275 [ \n]*
2276 ( # $5
2277 ([\'"]) # quote char = $6
2278 (.*?) # Title = $7
2279 \6 # matching quote
2280 [ \n]* # ignore any spaces/tabs between closing quote and )
2281 )? # title is optional
2282 \)
2283 (?:[ ]? '.$this->id_class_attr_catch_re.' )? # $8 = id/class attributes
2284 )
2285 }xs',
2286 array(&$this, '_doAnchors_inline_callback'), $text);
2287
2288 #
2289 # Last, handle reference-style shortcuts: [link text]
2290 # These must come last in case you've also got [link text][1]
2291 # or [link text](/foo)
2292 #
2293 $text = preg_replace_callback('{
2294 ( # wrap whole match in $1
2295 \[
2296 ([^\[\]]+) # link text = $2; can\'t contain [ or ]
2297 \]
2298 )
2299 }xs',
2300 array(&$this, '_doAnchors_reference_callback'), $text);
2301
2302 $this->in_anchor = false;
2303 return $text;
2304 }
2305 function _doAnchors_reference_callback($matches) {
2306 $whole_match = $matches[1];
2307 $link_text = $matches[2];
2308 $link_id =& $matches[3];
2309
2310 if ($link_id == "") {
2311 # for shortcut links like [this][] or [this].
2312 $link_id = $link_text;
2313 }
2314
2315 # lower-case and turn embedded newlines into spaces
2316 $link_id = strtolower($link_id);
2317 $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
2318
2319 if (isset($this->urls[$link_id])) {
2320 $url = $this->urls[$link_id];
2321 $url = $this->encodeAttribute($url);
2322
2323 $result = "<a href=\"$url\"";
2324 if ( isset( $this->titles[$link_id] ) ) {
2325 $title = $this->titles[$link_id];
2326 $title = $this->encodeAttribute($title);
2327 $result .= " title=\"$title\"";
2328 }
2329 if (isset($this->ref_attr[$link_id]))
2330 $result .= $this->ref_attr[$link_id];
2331
2332 $link_text = $this->runSpanGamut($link_text);
2333 $result .= ">$link_text</a>";
2334 $result = $this->hashPart($result);
2335 }
2336 else {
2337 $result = $whole_match;
2338 }
2339 return $result;
2340 }
2341 function _doAnchors_inline_callback($matches) {
2342 $whole_match = $matches[1];
2343 $link_text = $this->runSpanGamut($matches[2]);
2344 $url = $matches[3] == '' ? $matches[4] : $matches[3];
2345 $title =& $matches[7];
2346 $attr = $this->doExtraAttributes("a", $dummy =& $matches[8]);
2347
2348
2349 $url = $this->encodeAttribute($url);
2350
2351 $result = "<a href=\"$url\"";
2352 if (isset($title)) {
2353 $title = $this->encodeAttribute($title);
2354 $result .= " title=\"$title\"";
2355 }
2356 $result .= $attr;
2357
2358 $link_text = $this->runSpanGamut($link_text);
2359 $result .= ">$link_text</a>";
2360
2361 return $this->hashPart($result);
2362 }
2363
2364
2365 function doImages($text) {
2366 #
2367 # Turn Markdown image shortcuts into <img> tags.
2368 #
2369 #
2370 # First, handle reference-style labeled images: ![alt text][id]
2371 #
2372 $text = preg_replace_callback('{
2373 ( # wrap whole match in $1
2374 !\[
2375 ('.$this->nested_brackets_re.') # alt text = $2
2376 \]
2377
2378 [ ]? # one optional space
2379 (?:\n[ ]*)? # one optional newline followed by spaces
2380
2381 \[
2382 (.*?) # id = $3
2383 \]
2384
2385 )
2386 }xs',
2387 array(&$this, '_doImages_reference_callback'), $text);
2388
2389 #
2390 # Next, handle inline images: ![alt text](url "optional title")
2391 # Don't forget: encode * and _
2392 #
2393 $text = preg_replace_callback('{
2394 ( # wrap whole match in $1
2395 !\[
2396 ('.$this->nested_brackets_re.') # alt text = $2
2397 \]
2398 \s? # One optional whitespace character
2399 \( # literal paren
2400 [ \n]*
2401 (?:
2402 <(\S*)> # src url = $3
2403 |
2404 ('.$this->nested_url_parenthesis_re.') # src url = $4
2405 )
2406 [ \n]*
2407 ( # $5
2408 ([\'"]) # quote char = $6
2409 (.*?) # title = $7
2410 \6 # matching quote
2411 [ \n]*
2412 )? # title is optional
2413 \)
2414 (?:[ ]? '.$this->id_class_attr_catch_re.' )? # $8 = id/class attributes
2415 )
2416 }xs',
2417 array(&$this, '_doImages_inline_callback'), $text);
2418
2419 return $text;
2420 }
2421 function _doImages_reference_callback($matches) {
2422 $whole_match = $matches[1];
2423 $alt_text = $matches[2];
2424 $link_id = strtolower($matches[3]);
2425
2426 if ($link_id == "") {
2427 $link_id = strtolower($alt_text); # for shortcut links like ![this][].
2428 }
2429
2430 $alt_text = $this->encodeAttribute($alt_text);
2431 if (isset($this->urls[$link_id])) {
2432 $url = $this->encodeAttribute($this->urls[$link_id]);
2433 $result = "<img src=\"$url\" alt=\"$alt_text\"";
2434 if (isset($this->titles[$link_id])) {
2435 $title = $this->titles[$link_id];
2436 $title = $this->encodeAttribute($title);
2437 $result .= " title=\"$title\"";
2438 }
2439 if (isset($this->ref_attr[$link_id]))
2440 $result .= $this->ref_attr[$link_id];
2441 $result .= $this->empty_element_suffix;
2442 $result = $this->hashPart($result);
2443 }
2444 else {
2445 # If there's no such link ID, leave intact:
2446 $result = $whole_match;
2447 }
2448
2449 return $result;
2450 }
2451 function _doImages_inline_callback($matches) {
2452 $whole_match = $matches[1];
2453 $alt_text = $matches[2];
2454 $url = $matches[3] == '' ? $matches[4] : $matches[3];
2455 $title =& $matches[7];
2456 $attr = $this->doExtraAttributes("img", $dummy =& $matches[8]);
2457
2458 $alt_text = $this->encodeAttribute($alt_text);
2459 $url = $this->encodeAttribute($url);
2460 $result = "<img src=\"$url\" alt=\"$alt_text\"";
2461 if (isset($title)) {
2462 $title = $this->encodeAttribute($title);
2463 $result .= " title=\"$title\""; # $title already quoted
2464 }
2465 $result .= $attr;
2466 $result .= $this->empty_element_suffix;
2467
2468 return $this->hashPart($result);
2469 }
2470
2471
2472 function doHeaders($text) {
2473 #
2474 # Redefined to add id and class attribute support.
2475 #
2476 # Setext-style headers:
2477 # Header 1 {#header1}
2478 # ========
2479 #
2480 # Header 2 {#header2 .class1 .class2}
2481 # --------
2482 #
2483 $text = preg_replace_callback(
2484 '{
2485 (^.+?) # $1: Header text
2486 (?:[ ]+ '.$this->id_class_attr_catch_re.' )? # $3 = id/class attributes
2487 [ ]*\n(=+|-+)[ ]*\n+ # $3: Header footer
2488 }mx',
2489 array(&$this, '_doHeaders_callback_setext'), $text);
2490
2491 # atx-style headers:
2492 # # Header 1 {#header1}
2493 # ## Header 2 {#header2}
2494 # ## Header 2 with closing hashes ## {#header3.class1.class2}
2495 # ...
2496 # ###### Header 6 {.class2}
2497 #
2498 $text = preg_replace_callback('{
2499 ^(\#{1,6}) # $1 = string of #\'s
2500 [ ]*
2501 (.+?) # $2 = Header text
2502 [ ]*
2503 \#* # optional closing #\'s (not counted)
2504 (?:[ ]+ '.$this->id_class_attr_catch_re.' )? # $3 = id/class attributes
2505 [ ]*
2506 \n+
2507 }xm',
2508 array(&$this, '_doHeaders_callback_atx'), $text);
2509
2510 return $text;
2511 }
2512 function _doHeaders_callback_setext($matches) {
2513 if ($matches[3] == '-' && preg_match('{^- }', $matches[1]))
2514 return $matches[0];
2515 $level = $matches[3][0] == '=' ? 1 : 2;
2516 $attr = $this->doExtraAttributes("h$level", $dummy =& $matches[2]);
2517 $block = "<h$level$attr>".$this->runSpanGamut($matches[1])."</h$level>";
2518 return "\n" . $this->hashBlock($block) . "\n\n";
2519 }
2520 function _doHeaders_callback_atx($matches) {
2521 $level = strlen($matches[1]);
2522 $attr = $this->doExtraAttributes("h$level", $dummy =& $matches[3]);
2523 $block = "<h$level$attr>".$this->runSpanGamut($matches[2])."</h$level>";
2524 return "\n" . $this->hashBlock($block) . "\n\n";
2525 }
2526
2527
2528 function doTables($text) {
2529 #
2530 # Form HTML tables.
2531 #
2532 $less_than_tab = $this->tab_width - 1;
2533 #
2534 # Find tables with leading pipe.
2535 #
2536 # | Header 1 | Header 2
2537 # | -------- | --------
2538 # | Cell 1 | Cell 2
2539 # | Cell 3 | Cell 4
2540 #
2541 $text = preg_replace_callback('
2542 {
2543 ^ # Start of a line
2544 [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
2545 [|] # Optional leading pipe (present)
2546 (.+) \n # $1: Header row (at least one pipe)
2547
2548 [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
2549 [|] ([ ]*[-:]+[-| :]*) \n # $2: Header underline
2550
2551 ( # $3: Cells
2552 (?>
2553 [ ]* # Allowed whitespace.
2554 [|] .* \n # Row content.
2555 )*
2556 )
2557 (?=\n|\Z) # Stop at final double newline.
2558 }xm',
2559 array(&$this, '_doTable_leadingPipe_callback'), $text);
2560
2561 #
2562 # Find tables without leading pipe.
2563 #
2564 # Header 1 | Header 2
2565 # -------- | --------
2566 # Cell 1 | Cell 2
2567 # Cell 3 | Cell 4
2568 #
2569 $text = preg_replace_callback('
2570 {
2571 ^ # Start of a line
2572 [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
2573 (\S.*[|].*) \n # $1: Header row (at least one pipe)
2574
2575 [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
2576 ([-:]+[ ]*[|][-| :]*) \n # $2: Header underline
2577
2578 ( # $3: Cells
2579 (?>
2580 .* [|] .* \n # Row content
2581 )*
2582 )
2583 (?=\n|\Z) # Stop at final double newline.
2584 }xm',
2585 array(&$this, '_DoTable_callback'), $text);
2586
2587 return $text;
2588 }
2589 function _doTable_leadingPipe_callback($matches) {
2590 $head = $matches[1];
2591 $underline = $matches[2];
2592 $content = $matches[3];
2593
2594 # Remove leading pipe for each row.
2595 $content = preg_replace('/^ *[|]/m', '', $content);
2596
2597 return $this->_doTable_callback(array($matches[0], $head, $underline, $content));
2598 }
2599 function _doTable_callback($matches) {
2600 $head = $matches[1];
2601 $underline = $matches[2];
2602 $content = $matches[3];
2603
2604 # Remove any tailing pipes for each line.
2605 $head = preg_replace('/[|] *$/m', '', $head);
2606 $underline = preg_replace('/[|] *$/m', '', $underline);
2607 $content = preg_replace('/[|] *$/m', '', $content);
2608
2609 # Reading alignement from header underline.
2610 $separators = preg_split('/ *[|] */', $underline);
2611 $attr = array();
2612 foreach ($separators as $n => $s) {
2613 if (preg_match('/^ *-+: *$/', $s)) $attr[$n] = ' align="right"';
2614 else if (preg_match('/^ *:-+: *$/', $s))$attr[$n] = ' align="center"';
2615 else if (preg_match('/^ *:-+ *$/', $s)) $attr[$n] = ' align="left"';
2616 else $attr[$n] = '';
2617 }
2618
2619 # Parsing span elements, including code spans, character escapes,
2620 # and inline HTML tags, so that pipes inside those gets ignored.
2621 $head = $this->parseSpan($head);
2622 $headers = preg_split('/ *[|] */', $head);
2623 $col_count = count($headers);
2624 $attr = array_pad($attr, $col_count, '');
2625
2626 # Write column headers.
2627 $text = "<table>\n";
2628 $text .= "<thead>\n";
2629 $text .= "<tr>\n";
2630 foreach ($headers as $n => $header)
2631 $text .= " <th$attr[$n]>".$this->runSpanGamut(trim($header))."</th>\n";
2632 $text .= "</tr>\n";
2633 $text .= "</thead>\n";
2634
2635 # Split content by row.
2636 $rows = explode("\n", trim($content, "\n"));
2637
2638 $text .= "<tbody>\n";
2639 foreach ($rows as $row) {
2640 # Parsing span elements, including code spans, character escapes,
2641 # and inline HTML tags, so that pipes inside those gets ignored.
2642 $row = $this->parseSpan($row);
2643
2644 # Split row by cell.
2645 $row_cells = preg_split('/ *[|] */', $row, $col_count);
2646 $row_cells = array_pad($row_cells, $col_count, '');
2647
2648 $text .= "<tr>\n";
2649 foreach ($row_cells as $n => $cell)
2650 $text .= " <td$attr[$n]>".$this->runSpanGamut(trim($cell))."</td>\n";
2651 $text .= "</tr>\n";
2652 }
2653 $text .= "</tbody>\n";
2654 $text .= "</table>";
2655
2656 return $this->hashBlock($text) . "\n";
2657 }
2658
2659
2660 function doDefLists($text) {
2661 #
2662 # Form HTML definition lists.
2663 #
2664 $less_than_tab = $this->tab_width - 1;
2665
2666 # Re-usable pattern to match any entire dl list:
2667 $whole_list_re = '(?>
2668 ( # $1 = whole list
2669 ( # $2
2670 [ ]{0,'.$less_than_tab.'}
2671 ((?>.*\S.*\n)+) # $3 = defined term
2672 \n?
2673 [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
2674 )
2675 (?s:.+?)
2676 ( # $4
2677 \z
2678 |
2679 \n{2,}
2680 (?=\S)
2681 (?! # Negative lookahead for another term
2682 [ ]{0,'.$less_than_tab.'}
2683 (?: \S.*\n )+? # defined term
2684 \n?
2685 [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
2686 )
2687 (?! # Negative lookahead for another definition
2688 [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
2689 )
2690 )
2691 )
2692 )'; // mx
2693
2694 $text = preg_replace_callback('{
2695 (?>\A\n?|(?<=\n\n))
2696 '.$whole_list_re.'
2697 }mx',
2698 array(&$this, '_doDefLists_callback'), $text);
2699
2700 return $text;
2701 }
2702 function _doDefLists_callback($matches) {
2703 # Re-usable patterns to match list item bullets and number markers:
2704 $list = $matches[1];
2705
2706 # Turn double returns into triple returns, so that we can make a
2707 # paragraph for the last item in a list, if necessary:
2708 $result = trim($this->processDefListItems($list));
2709 $result = "<dl>\n" . $result . "\n</dl>";
2710 return $this->hashBlock($result) . "\n\n";
2711 }
2712
2713
2714 function processDefListItems($list_str) {
2715 #
2716 # Process the contents of a single definition list, splitting it
2717 # into individual term and definition list items.
2718 #
2719 $less_than_tab = $this->tab_width - 1;
2720
2721 # trim trailing blank lines:
2722 $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
2723
2724 # Process definition terms.
2725 $list_str = preg_replace_callback('{
2726 (?>\A\n?|\n\n+) # leading line
2727 ( # definition terms = $1
2728 [ ]{0,'.$less_than_tab.'} # leading whitespace
2729 (?!\:[ ]|[ ]) # negative lookahead for a definition
2730 # mark (colon) or more whitespace.
2731 (?> \S.* \n)+? # actual term (not whitespace).
2732 )
2733 (?=\n?[ ]{0,3}:[ ]) # lookahead for following line feed
2734 # with a definition mark.
2735 }xm',
2736 array(&$this, '_processDefListItems_callback_dt'), $list_str);
2737
2738 # Process actual definitions.
2739 $list_str = preg_replace_callback('{
2740 \n(\n+)? # leading line = $1
2741 ( # marker space = $2
2742 [ ]{0,'.$less_than_tab.'} # whitespace before colon
2743 \:[ ]+ # definition mark (colon)
2744 )
2745 ((?s:.+?)) # definition text = $3
2746 (?= \n+ # stop at next definition mark,
2747 (?: # next term or end of text
2748 [ ]{0,'.$less_than_tab.'} \:[ ] |
2749 <dt> | \z
2750 )
2751 )
2752 }xm',
2753 array(&$this, '_processDefListItems_callback_dd'), $list_str);
2754
2755 return $list_str;
2756 }
2757 function _processDefListItems_callback_dt($matches) {
2758 $terms = explode("\n", trim($matches[1]));
2759 $text = '';
2760 foreach ($terms as $term) {
2761 $term = $this->runSpanGamut(trim($term));
2762 $text .= "\n<dt>" . $term . "</dt>";
2763 }
2764 return $text . "\n";
2765 }
2766 function _processDefListItems_callback_dd($matches) {
2767 $leading_line = $matches[1];
2768 $marker_space = $matches[2];
2769 $def = $matches[3];
2770
2771 if ($leading_line || preg_match('/\n{2,}/', $def)) {
2772 # Replace marker with the appropriate whitespace indentation
2773 $def = str_repeat(' ', strlen($marker_space)) . $def;
2774 $def = $this->runBlockGamut($this->outdent($def . "\n\n"));
2775 $def = "\n". $def ."\n";
2776 }
2777 else {
2778 $def = rtrim($def);
2779 $def = $this->runSpanGamut($this->outdent($def));
2780 }
2781
2782 return "\n<dd>" . $def . "</dd>\n";
2783 }
2784
2785
2786 function doFencedCodeBlocks($text) {
2787 #
2788 # Adding the fenced code block syntax to regular Markdown:
2789 #
2790 # ~~~
2791 # Code block
2792 # ~~~
2793 #
2794 $less_than_tab = $this->tab_width;
2795
2796 $text = preg_replace_callback('{
2797 (?:\n|\A)
2798 # 1: Opening marker
2799 (
2800 (?:~{3,}|`{3,}) # 3 or more tildes/backticks.
2801 )
2802 [ ]*
2803 (?:
2804 \.?([-_:a-zA-Z0-9]+) # 2: standalone class name
2805 |
2806 '.$this->id_class_attr_catch_re.' # 3: Extra attributes
2807 )?
2808 [ ]* \n # Whitespace and newline following marker.
2809
2810 # 4: Content
2811 (
2812 (?>
2813 (?!\1 [ ]* \n) # Not a closing marker.
2814 .*\n+
2815 )+
2816 )
2817
2818 # Closing marker.
2819 \1 [ ]* (?= \n )
2820 }xm',
2821 array(&$this, '_doFencedCodeBlocks_callback'), $text);
2822
2823 return $text;
2824 }
2825 function _doFencedCodeBlocks_callback($matches) {
2826 $classname =& $matches[2];
2827 $attrs =& $matches[3];
2828 $codeblock = $matches[4];
2829 $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
2830 $codeblock = preg_replace_callback('/^\n+/',
2831 array(&$this, '_doFencedCodeBlocks_newlines'), $codeblock);
2832
2833 if ($classname != "") {
2834 if ($classname[0] == '.')
2835 $classname = substr($classname, 1);
2836 $attr_str = ' class="'.$this->code_class_prefix.$classname.'"';
2837 } else {
2838 $attr_str = $this->doExtraAttributes($this->code_attr_on_pre ? "pre" : "code", $attrs);
2839 }
2840 $pre_attr_str = $this->code_attr_on_pre ? $attr_str : '';
2841 $code_attr_str = $this->code_attr_on_pre ? '' : $attr_str;
2842 $codeblock = "<pre$pre_attr_str><code$code_attr_str>$codeblock</code></pre>";
2843
2844 return "\n\n".$this->hashBlock($codeblock)."\n\n";
2845 }
2846 function _doFencedCodeBlocks_newlines($matches) {
2847 return str_repeat("<br$this->empty_element_suffix",
2848 strlen($matches[0]));
2849 }
2850
2851
2852 #
2853 # Redefining emphasis markers so that emphasis by underscore does not
2854 # work in the middle of a word.
2855 #
2856 public $em_relist = array(
2857 '' => '(?:(?<!\*)\*(?!\*)|(?<![a-zA-Z0-9_])_(?!_))(?=\S|$)(?![\.,:;]\s)',
2858 '*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
2859 '_' => '(?<=\S|^)(?<!_)_(?![a-zA-Z0-9_])',
2860 );
2861 public $strong_relist = array(
2862 '' => '(?:(?<!\*)\*\*(?!\*)|(?<![a-zA-Z0-9_])__(?!_))(?=\S|$)(?![\.,:;]\s)',
2863 '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
2864 '__' => '(?<=\S|^)(?<!_)__(?![a-zA-Z0-9_])',
2865 );
2866 public $em_strong_relist = array(
2867 '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<![a-zA-Z0-9_])___(?!_))(?=\S|$)(?![\.,:;]\s)',
2868 '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
2869 '___' => '(?<=\S|^)(?<!_)___(?![a-zA-Z0-9_])',
2870 );
2871
2872
2873 function formParagraphs($text) {
2874 #
2875 # Params:
2876 # $text - string to process with html <p> tags
2877 #
2878 # Strip leading and trailing lines:
2879 $text = preg_replace('/\A\n+|\n+\z/', '', $text);
2880
2881 $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
2882
2883 #
2884 # Wrap <p> tags and unhashify HTML blocks
2885 #
2886 foreach ($grafs as $key => $value) {
2887 $value = trim($this->runSpanGamut($value));
2888
2889 # Check if this should be enclosed in a paragraph.
2890 # Clean tag hashes & block tag hashes are left alone.
2891 $is_p = !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value);
2892
2893 if ($is_p) {
2894 $value = "<p>$value</p>";
2895 }
2896 $grafs[$key] = $value;
2897 }
2898
2899 # Join grafs in one text, then unhash HTML tags.
2900 $text = implode("\n\n", $grafs);
2901
2902 # Finish by removing any tag hashes still present in $text.
2903 $text = $this->unhash($text);
2904
2905 return $text;
2906 }
2907
2908
2909 ### Footnotes
2910
2911 function stripFootnotes($text) {
2912 #
2913 # Strips link definitions from text, stores the URLs and titles in
2914 # hash references.
2915 #
2916 $less_than_tab = $this->tab_width - 1;
2917
2918 # Link defs are in the form: [^id]: url "optional title"
2919 $text = preg_replace_callback('{
2920 ^[ ]{0,'.$less_than_tab.'}\[\^(.+?)\][ ]?: # note_id = $1
2921 [ ]*
2922 \n? # maybe *one* newline
2923 ( # text = $2 (no blank lines allowed)
2924 (?:
2925 .+ # actual text
2926 |
2927 \n # newlines but
2928 (?!\[\^.+?\]:\s)# negative lookahead for footnote marker.
2929 (?!\n+[ ]{0,3}\S)# ensure line is not blank and followed
2930 # by non-indented content
2931 )*
2932 )
2933 }xm',
2934 array(&$this, '_stripFootnotes_callback'),
2935 $text);
2936 return $text;
2937 }
2938 function _stripFootnotes_callback($matches) {
2939 $note_id = $this->fn_id_prefix . $matches[1];
2940 $this->footnotes[$note_id] = $this->outdent($matches[2]);
2941 return ''; # String that will replace the block
2942 }
2943
2944
2945 function doFootnotes($text) {
2946 #
2947 # Replace footnote references in $text [^id] with a special text-token
2948 # which will be replaced by the actual footnote marker in appendFootnotes.
2949 #
2950 if (!$this->in_anchor) {
2951 $text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text);
2952 }
2953 return $text;
2954 }
2955
2956
2957 function appendFootnotes($text) {
2958 #
2959 # Append footnote list to text.
2960 #
2961 $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
2962 array(&$this, '_appendFootnotes_callback'), $text);
2963
2964 if (!empty($this->footnotes_ordered)) {
2965 $text .= "\n\n";
2966 $text .= "<div class=\"footnotes\">\n";
2967 $text .= "<hr". $this->empty_element_suffix ."\n";
2968 $text .= "<ol>\n\n";
2969
2970 $attr = "";
2971 if ($this->fn_backlink_class != "") {
2972 $class = $this->fn_backlink_class;
2973 $class = $this->encodeAttribute($class);
2974 $attr .= " class=\"$class\"";
2975 }
2976 if ($this->fn_backlink_title != "") {
2977 $title = $this->fn_backlink_title;
2978 $title = $this->encodeAttribute($title);
2979 $attr .= " title=\"$title\"";
2980 }
2981 $num = 0;
2982
2983 while (!empty($this->footnotes_ordered)) {
2984 $footnote = reset($this->footnotes_ordered);
2985 $note_id = key($this->footnotes_ordered);
2986 unset($this->footnotes_ordered[$note_id]);
2987 $ref_count = $this->footnotes_ref_count[$note_id];
2988 unset($this->footnotes_ref_count[$note_id]);
2989 unset($this->footnotes[$note_id]);
2990
2991 $footnote .= "\n"; # Need to append newline before parsing.
2992 $footnote = $this->runBlockGamut("$footnote\n");
2993 $footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
2994 array(&$this, '_appendFootnotes_callback'), $footnote);
2995
2996 $attr = str_replace("%%", ++$num, $attr);
2997 $note_id = $this->encodeAttribute($note_id);
2998
2999 # Prepare backlink, multiple backlinks if multiple references
3000 $backlink = "<a href=\"#fnref:$note_id\"$attr>&#8617;</a>";
3001 for ($ref_num = 2; $ref_num <= $ref_count; ++$ref_num) {
3002 $backlink .= " <a href=\"#fnref$ref_num:$note_id\"$attr>&#8617;</a>";
3003 }
3004 # Add backlink to last paragraph; create new paragraph if needed.
3005 if (preg_match('{</p>$}', $footnote)) {
3006 $footnote = substr($footnote, 0, -4) . "&#160;$backlink</p>";
3007 } else {
3008 $footnote .= "\n\n<p>$backlink</p>";
3009 }
3010
3011 $text .= "<li id=\"fn:$note_id\">\n";
3012 $text .= $footnote . "\n";
3013 $text .= "</li>\n\n";
3014 }
3015
3016 $text .= "</ol>\n";
3017 $text .= "</div>";
3018 }
3019 return $text;
3020 }
3021 function _appendFootnotes_callback($matches) {
3022 $node_id = $this->fn_id_prefix . $matches[1];
3023
3024 # Create footnote marker only if it has a corresponding footnote *and*
3025 # the footnote hasn't been used by another marker.
3026 if (isset($this->footnotes[$node_id])) {
3027 $num =& $this->footnotes_numbers[$node_id];
3028 if (!isset($num)) {
3029 # Transfer footnote content to the ordered list and give it its
3030 # number
3031 $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id];
3032 $this->footnotes_ref_count[$node_id] = 1;
3033 $num = $this->footnote_counter++;
3034 $ref_count_mark = '';
3035 } else {
3036 $ref_count_mark = $this->footnotes_ref_count[$node_id] += 1;
3037 }
3038
3039 $attr = "";
3040 if ($this->fn_link_class != "") {
3041 $class = $this->fn_link_class;
3042 $class = $this->encodeAttribute($class);
3043 $attr .= " class=\"$class\"";
3044 }
3045 if ($this->fn_link_title != "") {
3046 $title = $this->fn_link_title;
3047 $title = $this->encodeAttribute($title);
3048 $attr .= " title=\"$title\"";
3049 }
3050
3051 $attr = str_replace("%%", $num, $attr);
3052 $node_id = $this->encodeAttribute($node_id);
3053
3054 return
3055 "<sup id=\"fnref$ref_count_mark:$node_id\">".
3056 "<a href=\"#fn:$node_id\"$attr>$num</a>".
3057 "</sup>";
3058 }
3059
3060 return "[^".$matches[1]."]";
3061 }
3062
3063
3064 ### Abbreviations ###
3065
3066 function stripAbbreviations($text) {
3067 #
3068 # Strips abbreviations from text, stores titles in hash references.
3069 #
3070 $less_than_tab = $this->tab_width - 1;
3071
3072 # Link defs are in the form: [id]*: url "optional title"
3073 $text = preg_replace_callback('{
3074 ^[ ]{0,'.$less_than_tab.'}\*\[(.+?)\][ ]?: # abbr_id = $1
3075 (.*) # text = $2 (no blank lines allowed)
3076 }xm',
3077 array(&$this, '_stripAbbreviations_callback'),
3078 $text);
3079 return $text;
3080 }
3081 function _stripAbbreviations_callback($matches) {
3082 $abbr_word = $matches[1];
3083 $abbr_desc = $matches[2];
3084 if ($this->abbr_word_re)
3085 $this->abbr_word_re .= '|';
3086 $this->abbr_word_re .= preg_quote($abbr_word);
3087 $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
3088 return ''; # String that will replace the block
3089 }
3090
3091
3092 function doAbbreviations($text) {
3093 #
3094 # Find defined abbreviations in text and wrap them in <abbr> elements.
3095 #
3096 if ($this->abbr_word_re) {
3097 // cannot use the /x modifier because abbr_word_re may
3098 // contain significant spaces:
3099 $text = preg_replace_callback('{'.
3100 '(?<![\w\x1A])'.
3101 '(?:'.$this->abbr_word_re.')'.
3102 '(?![\w\x1A])'.
3103 '}',
3104 array(&$this, '_doAbbreviations_callback'), $text);
3105 }
3106 return $text;
3107 }
3108 function _doAbbreviations_callback($matches) {
3109 $abbr = $matches[0];
3110 if (isset($this->abbr_desciptions[$abbr])) {
3111 $desc = $this->abbr_desciptions[$abbr];
3112 if (empty($desc)) {
3113 return $this->hashPart("<abbr>$abbr</abbr>");
3114 } else {
3115 $desc = $this->encodeAttribute($desc);
3116 return $this->hashPart("<abbr title=\"$desc\">$abbr</abbr>");
3117 }
3118 } else {
3119 return $matches[0];
3120 }
3121 }
3122
3123 }
3124
3125
3126 /*
3127
3128 PHP Markdown Extra
3129 ==================
3130
3131 Description
3132 -----------
3133
3134 This is a PHP port of the original Markdown formatter written in Perl
3135 by John Gruber. This special "Extra" version of PHP Markdown features
3136 further enhancements to the syntax for making additional constructs
3137 such as tables and definition list.
3138
3139 Markdown is a text-to-HTML filter; it translates an easy-to-read /
3140 easy-to-write structured text format into HTML. Markdown's text format
3141 is mostly similar to that of plain text email, and supports features such
3142 as headers, *emphasis*, code blocks, blockquotes, and links.
3143
3144 Markdown's syntax is designed not as a generic markup language, but
3145 specifically to serve as a front-end to (X)HTML. You can use span-level
3146 HTML tags anywhere in a Markdown document, and you can use block level
3147 HTML tags (like <div> and <table> as well).
3148
3149 For more information about Markdown's syntax, see:
3150
3151 <http://daringfireball.net/projects/markdown/>
3152
3153
3154 Bugs
3155 ----
3156
3157 To file bug reports please send email to:
3158
3159 <michel.fortin@michelf.ca>
3160
3161 Please include with your report: (1) the example input; (2) the output you
3162 expected; (3) the output Markdown actually produced.
3163
3164
3165 Version History
3166 ---------------
3167
3168 See the readme file for detailed release notes for this version.
3169
3170
3171 Copyright and License
3172 ---------------------
3173
3174 PHP Markdown & Extra
3175 Copyright (c) 2004-2013 Michel Fortin
3176 <http://michelf.ca/>
3177 All rights reserved.
3178
3179 Based on Markdown
3180 Copyright (c) 2003-2006 John Gruber
3181 <http://daringfireball.net/>
3182 All rights reserved.
3183
3184 Redistribution and use in source and binary forms, with or without
3185 modification, are permitted provided that the following conditions are
3186 met:
3187
3188 * Redistributions of source code must retain the above copyright notice,
3189 this list of conditions and the following disclaimer.
3190
3191 * Redistributions in binary form must reproduce the above copyright
3192 notice, this list of conditions and the following disclaimer in the
3193 documentation and/or other materials provided with the distribution.
3194
3195 * Neither the name "Markdown" nor the names of its contributors may
3196 be used to endorse or promote products derived from this software
3197 without specific prior written permission.
3198
3199 This software is provided by the copyright holders and contributors "as
3200 is" and any express or implied warranties, including, but not limited
3201 to, the implied warranties of merchantability and fitness for a
3202 particular purpose are disclaimed. In no event shall the copyright owner
3203 or contributors be liable for any direct, indirect, incidental, special,
3204 exemplary, or consequential damages (including, but not limited to,
3205 procurement of substitute goods or services; loss of use, data, or
3206 profits; or business interruption) however caused and on any theory of
3207 liability, whether in contract, strict liability, or tort (including
3208 negligence or otherwise) arising in any way out of the use of this
3209 software, even if advised of the possibility of such damage.
3210
3211 */
3212 ?>
3213