Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like Markdown_Parser often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Markdown_Parser, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
70 | class Markdown_Parser { |
||
71 | |||
72 | ### Configuration Variables ### |
||
73 | |||
74 | # Change to ">" for HTML output. |
||
75 | public $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX; |
||
76 | public $tab_width = MARKDOWN_TAB_WIDTH; |
||
77 | |||
78 | # Change to `true` to disallow markup or entities. |
||
79 | public $no_markup = false; |
||
80 | public $no_entities = false; |
||
81 | |||
82 | # Predefined urls and titles for reference links and images. |
||
83 | public $predef_urls = array(); |
||
84 | public $predef_titles = array(); |
||
85 | |||
86 | |||
87 | ### Parser Implementation ### |
||
88 | |||
89 | # Regex to match balanced [brackets]. |
||
90 | # Needed to insert a maximum bracked depth while converting to PHP. |
||
91 | public $nested_brackets_depth = 6; |
||
92 | public $nested_brackets_re; |
||
93 | |||
94 | public $nested_url_parenthesis_depth = 4; |
||
95 | public $nested_url_parenthesis_re; |
||
96 | |||
97 | # Table of hash values for escaped characters: |
||
98 | public $escape_chars = '\`*_{}[]()>#+-.!'; |
||
99 | public $escape_chars_re; |
||
100 | |||
101 | |||
102 | function __construct() { |
||
124 | |||
125 | |||
126 | # Internal hashes used during transformation. |
||
127 | public $urls = array(); |
||
128 | public $titles = array(); |
||
129 | public $html_hashes = array(); |
||
130 | |||
131 | # Status flag to avoid invalid nesting. |
||
132 | public $in_anchor = false; |
||
133 | |||
134 | |||
135 | function setup() { |
||
136 | # |
||
137 | # Called before the transformation process starts to setup parser |
||
138 | # states. |
||
139 | # |
||
140 | # Clear global hashes. |
||
141 | $this->urls = $this->predef_urls; |
||
142 | $this->titles = $this->predef_titles; |
||
143 | $this->html_hashes = array(); |
||
144 | |||
145 | $this->in_anchor = false; |
||
146 | } |
||
147 | |||
148 | function teardown() { |
||
149 | # |
||
150 | # Called after the transformation process to clear any variable |
||
151 | # which may be taking up memory unnecessarly. |
||
152 | # |
||
153 | $this->urls = array(); |
||
154 | $this->titles = array(); |
||
155 | $this->html_hashes = array(); |
||
156 | } |
||
157 | |||
158 | |||
159 | function transform($text) { |
||
160 | # |
||
161 | # Main function. Performs some preprocessing on the input text |
||
162 | # and pass it through the document gamut. |
||
163 | # |
||
164 | $this->setup(); |
||
165 | |||
166 | # Remove UTF-8 BOM and marker character in input, if present. |
||
167 | $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text); |
||
168 | |||
169 | # Standardize line endings: |
||
170 | # DOS to Unix and Mac to Unix |
||
171 | $text = preg_replace('{\r\n?}', "\n", $text); |
||
172 | |||
173 | # Make sure $text ends with a couple of newlines: |
||
174 | $text .= "\n\n"; |
||
175 | |||
176 | # Convert all tabs to spaces. |
||
177 | $text = $this->detab($text); |
||
178 | |||
179 | # Turn block-level HTML blocks into hash entries |
||
180 | $text = $this->hashHTMLBlocks($text); |
||
181 | |||
182 | # Strip any lines consisting only of spaces and tabs. |
||
183 | # This makes subsequent regexen easier to write, because we can |
||
184 | # match consecutive blank lines with /\n+/ instead of something |
||
185 | # contorted like /[ ]*\n+/ . |
||
186 | $text = preg_replace('/^[ ]+$/m', '', $text); |
||
187 | |||
188 | # Run document gamut methods. |
||
189 | foreach ($this->document_gamut as $method => $priority) { |
||
190 | $text = $this->$method($text); |
||
191 | } |
||
192 | |||
193 | $this->teardown(); |
||
194 | |||
195 | return $text . "\n"; |
||
196 | } |
||
197 | |||
198 | public $document_gamut = array( |
||
199 | # Strip link definitions, store in hashes. |
||
200 | "stripLinkDefinitions" => 20, |
||
201 | |||
202 | "runBasicBlockGamut" => 30, |
||
203 | ); |
||
204 | |||
205 | |||
206 | View Code Duplication | function stripLinkDefinitions($text) { |
|
207 | # |
||
208 | # Strips link definitions from text, stores the URLs and titles in |
||
209 | # hash references. |
||
210 | # |
||
211 | $less_than_tab = $this->tab_width - 1; |
||
212 | |||
213 | # Link defs are in the form: ^[id]: url "optional title" |
||
214 | $text = preg_replace_callback('{ |
||
215 | ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1 |
||
216 | [ ]* |
||
217 | \n? # maybe *one* newline |
||
218 | [ ]* |
||
219 | (?: |
||
220 | <(.+?)> # url = $2 |
||
221 | | |
||
222 | (\S+?) # url = $3 |
||
223 | ) |
||
224 | [ ]* |
||
225 | \n? # maybe one newline |
||
226 | [ ]* |
||
227 | (?: |
||
228 | (?<=\s) # lookbehind for whitespace |
||
229 | ["(] |
||
230 | (.*?) # title = $4 |
||
231 | [")] |
||
232 | [ ]* |
||
233 | )? # title is optional |
||
234 | (?:\n+|\Z) |
||
235 | }xm', |
||
236 | array(&$this, '_stripLinkDefinitions_callback'), |
||
237 | $text); |
||
238 | return $text; |
||
239 | } |
||
240 | function _stripLinkDefinitions_callback($matches) { |
||
241 | $link_id = strtolower($matches[1]); |
||
242 | $url = $matches[2] == '' ? $matches[3] : $matches[2]; |
||
243 | $this->urls[$link_id] = $url; |
||
244 | $this->titles[$link_id] =& $matches[4]; |
||
245 | return ''; # String that will replace the block |
||
246 | } |
||
247 | |||
248 | |||
249 | function hashHTMLBlocks($text) { |
||
250 | if ($this->no_markup) return $text; |
||
251 | |||
252 | $less_than_tab = $this->tab_width - 1; |
||
253 | |||
254 | # Hashify HTML blocks: |
||
255 | # We only want to do this for block-level HTML tags, such as headers, |
||
256 | # lists, and tables. That's because we still want to wrap <p>s around |
||
257 | # "paragraphs" that are wrapped in non-block-level tags, such as anchors, |
||
258 | # phrase emphasis, and spans. The list of tags we're looking for is |
||
259 | # hard-coded: |
||
260 | # |
||
261 | # * List "a" is made of tags which can be both inline or block-level. |
||
262 | # These will be treated block-level when the start tag is alone on |
||
263 | # its line, otherwise they're not matched here and will be taken as |
||
264 | # inline later. |
||
265 | # * List "b" is made of tags which are always block-level; |
||
266 | # |
||
267 | $block_tags_a_re = 'ins|del'; |
||
268 | $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'. |
||
269 | 'script|noscript|form|fieldset|iframe|math|svg|'. |
||
270 | 'article|section|nav|aside|hgroup|header|footer|'. |
||
271 | 'figure'; |
||
272 | |||
273 | # Regular expression for the content of a block tag. |
||
274 | $nested_tags_level = 4; |
||
275 | $attr = ' |
||
276 | (?> # optional tag attributes |
||
277 | \s # starts with whitespace |
||
278 | (?> |
||
279 | [^>"/]+ # text outside quotes |
||
280 | | |
||
281 | /+(?!>) # slash not followed by ">" |
||
282 | | |
||
283 | "[^"]*" # text inside double quotes (tolerate ">") |
||
284 | | |
||
285 | \'[^\']*\' # text inside single quotes (tolerate ">") |
||
286 | )* |
||
287 | )? |
||
288 | '; |
||
289 | $content = |
||
290 | str_repeat(' |
||
291 | (?> |
||
292 | [^<]+ # content without tag |
||
293 | | |
||
294 | <\2 # nested opening tag |
||
295 | '.$attr.' # attributes |
||
296 | (?> |
||
297 | /> |
||
298 | | |
||
299 | >', $nested_tags_level). # end of opening tag |
||
300 | '.*?'. # last level nested tag content |
||
301 | str_repeat(' |
||
302 | </\2\s*> # closing nested tag |
||
303 | ) |
||
304 | | |
||
305 | <(?!/\2\s*> # other tags with a different name |
||
306 | ) |
||
307 | )*', |
||
308 | $nested_tags_level); |
||
309 | $content2 = str_replace('\2', '\3', $content); |
||
310 | |||
311 | # First, look for nested blocks, e.g.: |
||
312 | # <div> |
||
313 | # <div> |
||
314 | # tags for inner block must be indented. |
||
315 | # </div> |
||
316 | # </div> |
||
317 | # |
||
318 | # The outermost tags must start at the left margin for this to match, and |
||
319 | # the inner nested divs must be indented. |
||
320 | # We need to do this before the next, more liberal match, because the next |
||
321 | # match will start at the first `<div>` and stop at the first `</div>`. |
||
322 | $text = preg_replace_callback('{(?> |
||
323 | (?> |
||
324 | (?<=\n\n) # Starting after a blank line |
||
325 | | # or |
||
326 | \A\n? # the beginning of the doc |
||
327 | ) |
||
328 | ( # save in $1 |
||
329 | |||
330 | # Match from `\n<tag>` to `</tag>\n`, handling nested tags |
||
331 | # in between. |
||
332 | |||
333 | [ ]{0,'.$less_than_tab.'} |
||
334 | <('.$block_tags_b_re.')# start tag = $2 |
||
335 | '.$attr.'> # attributes followed by > and \n |
||
336 | '.$content.' # content, support nesting |
||
337 | </\2> # the matching end tag |
||
338 | [ ]* # trailing spaces/tabs |
||
339 | (?=\n+|\Z) # followed by a newline or end of document |
||
340 | |||
341 | | # Special version for tags of group a. |
||
342 | |||
343 | [ ]{0,'.$less_than_tab.'} |
||
344 | <('.$block_tags_a_re.')# start tag = $3 |
||
345 | '.$attr.'>[ ]*\n # attributes followed by > |
||
346 | '.$content2.' # content, support nesting |
||
347 | </\3> # the matching end tag |
||
348 | [ ]* # trailing spaces/tabs |
||
349 | (?=\n+|\Z) # followed by a newline or end of document |
||
350 | |||
351 | | # Special case just for <hr />. It was easier to make a special |
||
352 | # case than to make the other regex more complicated. |
||
353 | |||
354 | [ ]{0,'.$less_than_tab.'} |
||
355 | <(hr) # start tag = $2 |
||
356 | '.$attr.' # attributes |
||
357 | /?> # the matching end tag |
||
358 | [ ]* |
||
359 | (?=\n{2,}|\Z) # followed by a blank line or end of document |
||
360 | |||
361 | | # Special case for standalone HTML comments: |
||
362 | |||
363 | [ ]{0,'.$less_than_tab.'} |
||
364 | (?s: |
||
365 | <!-- .*? --> |
||
366 | ) |
||
367 | [ ]* |
||
368 | (?=\n{2,}|\Z) # followed by a blank line or end of document |
||
369 | |||
370 | | # PHP and ASP-style processor instructions (<? and <%) |
||
371 | |||
372 | [ ]{0,'.$less_than_tab.'} |
||
373 | (?s: |
||
374 | <([?%]) # $2 |
||
375 | .*? |
||
376 | \2> |
||
377 | ) |
||
378 | [ ]* |
||
379 | (?=\n{2,}|\Z) # followed by a blank line or end of document |
||
380 | |||
381 | ) |
||
382 | )}Sxmi', |
||
383 | array(&$this, '_hashHTMLBlocks_callback'), |
||
384 | $text); |
||
385 | |||
386 | return $text; |
||
387 | } |
||
388 | function _hashHTMLBlocks_callback($matches) { |
||
389 | $text = $matches[1]; |
||
390 | $key = $this->hashBlock($text); |
||
391 | return "\n\n$key\n\n"; |
||
392 | } |
||
393 | |||
394 | |||
395 | function hashPart($text, $boundary = 'X') { |
||
396 | # |
||
397 | # Called whenever a tag must be hashed when a function insert an atomic |
||
398 | # element in the text stream. Passing $text to through this function gives |
||
399 | # a unique text-token which will be reverted back when calling unhash. |
||
400 | # |
||
401 | # The $boundary argument specify what character should be used to surround |
||
402 | # the token. By convension, "B" is used for block elements that needs not |
||
403 | # to be wrapped into paragraph tags at the end, ":" is used for elements |
||
404 | # that are word separators and "X" is used in the general case. |
||
405 | # |
||
406 | # Swap back any tag hash found in $text so we do not have to `unhash` |
||
407 | # multiple times at the end. |
||
408 | $text = $this->unhash($text); |
||
409 | |||
410 | # Then hash the block. |
||
411 | static $i = 0; |
||
412 | $key = "$boundary\x1A" . ++$i . $boundary; |
||
413 | $this->html_hashes[$key] = $text; |
||
414 | return $key; # String that will replace the tag. |
||
415 | } |
||
416 | |||
417 | |||
418 | function hashBlock($text) { |
||
419 | # |
||
420 | # Shortcut function for hashPart with block-level boundaries. |
||
421 | # |
||
422 | return $this->hashPart($text, 'B'); |
||
423 | } |
||
424 | |||
425 | |||
426 | public $block_gamut = array( |
||
427 | # |
||
428 | # These are all the transformations that form block-level |
||
429 | # tags like paragraphs, headers, and list items. |
||
430 | # |
||
431 | "doHeaders" => 10, |
||
432 | "doHorizontalRules" => 20, |
||
433 | |||
434 | "doLists" => 40, |
||
435 | "doCodeBlocks" => 50, |
||
436 | "doBlockQuotes" => 60, |
||
437 | ); |
||
438 | |||
439 | function runBlockGamut($text) { |
||
440 | # |
||
441 | # Run block gamut tranformations. |
||
442 | # |
||
443 | # We need to escape raw HTML in Markdown source before doing anything |
||
444 | # else. This need to be done for each block, and not only at the |
||
445 | # beginning in the Markdown function since hashed blocks can be part of |
||
446 | # list items and could have been indented. Indented blocks would have |
||
447 | # been seen as a code block in a previous pass of hashHTMLBlocks. |
||
448 | $text = $this->hashHTMLBlocks($text); |
||
449 | |||
450 | return $this->runBasicBlockGamut($text); |
||
451 | } |
||
452 | |||
453 | function runBasicBlockGamut($text) { |
||
454 | # |
||
455 | # Run block gamut tranformations, without hashing HTML blocks. This is |
||
456 | # useful when HTML blocks are known to be already hashed, like in the first |
||
457 | # whole-document pass. |
||
458 | # |
||
459 | foreach ($this->block_gamut as $method => $priority) { |
||
460 | $text = $this->$method($text); |
||
461 | } |
||
462 | |||
463 | # Finally form paragraph and restore hashed blocks. |
||
464 | $text = $this->formParagraphs($text); |
||
465 | |||
466 | return $text; |
||
467 | } |
||
468 | |||
469 | |||
470 | function doHorizontalRules($text) { |
||
471 | # Do Horizontal Rules: |
||
472 | return preg_replace( |
||
473 | '{ |
||
474 | ^[ ]{0,3} # Leading space |
||
475 | ([-*_]) # $1: First marker |
||
476 | (?> # Repeated marker group |
||
477 | [ ]{0,2} # Zero, one, or two spaces. |
||
478 | \1 # Marker character |
||
479 | ){2,} # Group repeated at least twice |
||
480 | [ ]* # Tailing spaces |
||
481 | $ # End of line. |
||
482 | }mx', |
||
483 | "\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n", |
||
484 | $text); |
||
485 | } |
||
486 | |||
487 | |||
488 | public $span_gamut = array( |
||
489 | # |
||
490 | # These are all the transformations that occur *within* block-level |
||
491 | # tags like paragraphs, headers, and list items. |
||
492 | # |
||
493 | # Process character escapes, code spans, and inline HTML |
||
494 | # in one shot. |
||
495 | "parseSpan" => -30, |
||
496 | |||
497 | # Process anchor and image tags. Images must come first, |
||
498 | # because ![foo][f] looks like an anchor. |
||
499 | "doImages" => 10, |
||
500 | "doAnchors" => 20, |
||
501 | |||
502 | # Make links out of things like `<http://example.com/>` |
||
503 | # Must come after doAnchors, because you can use < and > |
||
504 | # delimiters in inline links like [this](<url>). |
||
505 | "doAutoLinks" => 30, |
||
506 | "encodeAmpsAndAngles" => 40, |
||
507 | |||
508 | "doItalicsAndBold" => 50, |
||
509 | "doHardBreaks" => 60, |
||
510 | ); |
||
511 | |||
512 | function runSpanGamut($text) { |
||
513 | # |
||
514 | # Run span gamut tranformations. |
||
515 | # |
||
516 | foreach ($this->span_gamut as $method => $priority) { |
||
517 | $text = $this->$method($text); |
||
518 | } |
||
519 | |||
520 | return $text; |
||
521 | } |
||
522 | |||
523 | |||
524 | function doHardBreaks($text) { |
||
525 | # Do hard breaks: |
||
526 | return preg_replace_callback('/ {2,}\n/', |
||
527 | array(&$this, '_doHardBreaks_callback'), $text); |
||
528 | } |
||
529 | function _doHardBreaks_callback($matches) { |
||
532 | |||
533 | |||
534 | View Code Duplication | function doAnchors($text) { |
|
535 | # |
||
536 | # Turn Markdown link shortcuts into XHTML <a> tags. |
||
537 | # |
||
538 | if ($this->in_anchor) return $text; |
||
539 | $this->in_anchor = true; |
||
540 | |||
541 | # |
||
542 | # First, handle reference-style links: [link text] [id] |
||
543 | # |
||
544 | $text = preg_replace_callback('{ |
||
545 | ( # wrap whole match in $1 |
||
546 | \[ |
||
547 | ('.$this->nested_brackets_re.') # link text = $2 |
||
548 | \] |
||
549 | |||
550 | [ ]? # one optional space |
||
551 | (?:\n[ ]*)? # one optional newline followed by spaces |
||
552 | |||
553 | \[ |
||
554 | (.*?) # id = $3 |
||
555 | \] |
||
556 | ) |
||
557 | }xs', |
||
558 | array(&$this, '_doAnchors_reference_callback'), $text); |
||
559 | |||
560 | # |
||
561 | # Next, inline-style links: [link text](url "optional title") |
||
562 | # |
||
563 | $text = preg_replace_callback('{ |
||
564 | ( # wrap whole match in $1 |
||
565 | \[ |
||
566 | ('.$this->nested_brackets_re.') # link text = $2 |
||
567 | \] |
||
568 | \( # literal paren |
||
569 | [ \n]* |
||
570 | (?: |
||
571 | <(.+?)> # href = $3 |
||
572 | | |
||
573 | ('.$this->nested_url_parenthesis_re.') # href = $4 |
||
574 | ) |
||
575 | [ \n]* |
||
576 | ( # $5 |
||
577 | ([\'"]) # quote char = $6 |
||
578 | (.*?) # Title = $7 |
||
579 | \6 # matching quote |
||
580 | [ \n]* # ignore any spaces/tabs between closing quote and ) |
||
581 | )? # title is optional |
||
582 | \) |
||
583 | ) |
||
584 | }xs', |
||
585 | array(&$this, '_doAnchors_inline_callback'), $text); |
||
586 | |||
587 | # |
||
588 | # Last, handle reference-style shortcuts: [link text] |
||
589 | # These must come last in case you've also got [link text][1] |
||
590 | # or [link text](/foo) |
||
591 | # |
||
592 | $text = preg_replace_callback('{ |
||
593 | ( # wrap whole match in $1 |
||
594 | \[ |
||
595 | ([^\[\]]+) # link text = $2; can\'t contain [ or ] |
||
596 | \] |
||
597 | ) |
||
598 | }xs', |
||
599 | array(&$this, '_doAnchors_reference_callback'), $text); |
||
600 | |||
601 | $this->in_anchor = false; |
||
602 | return $text; |
||
603 | } |
||
604 | function _doAnchors_reference_callback($matches) { |
||
605 | $whole_match = $matches[1]; |
||
606 | $link_text = $matches[2]; |
||
607 | $link_id =& $matches[3]; |
||
608 | |||
609 | if ($link_id == "") { |
||
610 | # for shortcut links like [this][] or [this]. |
||
611 | $link_id = $link_text; |
||
612 | } |
||
613 | |||
614 | # lower-case and turn embedded newlines into spaces |
||
615 | $link_id = strtolower($link_id); |
||
616 | $link_id = preg_replace('{[ ]?\n}', ' ', $link_id); |
||
617 | |||
618 | if (isset($this->urls[$link_id])) { |
||
619 | $url = $this->urls[$link_id]; |
||
620 | $url = $this->encodeAttribute($url); |
||
621 | |||
622 | $result = "<a href=\"$url\""; |
||
623 | View Code Duplication | if ( isset( $this->titles[$link_id] ) ) { |
|
624 | $title = $this->titles[$link_id]; |
||
625 | $title = $this->encodeAttribute($title); |
||
626 | $result .= " title=\"$title\""; |
||
627 | } |
||
628 | |||
629 | $link_text = $this->runSpanGamut($link_text); |
||
630 | $result .= ">$link_text</a>"; |
||
631 | $result = $this->hashPart($result); |
||
632 | } |
||
633 | else { |
||
634 | $result = $whole_match; |
||
635 | } |
||
636 | return $result; |
||
637 | } |
||
638 | View Code Duplication | function _doAnchors_inline_callback($matches) { |
|
639 | $whole_match = $matches[1]; |
||
640 | $link_text = $this->runSpanGamut($matches[2]); |
||
641 | $url = $matches[3] == '' ? $matches[4] : $matches[3]; |
||
642 | $title =& $matches[7]; |
||
643 | |||
644 | $url = $this->encodeAttribute($url); |
||
645 | |||
646 | $result = "<a href=\"$url\""; |
||
647 | if (isset($title)) { |
||
648 | $title = $this->encodeAttribute($title); |
||
649 | $result .= " title=\"$title\""; |
||
650 | } |
||
651 | |||
652 | $link_text = $this->runSpanGamut($link_text); |
||
653 | $result .= ">$link_text</a>"; |
||
654 | |||
655 | return $this->hashPart($result); |
||
656 | } |
||
657 | |||
658 | |||
659 | View Code Duplication | function doImages($text) { |
|
660 | # |
||
661 | # Turn Markdown image shortcuts into <img> tags. |
||
662 | # |
||
663 | # |
||
664 | # First, handle reference-style labeled images: ![alt text][id] |
||
665 | # |
||
666 | $text = preg_replace_callback('{ |
||
667 | ( # wrap whole match in $1 |
||
668 | !\[ |
||
669 | ('.$this->nested_brackets_re.') # alt text = $2 |
||
670 | \] |
||
671 | |||
672 | [ ]? # one optional space |
||
673 | (?:\n[ ]*)? # one optional newline followed by spaces |
||
674 | |||
675 | \[ |
||
676 | (.*?) # id = $3 |
||
677 | \] |
||
678 | |||
679 | ) |
||
680 | }xs', |
||
681 | array(&$this, '_doImages_reference_callback'), $text); |
||
682 | |||
683 | # |
||
684 | # Next, handle inline images:  |
||
685 | # Don't forget: encode * and _ |
||
686 | # |
||
687 | $text = preg_replace_callback('{ |
||
688 | ( # wrap whole match in $1 |
||
689 | !\[ |
||
690 | ('.$this->nested_brackets_re.') # alt text = $2 |
||
691 | \] |
||
692 | \s? # One optional whitespace character |
||
693 | \( # literal paren |
||
694 | [ \n]* |
||
695 | (?: |
||
696 | <(\S*)> # src url = $3 |
||
697 | | |
||
698 | ('.$this->nested_url_parenthesis_re.') # src url = $4 |
||
699 | ) |
||
700 | [ \n]* |
||
701 | ( # $5 |
||
702 | ([\'"]) # quote char = $6 |
||
703 | (.*?) # title = $7 |
||
704 | \6 # matching quote |
||
705 | [ \n]* |
||
706 | )? # title is optional |
||
707 | \) |
||
708 | ) |
||
709 | }xs', |
||
710 | array(&$this, '_doImages_inline_callback'), $text); |
||
711 | |||
712 | return $text; |
||
713 | } |
||
714 | function _doImages_reference_callback($matches) { |
||
715 | $whole_match = $matches[1]; |
||
716 | $alt_text = $matches[2]; |
||
717 | $link_id = strtolower($matches[3]); |
||
718 | |||
719 | if ($link_id == "") { |
||
720 | $link_id = strtolower($alt_text); # for shortcut links like ![this][]. |
||
721 | } |
||
722 | |||
723 | $alt_text = $this->encodeAttribute($alt_text); |
||
724 | if (isset($this->urls[$link_id])) { |
||
725 | $url = $this->encodeAttribute($this->urls[$link_id]); |
||
726 | $result = "<img src=\"$url\" alt=\"$alt_text\""; |
||
727 | View Code Duplication | if (isset($this->titles[$link_id])) { |
|
728 | $title = $this->titles[$link_id]; |
||
729 | $title = $this->encodeAttribute($title); |
||
730 | $result .= " title=\"$title\""; |
||
731 | } |
||
732 | $result .= $this->empty_element_suffix; |
||
733 | $result = $this->hashPart($result); |
||
734 | } |
||
735 | else { |
||
736 | # If there's no such link ID, leave intact: |
||
737 | $result = $whole_match; |
||
738 | } |
||
739 | |||
740 | return $result; |
||
741 | } |
||
742 | View Code Duplication | function _doImages_inline_callback($matches) { |
|
743 | $whole_match = $matches[1]; |
||
744 | $alt_text = $matches[2]; |
||
745 | $url = $matches[3] == '' ? $matches[4] : $matches[3]; |
||
746 | $title =& $matches[7]; |
||
747 | |||
748 | $alt_text = $this->encodeAttribute($alt_text); |
||
749 | $url = $this->encodeAttribute($url); |
||
750 | $result = "<img src=\"$url\" alt=\"$alt_text\""; |
||
751 | if (isset($title)) { |
||
752 | $title = $this->encodeAttribute($title); |
||
753 | $result .= " title=\"$title\""; # $title already quoted |
||
754 | } |
||
755 | $result .= $this->empty_element_suffix; |
||
756 | |||
757 | return $this->hashPart($result); |
||
758 | } |
||
759 | |||
760 | |||
761 | function doHeaders($text) { |
||
762 | # Setext-style headers: |
||
763 | # Header 1 |
||
764 | # ======== |
||
765 | # |
||
766 | # Header 2 |
||
767 | # -------- |
||
768 | # |
||
769 | $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx', |
||
770 | array(&$this, '_doHeaders_callback_setext'), $text); |
||
771 | |||
772 | # atx-style headers: |
||
773 | # # Header 1 |
||
774 | # ## Header 2 |
||
775 | # ## Header 2 with closing hashes ## |
||
776 | # ... |
||
777 | # ###### Header 6 |
||
778 | # |
||
779 | $text = preg_replace_callback('{ |
||
780 | ^(\#{1,6}) # $1 = string of #\'s |
||
781 | [ ]* |
||
782 | (.+?) # $2 = Header text |
||
783 | [ ]* |
||
784 | \#* # optional closing #\'s (not counted) |
||
785 | \n+ |
||
786 | }xm', |
||
787 | array(&$this, '_doHeaders_callback_atx'), $text); |
||
788 | |||
789 | return $text; |
||
790 | } |
||
791 | function _doHeaders_callback_setext($matches) { |
||
800 | function _doHeaders_callback_atx($matches) { |
||
801 | $level = strlen($matches[1]); |
||
802 | $block = "<h$level>".$this->runSpanGamut($matches[2])."</h$level>"; |
||
803 | return "\n" . $this->hashBlock($block) . "\n\n"; |
||
804 | } |
||
805 | |||
806 | |||
807 | function doLists($text) { |
||
808 | # |
||
809 | # Form HTML ordered (numbered) and unordered (bulleted) lists. |
||
810 | # |
||
811 | $less_than_tab = $this->tab_width - 1; |
||
812 | |||
813 | # Re-usable patterns to match list item bullets and number markers: |
||
814 | $marker_ul_re = '[*+-]'; |
||
815 | $marker_ol_re = '\d+[\.]'; |
||
816 | $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; |
||
817 | |||
818 | $markers_relist = array( |
||
819 | $marker_ul_re => $marker_ol_re, |
||
820 | $marker_ol_re => $marker_ul_re, |
||
821 | ); |
||
822 | |||
823 | foreach ($markers_relist as $marker_re => $other_marker_re) { |
||
824 | # Re-usable pattern to match any entirel ul or ol list: |
||
825 | $whole_list_re = ' |
||
826 | ( # $1 = whole list |
||
827 | ( # $2 |
||
828 | ([ ]{0,'.$less_than_tab.'}) # $3 = number of spaces |
||
829 | ('.$marker_re.') # $4 = first list item marker |
||
830 | [ ]+ |
||
831 | ) |
||
832 | (?s:.+?) |
||
833 | ( # $5 |
||
834 | \z |
||
835 | | |
||
836 | \n{2,} |
||
837 | (?=\S) |
||
838 | (?! # Negative lookahead for another list item marker |
||
839 | [ ]* |
||
840 | '.$marker_re.'[ ]+ |
||
841 | ) |
||
842 | | |
||
843 | (?= # Lookahead for another kind of list |
||
844 | \n |
||
845 | \3 # Must have the same indentation |
||
846 | '.$other_marker_re.'[ ]+ |
||
847 | ) |
||
848 | ) |
||
849 | ) |
||
850 | '; // mx |
||
851 | |||
852 | # We use a different prefix before nested lists than top-level lists. |
||
853 | # See extended comment in _ProcessListItems(). |
||
854 | |||
855 | if ($this->list_level) { |
||
856 | $text = preg_replace_callback('{ |
||
857 | ^ |
||
858 | '.$whole_list_re.' |
||
859 | }mx', |
||
860 | array(&$this, '_doLists_callback'), $text); |
||
861 | } |
||
862 | else { |
||
863 | $text = preg_replace_callback('{ |
||
864 | (?:(?<=\n)\n|\A\n?) # Must eat the newline |
||
865 | '.$whole_list_re.' |
||
866 | }mx', |
||
867 | array(&$this, '_doLists_callback'), $text); |
||
868 | } |
||
869 | } |
||
870 | |||
871 | return $text; |
||
872 | } |
||
873 | function _doLists_callback($matches) { |
||
874 | # Re-usable patterns to match list item bullets and number markers: |
||
875 | $marker_ul_re = '[*+-]'; |
||
876 | $marker_ol_re = '\d+[\.]'; |
||
877 | $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; |
||
878 | |||
879 | $list = $matches[1]; |
||
880 | $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol"; |
||
881 | |||
882 | $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re ); |
||
883 | |||
884 | $list .= "\n"; |
||
885 | $result = $this->processListItems($list, $marker_any_re); |
||
886 | |||
887 | $result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>"); |
||
888 | return "\n". $result ."\n\n"; |
||
889 | } |
||
890 | |||
891 | public $list_level = 0; |
||
892 | |||
893 | function processListItems($list_str, $marker_any_re) { |
||
894 | # |
||
895 | # Process the contents of a single ordered or unordered list, splitting it |
||
896 | # into individual list items. |
||
897 | # |
||
898 | # The $this->list_level global keeps track of when we're inside a list. |
||
899 | # Each time we enter a list, we increment it; when we leave a list, |
||
900 | # we decrement. If it's zero, we're not in a list anymore. |
||
901 | # |
||
902 | # We do this because when we're not inside a list, we want to treat |
||
903 | # something like this: |
||
904 | # |
||
905 | # I recommend upgrading to version |
||
906 | # 8. Oops, now this line is treated |
||
907 | # as a sub-list. |
||
908 | # |
||
909 | # As a single paragraph, despite the fact that the second line starts |
||
910 | # with a digit-period-space sequence. |
||
911 | # |
||
912 | # Whereas when we're inside a list (or sub-list), that line will be |
||
913 | # treated as the start of a sub-list. What a kludge, huh? This is |
||
914 | # an aspect of Markdown's syntax that's hard to parse perfectly |
||
915 | # without resorting to mind-reading. Perhaps the solution is to |
||
916 | # change the syntax rules such that sub-lists must start with a |
||
917 | # starting cardinal number; e.g. "1." or "a.". |
||
918 | |||
919 | $this->list_level++; |
||
920 | |||
921 | # trim trailing blank lines: |
||
922 | $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str); |
||
923 | |||
924 | $list_str = preg_replace_callback('{ |
||
925 | (\n)? # leading line = $1 |
||
926 | (^[ ]*) # leading whitespace = $2 |
||
927 | ('.$marker_any_re.' # list marker and space = $3 |
||
928 | (?:[ ]+|(?=\n)) # space only required if item is not empty |
||
929 | ) |
||
930 | ((?s:.*?)) # list item text = $4 |
||
931 | (?:(\n+(?=\n))|\n) # tailing blank line = $5 |
||
932 | (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n)))) |
||
933 | }xm', |
||
934 | array(&$this, '_processListItems_callback'), $list_str); |
||
935 | |||
936 | $this->list_level--; |
||
937 | return $list_str; |
||
938 | } |
||
939 | function _processListItems_callback($matches) { |
||
940 | $item = $matches[4]; |
||
941 | $leading_line =& $matches[1]; |
||
942 | $leading_space =& $matches[2]; |
||
943 | $marker_space = $matches[3]; |
||
944 | $tailing_blank_line =& $matches[5]; |
||
945 | |||
946 | View Code Duplication | if ($leading_line || $tailing_blank_line || |
|
947 | preg_match('/\n{2,}/', $item)) |
||
948 | { |
||
949 | # Replace marker with the appropriate whitespace indentation |
||
950 | $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item; |
||
951 | $item = $this->runBlockGamut($this->outdent($item)."\n"); |
||
952 | } |
||
953 | else { |
||
954 | # Recursion for sub-lists: |
||
955 | $item = $this->doLists($this->outdent($item)); |
||
956 | $item = preg_replace('/\n+$/', '', $item); |
||
957 | $item = $this->runSpanGamut($item); |
||
958 | } |
||
959 | |||
960 | return "<li>" . $item . "</li>\n"; |
||
961 | } |
||
962 | |||
963 | |||
964 | function doCodeBlocks($text) { |
||
965 | # |
||
966 | # Process Markdown `<pre><code>` blocks. |
||
967 | # |
||
968 | $text = preg_replace_callback('{ |
||
969 | (?:\n\n|\A\n?) |
||
970 | ( # $1 = the code block -- one or more lines, starting with a space/tab |
||
971 | (?> |
||
972 | [ ]{'.$this->tab_width.'} # Lines must start with a tab or a tab-width of spaces |
||
973 | .*\n+ |
||
974 | )+ |
||
975 | ) |
||
976 | ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc |
||
977 | }xm', |
||
978 | array(&$this, '_doCodeBlocks_callback'), $text); |
||
979 | |||
980 | return $text; |
||
981 | } |
||
982 | function _doCodeBlocks_callback($matches) { |
||
983 | $codeblock = $matches[1]; |
||
984 | |||
985 | $codeblock = $this->outdent($codeblock); |
||
986 | $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES); |
||
987 | |||
988 | # trim leading newlines and trailing newlines |
||
989 | $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock); |
||
990 | |||
991 | $codeblock = "<pre><code>$codeblock\n</code></pre>"; |
||
992 | return "\n\n".$this->hashBlock($codeblock)."\n\n"; |
||
993 | } |
||
994 | |||
995 | |||
996 | function makeCodeSpan($code) { |
||
997 | # |
||
998 | # Create a code span markup for $code. Called from handleSpanToken. |
||
999 | # |
||
1000 | $code = htmlspecialchars(trim($code), ENT_NOQUOTES); |
||
1001 | return $this->hashPart("<code>$code</code>"); |
||
1002 | } |
||
1003 | |||
1004 | |||
1005 | public $em_relist = array( |
||
1006 | '' => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S|$)(?![\.,:;]\s)', |
||
1007 | '*' => '(?<=\S|^)(?<!\*)\*(?!\*)', |
||
1008 | '_' => '(?<=\S|^)(?<!_)_(?!_)', |
||
1009 | ); |
||
1010 | public $strong_relist = array( |
||
1011 | '' => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S|$)(?![\.,:;]\s)', |
||
1012 | '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)', |
||
1013 | '__' => '(?<=\S|^)(?<!_)__(?!_)', |
||
1014 | ); |
||
1015 | public $em_strong_relist = array( |
||
1016 | '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S|$)(?![\.,:;]\s)', |
||
1017 | '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)', |
||
1018 | '___' => '(?<=\S|^)(?<!_)___(?!_)', |
||
1019 | ); |
||
1020 | public $em_strong_prepared_relist; |
||
1021 | |||
1022 | function prepareItalicsAndBold() { |
||
1023 | # |
||
1024 | # Prepare regular expressions for searching emphasis tokens in any |
||
1025 | # context. |
||
1026 | # |
||
1027 | foreach ($this->em_relist as $em => $em_re) { |
||
1028 | foreach ($this->strong_relist as $strong => $strong_re) { |
||
1029 | # Construct list of allowed token expressions. |
||
1030 | $token_relist = array(); |
||
1031 | if (isset($this->em_strong_relist["$em$strong"])) { |
||
1032 | $token_relist[] = $this->em_strong_relist["$em$strong"]; |
||
1033 | } |
||
1034 | $token_relist[] = $em_re; |
||
1035 | $token_relist[] = $strong_re; |
||
1036 | |||
1037 | # Construct master expression from list. |
||
1038 | $token_re = '{('. implode('|', $token_relist) .')}'; |
||
1039 | $this->em_strong_prepared_relist["$em$strong"] = $token_re; |
||
1040 | } |
||
1041 | } |
||
1042 | } |
||
1043 | |||
1044 | function doItalicsAndBold($text) { |
||
1045 | $token_stack = array(''); |
||
1046 | $text_stack = array(''); |
||
1047 | $em = ''; |
||
1048 | $strong = ''; |
||
1049 | $tree_char_em = false; |
||
1050 | |||
1051 | while (1) { |
||
1052 | # |
||
1053 | # Get prepared regular expression for seraching emphasis tokens |
||
1054 | # in current context. |
||
1055 | # |
||
1056 | $token_re = $this->em_strong_prepared_relist["$em$strong"]; |
||
1057 | |||
1058 | # |
||
1059 | # Each loop iteration search for the next emphasis token. |
||
1060 | # Each token is then passed to handleSpanToken. |
||
1061 | # |
||
1062 | $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); |
||
1063 | $text_stack[0] .= $parts[0]; |
||
1064 | $token =& $parts[1]; |
||
1065 | $text =& $parts[2]; |
||
1066 | |||
1067 | View Code Duplication | if (empty($token)) { |
|
1068 | # Reached end of text span: empty stack without emitting. |
||
1069 | # any more emphasis. |
||
1070 | while ($token_stack[0]) { |
||
1071 | $text_stack[1] .= array_shift($token_stack); |
||
1072 | $text_stack[0] .= array_shift($text_stack); |
||
1073 | } |
||
1074 | break; |
||
1075 | } |
||
1076 | |||
1077 | $token_len = strlen($token); |
||
1078 | if ($tree_char_em) { |
||
1079 | # Reached closing marker while inside a three-char emphasis. |
||
1080 | if ($token_len == 3) { |
||
1081 | # Three-char closing marker, close em and strong. |
||
1082 | array_shift($token_stack); |
||
1083 | $span = array_shift($text_stack); |
||
1084 | $span = $this->runSpanGamut($span); |
||
1085 | $span = "<strong><em>$span</em></strong>"; |
||
1086 | $text_stack[0] .= $this->hashPart($span); |
||
1087 | $em = ''; |
||
1088 | $strong = ''; |
||
1089 | } else { |
||
1090 | # Other closing marker: close one em or strong and |
||
1091 | # change current token state to match the other |
||
1092 | $token_stack[0] = str_repeat($token{0}, 3-$token_len); |
||
1093 | $tag = $token_len == 2 ? "strong" : "em"; |
||
1094 | $span = $text_stack[0]; |
||
1095 | $span = $this->runSpanGamut($span); |
||
1096 | $span = "<$tag>$span</$tag>"; |
||
1097 | $text_stack[0] = $this->hashPart($span); |
||
1098 | $$tag = ''; # $$tag stands for $em or $strong |
||
1099 | } |
||
1100 | $tree_char_em = false; |
||
1101 | } else if ($token_len == 3) { |
||
1102 | if ($em) { |
||
1103 | # Reached closing marker for both em and strong. |
||
1104 | # Closing strong marker: |
||
1105 | for ($i = 0; $i < 2; ++$i) { |
||
1106 | $shifted_token = array_shift($token_stack); |
||
1107 | $tag = strlen($shifted_token) == 2 ? "strong" : "em"; |
||
1108 | $span = array_shift($text_stack); |
||
1109 | $span = $this->runSpanGamut($span); |
||
1110 | $span = "<$tag>$span</$tag>"; |
||
1111 | $text_stack[0] .= $this->hashPart($span); |
||
1112 | $$tag = ''; # $$tag stands for $em or $strong |
||
1113 | } |
||
1114 | } else { |
||
1115 | # Reached opening three-char emphasis marker. Push on token |
||
1116 | # stack; will be handled by the special condition above. |
||
1117 | $em = $token{0}; |
||
1118 | $strong = "$em$em"; |
||
1119 | array_unshift($token_stack, $token); |
||
1120 | array_unshift($text_stack, ''); |
||
1121 | $tree_char_em = true; |
||
1122 | } |
||
1123 | } else if ($token_len == 2) { |
||
1124 | if ($strong) { |
||
1125 | # Unwind any dangling emphasis marker: |
||
1126 | View Code Duplication | if (strlen($token_stack[0]) == 1) { |
|
1127 | $text_stack[1] .= array_shift($token_stack); |
||
1128 | $text_stack[0] .= array_shift($text_stack); |
||
1129 | } |
||
1130 | # Closing strong marker: |
||
1131 | array_shift($token_stack); |
||
1132 | $span = array_shift($text_stack); |
||
1133 | $span = $this->runSpanGamut($span); |
||
1134 | $span = "<strong>$span</strong>"; |
||
1135 | $text_stack[0] .= $this->hashPart($span); |
||
1136 | $strong = ''; |
||
1137 | } else { |
||
1138 | array_unshift($token_stack, $token); |
||
1139 | array_unshift($text_stack, ''); |
||
1140 | $strong = $token; |
||
1141 | } |
||
1142 | } else { |
||
1143 | # Here $token_len == 1 |
||
1144 | if ($em) { |
||
1145 | if (strlen($token_stack[0]) == 1) { |
||
1146 | # Closing emphasis marker: |
||
1147 | array_shift($token_stack); |
||
1148 | $span = array_shift($text_stack); |
||
1149 | $span = $this->runSpanGamut($span); |
||
1150 | $span = "<em>$span</em>"; |
||
1151 | $text_stack[0] .= $this->hashPart($span); |
||
1152 | $em = ''; |
||
1153 | } else { |
||
1154 | $text_stack[0] .= $token; |
||
1155 | } |
||
1156 | } else { |
||
1157 | array_unshift($token_stack, $token); |
||
1158 | array_unshift($text_stack, ''); |
||
1159 | $em = $token; |
||
1160 | } |
||
1161 | } |
||
1162 | } |
||
1163 | return $text_stack[0]; |
||
1164 | } |
||
1165 | |||
1166 | |||
1167 | function doBlockQuotes($text) { |
||
1168 | $text = preg_replace_callback('/ |
||
1169 | ( # Wrap whole match in $1 |
||
1170 | (?> |
||
1171 | ^[ ]*>[ ]? # ">" at the start of a line |
||
1172 | .+\n # rest of the first line |
||
1173 | (.+\n)* # subsequent consecutive lines |
||
1174 | \n* # blanks |
||
1175 | )+ |
||
1176 | ) |
||
1177 | /xm', |
||
1178 | array(&$this, '_doBlockQuotes_callback'), $text); |
||
1179 | |||
1180 | return $text; |
||
1181 | } |
||
1182 | function _doBlockQuotes_callback($matches) { |
||
1183 | $bq = $matches[1]; |
||
1184 | # trim one level of quoting - trim whitespace-only lines |
||
1185 | $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq); |
||
1186 | $bq = $this->runBlockGamut($bq); # recurse |
||
1187 | |||
1188 | $bq = preg_replace('/^/m', " ", $bq); |
||
1189 | # These leading spaces cause problem with <pre> content, |
||
1190 | # so we need to fix that: |
||
1191 | $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx', |
||
1192 | array(&$this, '_doBlockQuotes_callback2'), $bq); |
||
1193 | |||
1194 | return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n"; |
||
1195 | } |
||
1196 | function _doBlockQuotes_callback2($matches) { |
||
1197 | $pre = $matches[1]; |
||
1198 | $pre = preg_replace('/^ /m', '', $pre); |
||
1199 | return $pre; |
||
1200 | } |
||
1201 | |||
1202 | |||
1203 | function formParagraphs($text) { |
||
1204 | # |
||
1205 | # Params: |
||
1206 | # $text - string to process with html <p> tags |
||
1207 | # |
||
1208 | # Strip leading and trailing lines: |
||
1209 | $text = preg_replace('/\A\n+|\n+\z/', '', $text); |
||
1210 | |||
1211 | $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY); |
||
1212 | |||
1213 | # |
||
1214 | # Wrap <p> tags and unhashify HTML blocks |
||
1215 | # |
||
1216 | foreach ($grafs as $key => $value) { |
||
1217 | if (!preg_match('/^B\x1A[0-9]+B$/', $value)) { |
||
1218 | # Is a paragraph. |
||
1219 | $value = $this->runSpanGamut($value); |
||
1220 | $value = preg_replace('/^([ ]*)/', "<p>", $value); |
||
1221 | $value .= "</p>"; |
||
1222 | $grafs[$key] = $this->unhash($value); |
||
1223 | } |
||
1224 | else { |
||
1225 | # Is a block. |
||
1226 | # Modify elements of @grafs in-place... |
||
1227 | $graf = $value; |
||
1228 | $block = $this->html_hashes[$graf]; |
||
1229 | $graf = $block; |
||
1230 | // if (preg_match('{ |
||
1231 | // \A |
||
1232 | // ( # $1 = <div> tag |
||
1233 | // <div \s+ |
||
1234 | // [^>]* |
||
1235 | // \b |
||
1236 | // markdown\s*=\s* ([\'"]) # $2 = attr quote char |
||
1237 | // 1 |
||
1238 | // \2 |
||
1239 | // [^>]* |
||
1240 | // > |
||
1241 | // ) |
||
1242 | // ( # $3 = contents |
||
1243 | // .* |
||
1244 | // ) |
||
1245 | // (</div>) # $4 = closing tag |
||
1246 | // \z |
||
1247 | // }xs', $block, $matches)) |
||
1248 | // { |
||
1249 | // list(, $div_open, , $div_content, $div_close) = $matches; |
||
1250 | // |
||
1251 | // # We can't call Markdown(), because that resets the hash; |
||
1252 | // # that initialization code should be pulled into its own sub, though. |
||
1253 | // $div_content = $this->hashHTMLBlocks($div_content); |
||
1254 | // |
||
1255 | // # Run document gamut methods on the content. |
||
1256 | // foreach ($this->document_gamut as $method => $priority) { |
||
1257 | // $div_content = $this->$method($div_content); |
||
1258 | // } |
||
1259 | // |
||
1260 | // $div_open = preg_replace( |
||
1261 | // '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open); |
||
1262 | // |
||
1263 | // $graf = $div_open . "\n" . $div_content . "\n" . $div_close; |
||
1264 | // } |
||
1265 | $grafs[$key] = $graf; |
||
1266 | } |
||
1267 | } |
||
1268 | |||
1269 | return implode("\n\n", $grafs); |
||
1270 | } |
||
1271 | |||
1272 | |||
1273 | function encodeAttribute($text) { |
||
1274 | # |
||
1275 | # Encode text for a double-quoted HTML attribute. This function |
||
1276 | # is *not* suitable for attributes enclosed in single quotes. |
||
1277 | # |
||
1278 | $text = $this->encodeAmpsAndAngles($text); |
||
1279 | $text = str_replace('"', '"', $text); |
||
1280 | return $text; |
||
1281 | } |
||
1282 | |||
1283 | |||
1284 | function encodeAmpsAndAngles($text) { |
||
1285 | # |
||
1286 | # Smart processing for ampersands and angle brackets that need to |
||
1287 | # be encoded. Valid character entities are left alone unless the |
||
1288 | # no-entities mode is set. |
||
1289 | # |
||
1290 | if ($this->no_entities) { |
||
1291 | $text = str_replace('&', '&', $text); |
||
1292 | } else { |
||
1293 | # Ampersand-encoding based entirely on Nat Irons's Amputator |
||
1294 | # MT plugin: <http://bumppo.net/projects/amputator/> |
||
1295 | $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/', |
||
1296 | '&', $text);; |
||
1297 | } |
||
1298 | # Encode remaining <'s |
||
1299 | $text = str_replace('<', '<', $text); |
||
1300 | |||
1301 | return $text; |
||
1302 | } |
||
1303 | |||
1304 | |||
1305 | function doAutoLinks($text) { |
||
1306 | $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i', |
||
1307 | array(&$this, '_doAutoLinks_url_callback'), $text); |
||
1308 | |||
1309 | # Email addresses: <[email protected]> |
||
1310 | $text = preg_replace_callback('{ |
||
1311 | < |
||
1312 | (?:mailto:)? |
||
1313 | ( |
||
1314 | (?: |
||
1315 | [-!#$%&\'*+/=?^_`.{|}~\w\x80-\xFF]+ |
||
1316 | | |
||
1317 | ".*?" |
||
1318 | ) |
||
1319 | \@ |
||
1320 | (?: |
||
1321 | [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+ |
||
1322 | | |
||
1323 | \[[\d.a-fA-F:]+\] # IPv4 & IPv6 |
||
1324 | ) |
||
1325 | ) |
||
1326 | > |
||
1327 | }xi', |
||
1328 | array(&$this, '_doAutoLinks_email_callback'), $text); |
||
1329 | $text = preg_replace_callback('{<(tel:([^\'">\s]+))>}i',array(&$this, '_doAutoLinks_tel_callback'), $text); |
||
1330 | |||
1331 | return $text; |
||
1332 | } |
||
1333 | function _doAutoLinks_tel_callback($matches) { |
||
1334 | $url = $this->encodeAttribute($matches[1]); |
||
1335 | $tel = $this->encodeAttribute($matches[2]); |
||
1336 | $link = "<a href=\"$url\">$tel</a>"; |
||
1337 | return $this->hashPart($link); |
||
1338 | } |
||
1339 | function _doAutoLinks_url_callback($matches) { |
||
1340 | $url = $this->encodeAttribute($matches[1]); |
||
1341 | $link = "<a href=\"$url\">$url</a>"; |
||
1342 | return $this->hashPart($link); |
||
1343 | } |
||
1344 | function _doAutoLinks_email_callback($matches) { |
||
1345 | $address = $matches[1]; |
||
1346 | $link = $this->encodeEmailAddress($address); |
||
1347 | return $this->hashPart($link); |
||
1348 | } |
||
1349 | |||
1350 | |||
1351 | function encodeEmailAddress($addr) { |
||
1352 | # |
||
1353 | # Input: an email address, e.g. "[email protected]" |
||
1354 | # |
||
1355 | # Output: the email address as a mailto link, with each character |
||
1356 | # of the address encoded as either a decimal or hex entity, in |
||
1357 | # the hopes of foiling most address harvesting spam bots. E.g.: |
||
1358 | # |
||
1359 | # <p><a href="mailto:foo |
||
1360 | # @example.co |
||
1361 | # m">foo@exampl |
||
1362 | # e.com</a></p> |
||
1363 | # |
||
1364 | # Based by a filter by Matthew Wickline, posted to BBEdit-Talk. |
||
1365 | # With some optimizations by Milian Wolff. |
||
1366 | # |
||
1367 | $addr = "mailto:" . $addr; |
||
1368 | $chars = preg_split('/(?<!^)(?!$)/', $addr); |
||
1369 | $seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed. |
||
1370 | |||
1371 | foreach ($chars as $key => $char) { |
||
1372 | $ord = ord($char); |
||
1373 | # Ignore non-ascii chars. |
||
1374 | if ($ord < 128) { |
||
1375 | $r = ($seed * (1 + $key)) % 100; # Pseudo-random function. |
||
1376 | # roughly 10% raw, 45% hex, 45% dec |
||
1377 | # '@' *must* be encoded. I insist. |
||
1378 | if ($r > 90 && $char != '@') /* do nothing */; |
||
1379 | else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';'; |
||
1380 | else $chars[$key] = '&#'.$ord.';'; |
||
1381 | } |
||
1382 | } |
||
1383 | |||
1384 | $addr = implode('', $chars); |
||
1385 | $text = implode('', array_slice($chars, 7)); # text without `mailto:` |
||
1386 | $addr = "<a href=\"$addr\">$text</a>"; |
||
1387 | |||
1388 | return $addr; |
||
1389 | } |
||
1390 | |||
1391 | |||
1392 | function parseSpan($str) { |
||
1393 | # |
||
1394 | # Take the string $str and parse it into tokens, hashing embedded HTML, |
||
1395 | # escaped characters and handling code spans. |
||
1396 | # |
||
1397 | $output = ''; |
||
1398 | |||
1399 | $span_re = '{ |
||
1400 | ( |
||
1401 | \\\\'.$this->escape_chars_re.' |
||
1402 | | |
||
1403 | (?<![`\\\\]) |
||
1404 | `+ # code span marker |
||
1405 | '.( $this->no_markup ? '' : ' |
||
1406 | | |
||
1407 | <!-- .*? --> # comment |
||
1408 | | |
||
1409 | <\?.*?\?> | <%.*?%> # processing instruction |
||
1410 | | |
||
1411 | <[!$]?[-a-zA-Z0-9:_]+ # regular tags |
||
1412 | (?> |
||
1413 | \s |
||
1414 | (?>[^"\'>]+|"[^"]*"|\'[^\']*\')* |
||
1415 | )? |
||
1416 | > |
||
1417 | | |
||
1418 | <[-a-zA-Z0-9:_]+\s*/> # xml-style empty tag |
||
1419 | | |
||
1420 | </[-a-zA-Z0-9:_]+\s*> # closing tag |
||
1421 | ').' |
||
1422 | ) |
||
1423 | }xs'; |
||
1424 | |||
1425 | while (1) { |
||
1426 | # |
||
1427 | # Each loop iteration search for either the next tag, the next |
||
1428 | # openning code span marker, or the next escaped character. |
||
1429 | # Each token is then passed to handleSpanToken. |
||
1430 | # |
||
1431 | $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE); |
||
1432 | |||
1433 | # Create token from text preceding tag. |
||
1434 | if ($parts[0] != "") { |
||
1435 | $output .= $parts[0]; |
||
1436 | } |
||
1437 | |||
1438 | # Check if we reach the end. |
||
1439 | if (isset($parts[1])) { |
||
1440 | $output .= $this->handleSpanToken($parts[1], $parts[2]); |
||
1441 | $str = $parts[2]; |
||
1442 | } |
||
1443 | else { |
||
1444 | break; |
||
1445 | } |
||
1446 | } |
||
1447 | |||
1448 | return $output; |
||
1449 | } |
||
1450 | |||
1451 | |||
1452 | function handleSpanToken($token, &$str) { |
||
1453 | # |
||
1454 | # Handle $token provided by parseSpan by determining its nature and |
||
1455 | # returning the corresponding value that should replace it. |
||
1456 | # |
||
1457 | switch ($token{0}) { |
||
1458 | case "\\": |
||
1459 | return $this->hashPart("&#". ord($token{1}). ";"); |
||
1460 | case "`": |
||
1461 | # Search for end marker in remaining text. |
||
1462 | if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm', |
||
1463 | $str, $matches)) |
||
1464 | { |
||
1465 | $str = $matches[2]; |
||
1466 | $codespan = $this->makeCodeSpan($matches[1]); |
||
1467 | return $this->hashPart($codespan); |
||
1468 | } |
||
1469 | return $token; // return as text since no ending marker found. |
||
1470 | default: |
||
1471 | return $this->hashPart($token); |
||
1472 | } |
||
1473 | } |
||
1474 | |||
1475 | |||
1476 | function outdent($text) { |
||
1477 | # |
||
1478 | # Remove one level of line-leading tabs or spaces |
||
1479 | # |
||
1480 | return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text); |
||
1481 | } |
||
1482 | |||
1483 | |||
1484 | # String length function for detab. `_initDetab` will create a function to |
||
1485 | # hanlde UTF-8 if the default function does not exist. |
||
1486 | public $utf8_strlen = 'mb_strlen'; |
||
1487 | |||
1488 | function detab($text) { |
||
1489 | # |
||
1490 | # Replace tabs with the appropriate amount of space. |
||
1491 | # |
||
1492 | # For each line we separate the line in blocks delemited by |
||
1493 | # tab characters. Then we reconstruct every line by adding the |
||
1494 | # appropriate number of space between each blocks. |
||
1495 | |||
1496 | $text = preg_replace_callback('/^.*\t.*$/m', |
||
1497 | array(&$this, '_detab_callback'), $text); |
||
1498 | |||
1499 | return $text; |
||
1500 | } |
||
1501 | function _detab_callback($matches) { |
||
1502 | $line = $matches[0]; |
||
1503 | $strlen = $this->utf8_strlen; # strlen function for UTF-8. |
||
1504 | |||
1505 | # Split in blocks. |
||
1506 | $blocks = explode("\t", $line); |
||
1507 | # Add each blocks to the line. |
||
1508 | $line = $blocks[0]; |
||
1509 | unset($blocks[0]); # Do not add first block twice. |
||
1510 | foreach ($blocks as $block) { |
||
1511 | # Calculate amount of space, insert spaces, insert block. |
||
1512 | $amount = $this->tab_width - |
||
1513 | $strlen($line, 'UTF-8') % $this->tab_width; |
||
1514 | $line .= str_repeat(" ", $amount) . $block; |
||
1515 | } |
||
1516 | return $line; |
||
1517 | } |
||
1518 | function _initDetab() { |
||
1519 | # |
||
1520 | # Check for the availability of the function in the `utf8_strlen` property |
||
1521 | # (initially `mb_strlen`). If the function is not available, create a |
||
1522 | # function that will loosely count the number of UTF-8 characters with a |
||
1523 | # regular expression. |
||
1524 | # |
||
1525 | if (function_exists($this->utf8_strlen)) return; |
||
1526 | $this->utf8_strlen = create_function('$text', 'return preg_match_all( |
||
1527 | "/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/", |
||
1528 | $text, $m);'); |
||
1529 | } |
||
1530 | |||
1531 | |||
1532 | function unhash($text) { |
||
1533 | # |
||
1534 | # Swap back in all the tags hashed by _HashHTMLBlocks. |
||
1535 | # |
||
1536 | return preg_replace_callback('/(.)\x1A[0-9]+\1/', |
||
1537 | array(&$this, '_unhash_callback'), $text); |
||
1538 | } |
||
1539 | function _unhash_callback($matches) { |
||
1542 | |||
1543 | } |
||
1544 | |||
1545 | |||
1546 | # |
||
1547 | # Markdown Extra Parser Class |
||
1548 | # |
||
1549 | |||
1550 | class MarkdownExtra_Parser extends Markdown_Parser { |
||
1551 | |||
1552 | ### Configuration Variables ### |
||
1553 | |||
1554 | # Prefix for footnote ids. |
||
1555 | public $fn_id_prefix = ""; |
||
1556 | |||
1557 | # Optional title attribute for footnote links and backlinks. |
||
1558 | public $fn_link_title = MARKDOWN_FN_LINK_TITLE; |
||
1559 | public $fn_backlink_title = MARKDOWN_FN_BACKLINK_TITLE; |
||
1560 | |||
1561 | # Optional class attribute for footnote links and backlinks. |
||
1562 | public $fn_link_class = MARKDOWN_FN_LINK_CLASS; |
||
1563 | public $fn_backlink_class = MARKDOWN_FN_BACKLINK_CLASS; |
||
1564 | |||
1565 | # Optional class prefix for fenced code block. |
||
1566 | public $code_class_prefix = MARKDOWN_CODE_CLASS_PREFIX; |
||
1567 | # Class attribute for code blocks goes on the `code` tag; |
||
1568 | # setting this to true will put attributes on the `pre` tag instead. |
||
1569 | public $code_attr_on_pre = MARKDOWN_CODE_ATTR_ON_PRE; |
||
1570 | |||
1571 | # Predefined abbreviations. |
||
1572 | public $predef_abbr = array(); |
||
1573 | |||
1574 | |||
1575 | ### Parser Implementation ### |
||
1576 | |||
1577 | function __construct() { |
||
1578 | # |
||
1579 | # Constructor function. Initialize the parser object. |
||
1580 | # |
||
1581 | # Add extra escapable characters before parent constructor |
||
1582 | # initialize the table. |
||
1583 | $this->escape_chars .= ':|'; |
||
1584 | |||
1585 | # Insert extra document, block, and span transformations. |
||
1586 | # Parent constructor will do the sorting. |
||
1587 | $this->document_gamut += array( |
||
1588 | "doFencedCodeBlocks" => 5, |
||
1589 | "stripFootnotes" => 15, |
||
1590 | "stripAbbreviations" => 25, |
||
1591 | "appendFootnotes" => 50, |
||
3194 | ?> |
||
If you suppress an error, we recommend checking for the error condition explicitly: