├── README.md ├── demo ├── index.php └── style.css ├── extension-meta.php └── markdown.php /README.md: -------------------------------------------------------------------------------- 1 | WordPress Package Parser 2 | ======================== 3 | 4 | A PHP library for parsing WordPress plugin and theme metadata. Point it at a ZIP package and it will: 5 | 6 | - Tell you whether it contains a plugin or a theme. 7 | - Give you the metadata from the comment header (Version, Description, Author URI, etc). 8 | - Parse readme.txt into a list of headers and sections. 9 | - Convert readme.txt contents from Markdown to HTML (optional). 10 | 11 | Basic usage 12 | ----------- 13 | 14 | Extract plugin metadata: 15 | 16 | ```php 17 | require 'wp-extension-meta/extension-meta.php'; 18 | $package = WshWordPressPackageParser::parsePackage('sample-plugin.zip', true); 19 | print_r($package); 20 | ``` 21 | 22 | Sample output: 23 | 24 | ``` 25 | Array 26 | ( 27 | [header] => Array 28 | ( 29 | [Name] => Plugin Name 30 | [PluginURI] => http://example.com/ 31 | [Version] => 1.7 32 | [Description] => This plugin does stuff. 33 | [Author] => Yahnis Elsts 34 | [AuthorURI] => http://w-shadow.com/ 35 | [TextDomain] => sample-plugin 36 | [DomainPath] => 37 | [Network] => 38 | [Title] => Plugin Name 39 | ) 40 | 41 | [readme] => Array 42 | ( 43 | [name] => Plugin Name 44 | [contributors] => Array 45 | ( 46 | [0] => whiteshadow 47 | ) 48 | 49 | [tags] => Array 50 | ( 51 | [0] => sample 52 | [1] => tag 53 | [2] => stuff 54 | ) 55 | 56 | [requires] => 3.2 57 | [tested] => 3.5.1 58 | [stable] => 1.7 59 | [short_description] => This is the short description from the readme. 60 | [sections] => Array 61 | ( 62 | [Description] => This is the Description section of the readme. 63 | [Installation] => ... 64 | [Changelog] => ... 65 | ) 66 | ) 67 | [pluginFile] => sample-plugin/sample-plugin.php 68 | [stylesheet] => 69 | [type] => plugin 70 | ) 71 | ``` 72 | 73 | Requirements 74 | ------------ 75 | PHP 5.2. 76 | 77 | Credits 78 | ------- 79 | Partially based on plugin header parsing code from the WordPress core. 80 | -------------------------------------------------------------------------------- /demo/index.php: -------------------------------------------------------------------------------- 1 | 2 |
3 |(.+?)
@i"; 432 | if ( preg_match($regex, $meta['sections']['upgrade_notice'], $matches) ){ 433 | $meta['upgrade_notice'] = trim(strip_tags($matches[1])); 434 | } 435 | } 436 | } 437 | 438 | if ( !empty($packageInfo['pluginFile']) ){ 439 | $meta['slug'] = strtolower(basename(dirname($packageInfo['pluginFile']))); 440 | } 441 | 442 | return $meta; 443 | } 444 | -------------------------------------------------------------------------------- /markdown.php: -------------------------------------------------------------------------------- 1 | 8 | # 9 | # Original Markdown 10 | # Copyright (c) 2004-2006 John Gruber 11 | #
'.$text.'
'; 153 | $text = preg_replace('{\n{2,}}', "\n\n", $text); 154 | } 155 | return $text; 156 | } 157 | 158 | function mdwp_strip_p($t) { return preg_replace('{?p>}i', '', $t); } 159 | 160 | function mdwp_hide_tags($text) { 161 | global $mdwp_hidden_tags, $mdwp_placeholders; 162 | return str_replace($mdwp_hidden_tags, $mdwp_placeholders, $text); 163 | } 164 | function mdwp_show_tags($text) { 165 | global $mdwp_hidden_tags, $mdwp_placeholders; 166 | return str_replace($mdwp_placeholders, $mdwp_hidden_tags, $text); 167 | } 168 | } 169 | 170 | 171 | ### bBlog Plugin Info ### 172 | 173 | function identify_modifier_markdown() { 174 | return array( 175 | 'name' => 'markdown', 176 | 'type' => 'modifier', 177 | 'nicename' => 'PHP Markdown Extra', 178 | 'description' => 'A text-to-HTML conversion tool for web writers', 179 | 'authors' => 'Michel Fortin and John Gruber', 180 | 'licence' => 'GPL', 181 | 'version' => MARKDOWNEXTRA_VERSION, 182 | 'help' => 'Markdown syntax allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by John Gruber. More...', 183 | ); 184 | } 185 | 186 | 187 | ### Smarty Modifier Interface ### 188 | 189 | function smarty_modifier_markdown($text) { 190 | return Markdown($text); 191 | } 192 | 193 | 194 | ### Textile Compatibility Mode ### 195 | 196 | # Rename this file to "classTextile.php" and it can replace Textile everywhere. 197 | 198 | if (strcasecmp(substr(__FILE__, -16), "classTextile.php") == 0) { 199 | # Try to include PHP SmartyPants. Should be in the same directory. 200 | @include_once 'smartypants.php'; 201 | # Fake Textile class. It calls Markdown instead. 202 | class Textile { 203 | function TextileThis($text, $lite='', $encode='') { 204 | if ($lite == '' && $encode == '') $text = Markdown($text); 205 | if (function_exists('SmartyPants')) $text = SmartyPants($text); 206 | return $text; 207 | } 208 | # Fake restricted version: restrictions are not supported for now. 209 | function TextileRestricted($text, $lite='', $noimage='') { 210 | return $this->TextileThis($text, $lite); 211 | } 212 | # Workaround to ensure compatibility with TextPattern 4.0.3. 213 | function blockLite($text) { return $text; } 214 | } 215 | } 216 | 217 | 218 | 219 | # 220 | # Markdown Parser Class 221 | # 222 | 223 | class Markdown_Parser { 224 | 225 | ### Configuration Variables ### 226 | 227 | # Change to ">" for HTML output. 228 | var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX; 229 | var $tab_width = MARKDOWN_TAB_WIDTH; 230 | 231 | # Change to `true` to disallow markup or entities. 232 | var $no_markup = false; 233 | var $no_entities = false; 234 | 235 | # Predefined urls and titles for reference links and images. 236 | var $predef_urls = array(); 237 | var $predef_titles = array(); 238 | 239 | 240 | ### Parser Implementation ### 241 | 242 | # Regex to match balanced [brackets]. 243 | # Needed to insert a maximum bracked depth while converting to PHP. 244 | var $nested_brackets_depth = 6; 245 | var $nested_brackets_re; 246 | 247 | var $nested_url_parenthesis_depth = 4; 248 | var $nested_url_parenthesis_re; 249 | 250 | # Table of hash values for escaped characters: 251 | var $escape_chars = '\`*_{}[]()>#+-.!'; 252 | var $escape_chars_re; 253 | 254 | 255 | function Markdown_Parser() { 256 | # 257 | # Constructor function. Initialize appropriate member variables. 258 | # 259 | $this->_initDetab(); 260 | $this->prepareItalicsAndBold(); 261 | 262 | $this->nested_brackets_re = 263 | str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth). 264 | str_repeat('\])*', $this->nested_brackets_depth); 265 | 266 | $this->nested_url_parenthesis_re = 267 | str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth). 268 | str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth); 269 | 270 | $this->escape_chars_re = '['.preg_quote($this->escape_chars).']'; 271 | 272 | # Sort document, block, and span gamut in ascendent priority order. 273 | asort($this->document_gamut); 274 | asort($this->block_gamut); 275 | asort($this->span_gamut); 276 | } 277 | 278 | 279 | # Internal hashes used during transformation. 280 | var $urls = array(); 281 | var $titles = array(); 282 | var $html_hashes = array(); 283 | 284 | # Status flag to avoid invalid nesting. 285 | var $in_anchor = false; 286 | 287 | 288 | function setup() { 289 | # 290 | # Called before the transformation process starts to setup parser 291 | # states. 292 | # 293 | # Clear global hashes. 294 | $this->urls = $this->predef_urls; 295 | $this->titles = $this->predef_titles; 296 | $this->html_hashes = array(); 297 | 298 | $in_anchor = false; 299 | } 300 | 301 | function teardown() { 302 | # 303 | # Called after the transformation process to clear any variable 304 | # which may be taking up memory unnecessarly. 305 | # 306 | $this->urls = array(); 307 | $this->titles = array(); 308 | $this->html_hashes = array(); 309 | } 310 | 311 | 312 | function transform($text) { 313 | # 314 | # Main function. Performs some preprocessing on the input text 315 | # and pass it through the document gamut. 316 | # 317 | $this->setup(); 318 | 319 | # Remove UTF-8 BOM and marker character in input, if present. 320 | $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text); 321 | 322 | # Standardize line endings: 323 | # DOS to Unix and Mac to Unix 324 | $text = preg_replace('{\r\n?}', "\n", $text); 325 | 326 | # Make sure $text ends with a couple of newlines: 327 | $text .= "\n\n"; 328 | 329 | # Convert all tabs to spaces. 330 | $text = $this->detab($text); 331 | 332 | # Turn block-level HTML blocks into hash entries 333 | $text = $this->hashHTMLBlocks($text); 334 | 335 | # Strip any lines consisting only of spaces and tabs. 336 | # This makes subsequent regexen easier to write, because we can 337 | # match consecutive blank lines with /\n+/ instead of something 338 | # contorted like /[ ]*\n+/ . 339 | $text = preg_replace('/^[ ]+$/m', '', $text); 340 | 341 | # Run document gamut methods. 342 | foreach ($this->document_gamut as $method => $priority) { 343 | $text = $this->$method($text); 344 | } 345 | 346 | $this->teardown(); 347 | 348 | return $text . "\n"; 349 | } 350 | 351 | var $document_gamut = array( 352 | # Strip link definitions, store in hashes. 353 | "stripLinkDefinitions" => 20, 354 | 355 | "runBasicBlockGamut" => 30, 356 | ); 357 | 358 | 359 | function stripLinkDefinitions($text) { 360 | # 361 | # Strips link definitions from text, stores the URLs and titles in 362 | # hash references. 363 | # 364 | $less_than_tab = $this->tab_width - 1; 365 | 366 | # Link defs are in the form: ^[id]: url "optional title" 367 | $text = preg_replace_callback('{ 368 | ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1 369 | [ ]* 370 | \n? # maybe *one* newline 371 | [ ]* 372 | (?: 373 | <(.+?)> # url = $2 374 | | 375 | (\S+?) # url = $3 376 | ) 377 | [ ]* 378 | \n? # maybe one newline 379 | [ ]* 380 | (?: 381 | (?<=\s) # lookbehind for whitespace 382 | ["(] 383 | (.*?) # title = $4 384 | [")] 385 | [ ]* 386 | )? # title is optional 387 | (?:\n+|\Z) 388 | }xm', 389 | array(&$this, '_stripLinkDefinitions_callback'), 390 | $text); 391 | return $text; 392 | } 393 | function _stripLinkDefinitions_callback($matches) { 394 | $link_id = strtolower($matches[1]); 395 | $url = $matches[2] == '' ? $matches[3] : $matches[2]; 396 | $this->urls[$link_id] = $url; 397 | $this->titles[$link_id] =& $matches[4]; 398 | return ''; # String that will replace the block 399 | } 400 | 401 | 402 | function hashHTMLBlocks($text) { 403 | if ($this->no_markup) return $text; 404 | 405 | $less_than_tab = $this->tab_width - 1; 406 | 407 | # Hashify HTML blocks: 408 | # We only want to do this for block-level HTML tags, such as headers, 409 | # lists, and tables. That's because we still want to wrap
s around 410 | # "paragraphs" that are wrapped in non-block-level tags, such as anchors, 411 | # phrase emphasis, and spans. The list of tags we're looking for is 412 | # hard-coded: 413 | # 414 | # * List "a" is made of tags which can be both inline or block-level. 415 | # These will be treated block-level when the start tag is alone on 416 | # its line, otherwise they're not matched here and will be taken as 417 | # inline later. 418 | # * List "b" is made of tags which are always block-level; 419 | # 420 | $block_tags_a_re = 'ins|del'; 421 | $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'. 422 | 'script|noscript|form|fieldset|iframe|math|svg|'. 423 | 'article|section|nav|aside|hgroup|header|footer|'. 424 | 'figure'; 425 | 426 | # Regular expression for the content of a block tag. 427 | $nested_tags_level = 4; 428 | $attr = ' 429 | (?> # optional tag attributes 430 | \s # starts with whitespace 431 | (?> 432 | [^>"/]+ # text outside quotes 433 | | 434 | /+(?!>) # slash not followed by ">" 435 | | 436 | "[^"]*" # text inside double quotes (tolerate ">") 437 | | 438 | \'[^\']*\' # text inside single quotes (tolerate ">") 439 | )* 440 | )? 441 | '; 442 | $content = 443 | str_repeat(' 444 | (?> 445 | [^<]+ # content without tag 446 | | 447 | <\2 # nested opening tag 448 | '.$attr.' # attributes 449 | (?> 450 | /> 451 | | 452 | >', $nested_tags_level). # end of opening tag 453 | '.*?'. # last level nested tag content 454 | str_repeat(' 455 | \2\s*> # closing nested tag 456 | ) 457 | | 458 | <(?!/\2\s*> # other tags with a different name 459 | ) 460 | )*', 461 | $nested_tags_level); 462 | $content2 = str_replace('\2', '\3', $content); 463 | 464 | # First, look for nested blocks, e.g.: 465 | #
` blocks.
1120 | #
1121 | $text = preg_replace_callback('{
1122 | (?:\n\n|\A\n?)
1123 | ( # $1 = the code block -- one or more lines, starting with a space/tab
1124 | (?>
1125 | [ ]{'.$this->tab_width.'} # Lines must start with a tab or a tab-width of spaces
1126 | .*\n+
1127 | )+
1128 | )
1129 | ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
1130 | }xm',
1131 | array(&$this, '_doCodeBlocks_callback'), $text);
1132 |
1133 | return $text;
1134 | }
1135 | function _doCodeBlocks_callback($matches) {
1136 | $codeblock = $matches[1];
1137 |
1138 | $codeblock = $this->outdent($codeblock);
1139 | $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
1140 |
1141 | # trim leading newlines and trailing newlines
1142 | $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
1143 |
1144 | $codeblock = "$codeblock\n
";
1145 | return "\n\n".$this->hashBlock($codeblock)."\n\n";
1146 | }
1147 |
1148 |
1149 | function makeCodeSpan($code) {
1150 | #
1151 | # Create a code span markup for $code. Called from handleSpanToken.
1152 | #
1153 | $code = htmlspecialchars(trim($code), ENT_NOQUOTES);
1154 | return $this->hashPart("$code
");
1155 | }
1156 |
1157 |
1158 | var $em_relist = array(
1159 | '' => '(?:(? '(?<=\S|^)(? '(?<=\S|^)(? '(?:(? '(?<=\S|^)(? '(?<=\S|^)(? '(?:(? '(?<=\S|^)(? '(?<=\S|^)(?em_relist as $em => $em_re) {
1181 | foreach ($this->strong_relist as $strong => $strong_re) {
1182 | # Construct list of allowed token expressions.
1183 | $token_relist = array();
1184 | if (isset($this->em_strong_relist["$em$strong"])) {
1185 | $token_relist[] = $this->em_strong_relist["$em$strong"];
1186 | }
1187 | $token_relist[] = $em_re;
1188 | $token_relist[] = $strong_re;
1189 |
1190 | # Construct master expression from list.
1191 | $token_re = '{('. implode('|', $token_relist) .')}';
1192 | $this->em_strong_prepared_relist["$em$strong"] = $token_re;
1193 | }
1194 | }
1195 | }
1196 |
1197 | function doItalicsAndBold($text) {
1198 | $token_stack = array('');
1199 | $text_stack = array('');
1200 | $em = '';
1201 | $strong = '';
1202 | $tree_char_em = false;
1203 |
1204 | while (1) {
1205 | #
1206 | # Get prepared regular expression for seraching emphasis tokens
1207 | # in current context.
1208 | #
1209 | $token_re = $this->em_strong_prepared_relist["$em$strong"];
1210 |
1211 | #
1212 | # Each loop iteration search for the next emphasis token.
1213 | # Each token is then passed to handleSpanToken.
1214 | #
1215 | $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
1216 | $text_stack[0] .= $parts[0];
1217 | $token =& $parts[1];
1218 | $text =& $parts[2];
1219 |
1220 | if (empty($token)) {
1221 | # Reached end of text span: empty stack without emitting.
1222 | # any more emphasis.
1223 | while ($token_stack[0]) {
1224 | $text_stack[1] .= array_shift($token_stack);
1225 | $text_stack[0] .= array_shift($text_stack);
1226 | }
1227 | break;
1228 | }
1229 |
1230 | $token_len = strlen($token);
1231 | if ($tree_char_em) {
1232 | # Reached closing marker while inside a three-char emphasis.
1233 | if ($token_len == 3) {
1234 | # Three-char closing marker, close em and strong.
1235 | array_shift($token_stack);
1236 | $span = array_shift($text_stack);
1237 | $span = $this->runSpanGamut($span);
1238 | $span = "$span";
1239 | $text_stack[0] .= $this->hashPart($span);
1240 | $em = '';
1241 | $strong = '';
1242 | } else {
1243 | # Other closing marker: close one em or strong and
1244 | # change current token state to match the other
1245 | $token_stack[0] = str_repeat($token{0}, 3-$token_len);
1246 | $tag = $token_len == 2 ? "strong" : "em";
1247 | $span = $text_stack[0];
1248 | $span = $this->runSpanGamut($span);
1249 | $span = "<$tag>$span$tag>";
1250 | $text_stack[0] = $this->hashPart($span);
1251 | $$tag = ''; # $$tag stands for $em or $strong
1252 | }
1253 | $tree_char_em = false;
1254 | } else if ($token_len == 3) {
1255 | if ($em) {
1256 | # Reached closing marker for both em and strong.
1257 | # Closing strong marker:
1258 | for ($i = 0; $i < 2; ++$i) {
1259 | $shifted_token = array_shift($token_stack);
1260 | $tag = strlen($shifted_token) == 2 ? "strong" : "em";
1261 | $span = array_shift($text_stack);
1262 | $span = $this->runSpanGamut($span);
1263 | $span = "<$tag>$span$tag>";
1264 | $text_stack[0] .= $this->hashPart($span);
1265 | $$tag = ''; # $$tag stands for $em or $strong
1266 | }
1267 | } else {
1268 | # Reached opening three-char emphasis marker. Push on token
1269 | # stack; will be handled by the special condition above.
1270 | $em = $token{0};
1271 | $strong = "$em$em";
1272 | array_unshift($token_stack, $token);
1273 | array_unshift($text_stack, '');
1274 | $tree_char_em = true;
1275 | }
1276 | } else if ($token_len == 2) {
1277 | if ($strong) {
1278 | # Unwind any dangling emphasis marker:
1279 | if (strlen($token_stack[0]) == 1) {
1280 | $text_stack[1] .= array_shift($token_stack);
1281 | $text_stack[0] .= array_shift($text_stack);
1282 | }
1283 | # Closing strong marker:
1284 | array_shift($token_stack);
1285 | $span = array_shift($text_stack);
1286 | $span = $this->runSpanGamut($span);
1287 | $span = "$span";
1288 | $text_stack[0] .= $this->hashPart($span);
1289 | $strong = '';
1290 | } else {
1291 | array_unshift($token_stack, $token);
1292 | array_unshift($text_stack, '');
1293 | $strong = $token;
1294 | }
1295 | } else {
1296 | # Here $token_len == 1
1297 | if ($em) {
1298 | if (strlen($token_stack[0]) == 1) {
1299 | # Closing emphasis marker:
1300 | array_shift($token_stack);
1301 | $span = array_shift($text_stack);
1302 | $span = $this->runSpanGamut($span);
1303 | $span = "$span";
1304 | $text_stack[0] .= $this->hashPart($span);
1305 | $em = '';
1306 | } else {
1307 | $text_stack[0] .= $token;
1308 | }
1309 | } else {
1310 | array_unshift($token_stack, $token);
1311 | array_unshift($text_stack, '');
1312 | $em = $token;
1313 | }
1314 | }
1315 | }
1316 | return $text_stack[0];
1317 | }
1318 |
1319 |
1320 | function doBlockQuotes($text) {
1321 | $text = preg_replace_callback('/
1322 | ( # Wrap whole match in $1
1323 | (?>
1324 | ^[ ]*>[ ]? # ">" at the start of a line
1325 | .+\n # rest of the first line
1326 | (.+\n)* # subsequent consecutive lines
1327 | \n* # blanks
1328 | )+
1329 | )
1330 | /xm',
1331 | array(&$this, '_doBlockQuotes_callback'), $text);
1332 |
1333 | return $text;
1334 | }
1335 | function _doBlockQuotes_callback($matches) {
1336 | $bq = $matches[1];
1337 | # trim one level of quoting - trim whitespace-only lines
1338 | $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
1339 | $bq = $this->runBlockGamut($bq); # recurse
1340 |
1341 | $bq = preg_replace('/^/m', " ", $bq);
1342 | # These leading spaces cause problem with content,
1343 | # so we need to fix that:
1344 | $bq = preg_replace_callback('{(\s*.+?
)}sx',
1345 | array(&$this, '_doBlockQuotes_callback2'), $bq);
1346 |
1347 | return "\n". $this->hashBlock("\n$bq\n
")."\n\n";
1348 | }
1349 | function _doBlockQuotes_callback2($matches) {
1350 | $pre = $matches[1];
1351 | $pre = preg_replace('/^ /m', '', $pre);
1352 | return $pre;
1353 | }
1354 |
1355 |
1356 | function formParagraphs($text) {
1357 | #
1358 | # Params:
1359 | # $text - string to process with html tags
1360 | #
1361 | # Strip leading and trailing lines:
1362 | $text = preg_replace('/\A\n+|\n+\z/', '', $text);
1363 |
1364 | $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
1365 |
1366 | #
1367 | # Wrap
tags and unhashify HTML blocks
1368 | #
1369 | foreach ($grafs as $key => $value) {
1370 | if (!preg_match('/^B\x1A[0-9]+B$/', $value)) {
1371 | # Is a paragraph.
1372 | $value = $this->runSpanGamut($value);
1373 | $value = preg_replace('/^([ ]*)/', "
", $value);
1374 | $value .= "
";
1375 | $grafs[$key] = $this->unhash($value);
1376 | }
1377 | else {
1378 | # Is a block.
1379 | # Modify elements of @grafs in-place...
1380 | $graf = $value;
1381 | $block = $this->html_hashes[$graf];
1382 | $graf = $block;
1383 | // if (preg_match('{
1384 | // \A
1385 | // ( # $1 = tag
1386 | // ]*
1388 | // \b
1389 | // markdown\s*=\s* ([\'"]) # $2 = attr quote char
1390 | // 1
1391 | // \2
1392 | // [^>]*
1393 | // >
1394 | // )
1395 | // ( # $3 = contents
1396 | // .*
1397 | // )
1398 | // () # $4 = closing tag
1399 | // \z
1400 | // }xs', $block, $matches))
1401 | // {
1402 | // list(, $div_open, , $div_content, $div_close) = $matches;
1403 | //
1404 | // # We can't call Markdown(), because that resets the hash;
1405 | // # that initialization code should be pulled into its own sub, though.
1406 | // $div_content = $this->hashHTMLBlocks($div_content);
1407 | //
1408 | // # Run document gamut methods on the content.
1409 | // foreach ($this->document_gamut as $method => $priority) {
1410 | // $div_content = $this->$method($div_content);
1411 | // }
1412 | //
1413 | // $div_open = preg_replace(
1414 | // '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open);
1415 | //
1416 | // $graf = $div_open . "\n" . $div_content . "\n" . $div_close;
1417 | // }
1418 | $grafs[$key] = $graf;
1419 | }
1420 | }
1421 |
1422 | return implode("\n\n", $grafs);
1423 | }
1424 |
1425 |
1426 | function encodeAttribute($text) {
1427 | #
1428 | # Encode text for a double-quoted HTML attribute. This function
1429 | # is *not* suitable for attributes enclosed in single quotes.
1430 | #
1431 | $text = $this->encodeAmpsAndAngles($text);
1432 | $text = str_replace('"', '"', $text);
1433 | return $text;
1434 | }
1435 |
1436 |
1437 | function encodeAmpsAndAngles($text) {
1438 | #
1439 | # Smart processing for ampersands and angle brackets that need to
1440 | # be encoded. Valid character entities are left alone unless the
1441 | # no-entities mode is set.
1442 | #
1443 | if ($this->no_entities) {
1444 | $text = str_replace('&', '&', $text);
1445 | } else {
1446 | # Ampersand-encoding based entirely on Nat Irons's Amputator
1447 | # MT plugin:
1448 | $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
1449 | '&', $text);;
1450 | }
1451 | # Encode remaining <'s
1452 | $text = str_replace('<', '<', $text);
1453 |
1454 | return $text;
1455 | }
1456 |
1457 |
1458 | function doAutoLinks($text) {
1459 | $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i',
1460 | array(&$this, '_doAutoLinks_url_callback'), $text);
1461 |
1462 | # Email addresses:
1463 | $text = preg_replace_callback('{
1464 | <
1465 | (?:mailto:)?
1466 | (
1467 | (?:
1468 | [-!#$%&\'*+/=?^_`.{|}~\w\x80-\xFF]+
1469 | |
1470 | ".*?"
1471 | )
1472 | \@
1473 | (?:
1474 | [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+
1475 | |
1476 | \[[\d.a-fA-F:]+\] # IPv4 & IPv6
1477 | )
1478 | )
1479 | >
1480 | }xi',
1481 | array(&$this, '_doAutoLinks_email_callback'), $text);
1482 |
1483 | return $text;
1484 | }
1485 | function _doAutoLinks_url_callback($matches) {
1486 | $url = $this->encodeAttribute($matches[1]);
1487 | $link = "$url";
1488 | return $this->hashPart($link);
1489 | }
1490 | function _doAutoLinks_email_callback($matches) {
1491 | $address = $matches[1];
1492 | $link = $this->encodeEmailAddress($address);
1493 | return $this->hashPart($link);
1494 | }
1495 |
1496 |
1497 | function encodeEmailAddress($addr) {
1498 | #
1499 | # Input: an email address, e.g. "foo@example.com"
1500 | #
1501 | # Output: the email address as a mailto link, with each character
1502 | # of the address encoded as either a decimal or hex entity, in
1503 | # the hopes of foiling most address harvesting spam bots. E.g.:
1504 | #
1505 | #
1509 | #
1510 | # Based by a filter by Matthew Wickline, posted to BBEdit-Talk.
1511 | # With some optimizations by Milian Wolff.
1512 | #
1513 | $addr = "mailto:" . $addr;
1514 | $chars = preg_split('/(? $char) {
1518 | $ord = ord($char);
1519 | # Ignore non-ascii chars.
1520 | if ($ord < 128) {
1521 | $r = ($seed * (1 + $key)) % 100; # Pseudo-random function.
1522 | # roughly 10% raw, 45% hex, 45% dec
1523 | # '@' *must* be encoded. I insist.
1524 | if ($r > 90 && $char != '@') /* do nothing */;
1525 | else if ($r < 45) $chars[$key] = ''.dechex($ord).';';
1526 | else $chars[$key] = ''.$ord.';';
1527 | }
1528 | }
1529 |
1530 | $addr = implode('', $chars);
1531 | $text = implode('', array_slice($chars, 7)); # text without `mailto:`
1532 | $addr = "$text";
1533 |
1534 | return $addr;
1535 | }
1536 |
1537 |
1538 | function parseSpan($str) {
1539 | #
1540 | # Take the string $str and parse it into tokens, hashing embeded HTML,
1541 | # escaped characters and handling code spans.
1542 | #
1543 | $output = '';
1544 |
1545 | $span_re = '{
1546 | (
1547 | \\\\'.$this->escape_chars_re.'
1548 | |
1549 | (?no_markup ? '' : '
1552 | |
1553 | # comment
1554 | |
1555 | <\?.*?\?> | <%.*?%> # processing instruction
1556 | |
1557 | <[!$]?[-a-zA-Z0-9:_]+ # regular tags
1558 | (?>
1559 | \s
1560 | (?>[^"\'>]+|"[^"]*"|\'[^\']*\')*
1561 | )?
1562 | >
1563 | |
1564 | <[-a-zA-Z0-9:_]+\s*/> # xml-style empty tag
1565 | |
1566 | [-a-zA-Z0-9:_]+\s*> # closing tag
1567 | ').'
1568 | )
1569 | }xs';
1570 |
1571 | while (1) {
1572 | #
1573 | # Each loop iteration seach for either the next tag, the next
1574 | # openning code span marker, or the next escaped character.
1575 | # Each token is then passed to handleSpanToken.
1576 | #
1577 | $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE);
1578 |
1579 | # Create token from text preceding tag.
1580 | if ($parts[0] != "") {
1581 | $output .= $parts[0];
1582 | }
1583 |
1584 | # Check if we reach the end.
1585 | if (isset($parts[1])) {
1586 | $output .= $this->handleSpanToken($parts[1], $parts[2]);
1587 | $str = $parts[2];
1588 | }
1589 | else {
1590 | break;
1591 | }
1592 | }
1593 |
1594 | return $output;
1595 | }
1596 |
1597 |
1598 | function handleSpanToken($token, &$str) {
1599 | #
1600 | # Handle $token provided by parseSpan by determining its nature and
1601 | # returning the corresponding value that should replace it.
1602 | #
1603 | switch ($token{0}) {
1604 | case "\\":
1605 | return $this->hashPart("". ord($token{1}). ";");
1606 | case "`":
1607 | # Search for end marker in remaining text.
1608 | if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm',
1609 | $str, $matches))
1610 | {
1611 | $str = $matches[2];
1612 | $codespan = $this->makeCodeSpan($matches[1]);
1613 | return $this->hashPart($codespan);
1614 | }
1615 | return $token; // return as text since no ending marker found.
1616 | default:
1617 | return $this->hashPart($token);
1618 | }
1619 | }
1620 |
1621 |
1622 | function outdent($text) {
1623 | #
1624 | # Remove one level of line-leading tabs or spaces
1625 | #
1626 | return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text);
1627 | }
1628 |
1629 |
1630 | # String length function for detab. `_initDetab` will create a function to
1631 | # hanlde UTF-8 if the default function does not exist.
1632 | var $utf8_strlen = 'mb_strlen';
1633 |
1634 | function detab($text) {
1635 | #
1636 | # Replace tabs with the appropriate amount of space.
1637 | #
1638 | # For each line we separate the line in blocks delemited by
1639 | # tab characters. Then we reconstruct every line by adding the
1640 | # appropriate number of space between each blocks.
1641 |
1642 | $text = preg_replace_callback('/^.*\t.*$/m',
1643 | array(&$this, '_detab_callback'), $text);
1644 |
1645 | return $text;
1646 | }
1647 | function _detab_callback($matches) {
1648 | $line = $matches[0];
1649 | $strlen = $this->utf8_strlen; # strlen function for UTF-8.
1650 |
1651 | # Split in blocks.
1652 | $blocks = explode("\t", $line);
1653 | # Add each blocks to the line.
1654 | $line = $blocks[0];
1655 | unset($blocks[0]); # Do not add first block twice.
1656 | foreach ($blocks as $block) {
1657 | # Calculate amount of space, insert spaces, insert block.
1658 | $amount = $this->tab_width -
1659 | $strlen($line, 'UTF-8') % $this->tab_width;
1660 | $line .= str_repeat(" ", $amount) . $block;
1661 | }
1662 | return $line;
1663 | }
1664 | function _initDetab() {
1665 | #
1666 | # Check for the availability of the function in the `utf8_strlen` property
1667 | # (initially `mb_strlen`). If the function is not available, create a
1668 | # function that will loosely count the number of UTF-8 characters with a
1669 | # regular expression.
1670 | #
1671 | if (function_exists($this->utf8_strlen)) return;
1672 | $this->utf8_strlen = create_function('$text', 'return preg_match_all(
1673 | "/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/",
1674 | $text, $m);');
1675 | }
1676 |
1677 |
1678 | function unhash($text) {
1679 | #
1680 | # Swap back in all the tags hashed by _HashHTMLBlocks.
1681 | #
1682 | return preg_replace_callback('/(.)\x1A[0-9]+\1/',
1683 | array(&$this, '_unhash_callback'), $text);
1684 | }
1685 | function _unhash_callback($matches) {
1686 | return $this->html_hashes[$matches[0]];
1687 | }
1688 |
1689 | }
1690 |
1691 |
1692 | #
1693 | # Markdown Extra Parser Class
1694 | #
1695 |
1696 | class MarkdownExtra_Parser extends Markdown_Parser {
1697 |
1698 | ### Configuration Variables ###
1699 |
1700 | # Prefix for footnote ids.
1701 | var $fn_id_prefix = "";
1702 |
1703 | # Optional title attribute for footnote links and backlinks.
1704 | var $fn_link_title = MARKDOWN_FN_LINK_TITLE;
1705 | var $fn_backlink_title = MARKDOWN_FN_BACKLINK_TITLE;
1706 |
1707 | # Optional class attribute for footnote links and backlinks.
1708 | var $fn_link_class = MARKDOWN_FN_LINK_CLASS;
1709 | var $fn_backlink_class = MARKDOWN_FN_BACKLINK_CLASS;
1710 |
1711 | # Optional class prefix for fenced code block.
1712 | var $code_class_prefix = MARKDOWN_CODE_CLASS_PREFIX;
1713 | # Class attribute for code blocks goes on the `code` tag;
1714 | # setting this to true will put attributes on the `pre` tag instead.
1715 | var $code_attr_on_pre = MARKDOWN_CODE_ATTR_ON_PRE;
1716 |
1717 | # Predefined abbreviations.
1718 | var $predef_abbr = array();
1719 |
1720 |
1721 | ### Parser Implementation ###
1722 |
1723 | function MarkdownExtra_Parser() {
1724 | #
1725 | # Constructor function. Initialize the parser object.
1726 | #
1727 | # Add extra escapable characters before parent constructor
1728 | # initialize the table.
1729 | $this->escape_chars .= ':|';
1730 |
1731 | # Insert extra document, block, and span transformations.
1732 | # Parent constructor will do the sorting.
1733 | $this->document_gamut += array(
1734 | "doFencedCodeBlocks" => 5,
1735 | "stripFootnotes" => 15,
1736 | "stripAbbreviations" => 25,
1737 | "appendFootnotes" => 50,
1738 | );
1739 | $this->block_gamut += array(
1740 | "doFencedCodeBlocks" => 5,
1741 | "doTables" => 15,
1742 | "doDefLists" => 45,
1743 | );
1744 | $this->span_gamut += array(
1745 | "doFootnotes" => 5,
1746 | "doAbbreviations" => 70,
1747 | );
1748 |
1749 | parent::Markdown_Parser();
1750 | }
1751 |
1752 |
1753 | # Extra variables used during extra transformations.
1754 | var $footnotes = array();
1755 | var $footnotes_ordered = array();
1756 | var $footnotes_ref_count = array();
1757 | var $footnotes_numbers = array();
1758 | var $abbr_desciptions = array();
1759 | var $abbr_word_re = '';
1760 |
1761 | # Give the current footnote number.
1762 | var $footnote_counter = 1;
1763 |
1764 |
1765 | function setup() {
1766 | #
1767 | # Setting up Extra-specific variables.
1768 | #
1769 | parent::setup();
1770 |
1771 | $this->footnotes = array();
1772 | $this->footnotes_ordered = array();
1773 | $this->footnotes_ref_count = array();
1774 | $this->footnotes_numbers = array();
1775 | $this->abbr_desciptions = array();
1776 | $this->abbr_word_re = '';
1777 | $this->footnote_counter = 1;
1778 |
1779 | foreach ($this->predef_abbr as $abbr_word => $abbr_desc) {
1780 | if ($this->abbr_word_re)
1781 | $this->abbr_word_re .= '|';
1782 | $this->abbr_word_re .= preg_quote($abbr_word);
1783 | $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
1784 | }
1785 | }
1786 |
1787 | function teardown() {
1788 | #
1789 | # Clearing Extra-specific variables.
1790 | #
1791 | $this->footnotes = array();
1792 | $this->footnotes_ordered = array();
1793 | $this->footnotes_ref_count = array();
1794 | $this->footnotes_numbers = array();
1795 | $this->abbr_desciptions = array();
1796 | $this->abbr_word_re = '';
1797 |
1798 | parent::teardown();
1799 | }
1800 |
1801 |
1802 | ### Extra Attribute Parser ###
1803 |
1804 | # Expression to use to catch attributes (includes the braces)
1805 | var $id_class_attr_catch_re = '\{((?:[ ]*[#.][-_:a-zA-Z0-9]+){1,})[ ]*\}';
1806 | # Expression to use when parsing in a context when no capture is desired
1807 | var $id_class_attr_nocatch_re = '\{(?:[ ]*[#.][-_:a-zA-Z0-9]+){1,}[ ]*\}';
1808 |
1809 | function doExtraAttributes($tag_name, $attr) {
1810 | #
1811 | # Parse attributes caught by the $this->id_class_attr_catch_re expression
1812 | # and return the HTML-formatted list of attributes.
1813 | #
1814 | # Currently supported attributes are .class and #id.
1815 | #
1816 | if (empty($attr)) return "";
1817 |
1818 | # Split on components
1819 | preg_match_all("/[.#][-_:a-zA-Z0-9]+/", $attr, $matches);
1820 | $elements = $matches[0];
1821 |
1822 | # handle classes and ids (only first id taken into account)
1823 | $classes = array();
1824 | $id = false;
1825 | foreach ($elements as $element) {
1826 | if ($element{0} == '.') {
1827 | $classes[] = substr($element, 1);
1828 | } else if ($element{0} == '#') {
1829 | if ($id === false) $id = substr($element, 1);
1830 | }
1831 | }
1832 |
1833 | # compose attributes as string
1834 | $attr_str = "";
1835 | if (!empty($id)) {
1836 | $attr_str .= ' id="'.$id.'"';
1837 | }
1838 | if (!empty($classes)) {
1839 | $attr_str .= ' class="'.implode(" ", $classes).'"';
1840 | }
1841 | return $attr_str;
1842 | }
1843 |
1844 |
1845 | ### HTML Block Parser ###
1846 |
1847 | # Tags that are always treated as block tags:
1848 | var $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';
1849 |
1850 | # Tags treated as block tags only if the opening tag is alone on its line:
1851 | var $context_block_tags_re = 'script|noscript|ins|del|iframe|object|source|track|param|math|svg|canvas|audio|video';
1852 |
1853 | # Tags where markdown="1" default to span mode:
1854 | var $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address';
1855 |
1856 | # Tags which must not have their contents modified, no matter where
1857 | # they appear:
1858 | var $clean_tags_re = 'script|math|svg';
1859 |
1860 | # Tags that do not need to be closed.
1861 | var $auto_close_tags_re = 'hr|img|param|source|track';
1862 |
1863 |
1864 | function hashHTMLBlocks($text) {
1865 | #
1866 | # Hashify HTML Blocks and "clean tags".
1867 | #
1868 | # We only want to do this for block-level HTML tags, such as headers,
1869 | # lists, and tables. That's because we still want to wrap s around
1870 | # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
1871 | # phrase emphasis, and spans. The list of tags we're looking for is
1872 | # hard-coded.
1873 | #
1874 | # This works by calling _HashHTMLBlocks_InMarkdown, which then calls
1875 | # _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1"
1876 | # attribute is found within a tag, _HashHTMLBlocks_InHTML calls back
1877 | # _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag.
1878 | # These two functions are calling each other. It's recursive!
1879 | #
1880 | if ($this->no_markup) return $text;
1881 |
1882 | #
1883 | # Call the HTML-in-Markdown hasher.
1884 | #
1885 | list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text);
1886 |
1887 | return $text;
1888 | }
1889 | function _hashHTMLBlocks_inMarkdown($text, $indent = 0,
1890 | $enclosing_tag_re = '', $span = false)
1891 | {
1892 | #
1893 | # Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags.
1894 | #
1895 | # * $indent is the number of space to be ignored when checking for code
1896 | # blocks. This is important because if we don't take the indent into
1897 | # account, something like this (which looks right) won't work as expected:
1898 | #
1899 | #
1900 | #
1901 | # Hello World. <-- Is this a Markdown code block or text?
1902 | # <-- Is this a Markdown code block or a real tag?
1903 | #
1904 | #
1905 | # If you don't like this, just don't indent the tag on which
1906 | # you apply the markdown="1" attribute.
1907 | #
1908 | # * If $enclosing_tag_re is not empty, stops at the first unmatched closing
1909 | # tag with that name. Nested tags supported.
1910 | #
1911 | # * If $span is true, text inside must treated as span. So any double
1912 | # newline will be replaced by a single newline so that it does not create
1913 | # paragraphs.
1914 | #
1915 | # Returns an array of that form: ( processed text , remaining text )
1916 | #
1917 | if ($text === '') return array('', '');
1918 |
1919 | # Regex to check for the presense of newlines around a block tag.
1920 | $newline_before_re = '/(?:^\n?|\n\n)*$/';
1921 | $newline_after_re =
1922 | '{
1923 | ^ # Start of text following the tag.
1924 | (?>[ ]*)? # Optional comment.
1925 | [ ]*\n # Must be followed by newline.
1926 | }xs';
1927 |
1928 | # Regex to match any tag.
1929 | $block_tag_re =
1930 | '{
1931 | ( # $2: Capture whole tag.
1932 | ? # Any opening or closing tag.
1933 | (?> # Tag name.
1934 | '.$this->block_tags_re.' |
1935 | '.$this->context_block_tags_re.' |
1936 | '.$this->clean_tags_re.' |
1937 | (?!\s)'.$enclosing_tag_re.'
1938 | )
1939 | (?:
1940 | (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
1941 | (?>
1942 | ".*?" | # Double quotes (can contain `>`)
1943 | \'.*?\' | # Single quotes (can contain `>`)
1944 | .+? # Anything but quotes and `>`.
1945 | )*?
1946 | )?
1947 | > # End of tag.
1948 | |
1949 | # HTML Comment
1950 | |
1951 | <\?.*?\?> | <%.*?%> # Processing instruction
1952 | |
1953 | # CData Block
1954 | |
1955 | # Code span marker
1956 | `+
1957 | '. ( !$span ? ' # If not in span.
1958 | |
1959 | # Indented code block
1960 | (?: ^[ ]*\n | ^ | \n[ ]*\n )
1961 | [ ]{'.($indent+4).'}[^\n]* \n
1962 | (?>
1963 | (?: [ ]{'.($indent+4).'}[^\n]* | [ ]* ) \n
1964 | )*
1965 | |
1966 | # Fenced code block marker
1967 | (?<= ^ | \n )
1968 | [ ]{0,'.($indent+3).'}~{3,}
1969 | [ ]*
1970 | (?:
1971 | [.]?[-_:a-zA-Z0-9]+ # standalone class name
1972 | |
1973 | '.$this->id_class_attr_nocatch_re.' # extra attributes
1974 | )?
1975 | [ ]*
1976 | \n
1977 | ' : '' ). ' # End (if not is span).
1978 | )
1979 | }xs';
1980 |
1981 |
1982 | $depth = 0; # Current depth inside the tag tree.
1983 | $parsed = ""; # Parsed text that will be returned.
1984 |
1985 | #
1986 | # Loop through every tag until we find the closing tag of the parent
1987 | # or loop until reaching the end of text if no parent tag specified.
1988 | #
1989 | do {
1990 | #
1991 | # Split the text using the first $tag_match pattern found.
1992 | # Text before pattern will be first in the array, text after
1993 | # pattern will be at the end, and between will be any catches made
1994 | # by the pattern.
1995 | #
1996 | $parts = preg_split($block_tag_re, $text, 2,
1997 | PREG_SPLIT_DELIM_CAPTURE);
1998 |
1999 | # If in Markdown span mode, add a empty-string span-level hash
2000 | # after each newline to prevent triggering any block element.
2001 | if ($span) {
2002 | $void = $this->hashPart("", ':');
2003 | $newline = "$void\n";
2004 | $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void;
2005 | }
2006 |
2007 | $parsed .= $parts[0]; # Text before current tag.
2008 |
2009 | # If end of $text has been reached. Stop loop.
2010 | if (count($parts) < 3) {
2011 | $text = "";
2012 | break;
2013 | }
2014 |
2015 | $tag = $parts[1]; # Tag to handle.
2016 | $text = $parts[2]; # Remaining text after current tag.
2017 | $tag_re = preg_quote($tag); # For use in a regular expression.
2018 |
2019 | #
2020 | # Check for: Code span marker
2021 | #
2022 | if ($tag{0} == "`") {
2023 | # Find corresponding end marker.
2024 | $tag_re = preg_quote($tag);
2025 | if (preg_match('{^(?>.+?|\n(?!\n))*?(?.*\n)*?[ ]{'.($fence_indent).'}'.$fence_re.'[ ]*(?:\n|$)}', $text,
2045 | $matches))
2046 | {
2047 | # End marker found: pass text unchanged until marker.
2048 | $parsed .= $tag . $matches[0];
2049 | $text = substr($text, strlen($matches[0]));
2050 | }
2051 | else {
2052 | # No end marker: just skip it.
2053 | $parsed .= $tag;
2054 | }
2055 | }
2056 | #
2057 | # Check for: Indented code block.
2058 | #
2059 | else if ($tag{0} == "\n" || $tag{0} == " ") {
2060 | # Indented code block: pass it unchanged, will be handled
2061 | # later.
2062 | $parsed .= $tag;
2063 | }
2064 | #
2065 | # Check for: Opening Block level tag or
2066 | # Opening Context Block tag (like ins and del)
2067 | # used as a block tag (tag is alone on it's line).
2068 | #
2069 | else if (preg_match('{^<(?:'.$this->block_tags_re.')\b}', $tag) ||
2070 | ( preg_match('{^<(?:'.$this->context_block_tags_re.')\b}', $tag) &&
2071 | preg_match($newline_before_re, $parsed) &&
2072 | preg_match($newline_after_re, $text) )
2073 | )
2074 | {
2075 | # Need to parse tag and following text using the HTML parser.
2076 | list($block_text, $text) =
2077 | $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true);
2078 |
2079 | # Make sure it stays outside of any paragraph by adding newlines.
2080 | $parsed .= "\n\n$block_text\n\n";
2081 | }
2082 | #
2083 | # Check for: Clean tag (like script, math)
2084 | # HTML Comments, processing instructions.
2085 | #
2086 | else if (preg_match('{^<(?:'.$this->clean_tags_re.')\b}', $tag) ||
2087 | $tag{1} == '!' || $tag{1} == '?')
2088 | {
2089 | # Need to parse tag and following text using the HTML parser.
2090 | # (don't check for markdown attribute)
2091 | list($block_text, $text) =
2092 | $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false);
2093 |
2094 | $parsed .= $block_text;
2095 | }
2096 | #
2097 | # Check for: Tag with same name as enclosing tag.
2098 | #
2099 | else if ($enclosing_tag_re !== '' &&
2100 | # Same name as enclosing tag.
2101 | preg_match('{^?(?:'.$enclosing_tag_re.')\b}', $tag))
2102 | {
2103 | #
2104 | # Increase/decrease nested tag count.
2105 | #
2106 | if ($tag{1} == '/') $depth--;
2107 | else if ($tag{strlen($tag)-2} != '/') $depth++;
2108 |
2109 | if ($depth < 0) {
2110 | #
2111 | # Going out of parent element. Clean up and break so we
2112 | # return to the calling function.
2113 | #
2114 | $text = $tag . $text;
2115 | break;
2116 | }
2117 |
2118 | $parsed .= $tag;
2119 | }
2120 | else {
2121 | $parsed .= $tag;
2122 | }
2123 | } while ($depth >= 0);
2124 |
2125 | return array($parsed, $text);
2126 | }
2127 | function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) {
2128 | #
2129 | # Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags.
2130 | #
2131 | # * Calls $hash_method to convert any blocks.
2132 | # * Stops when the first opening tag closes.
2133 | # * $md_attr indicate if the use of the `markdown="1"` attribute is allowed.
2134 | # (it is not inside clean tags)
2135 | #
2136 | # Returns an array of that form: ( processed text , remaining text )
2137 | #
2138 | if ($text === '') return array('', '');
2139 |
2140 | # Regex to match `markdown` attribute inside of a tag.
2141 | $markdown_attr_re = '
2142 | {
2143 | \s* # Eat whitespace before the `markdown` attribute
2144 | markdown
2145 | \s*=\s*
2146 | (?>
2147 | (["\']) # $1: quote delimiter
2148 | (.*?) # $2: attribute value
2149 | \1 # matching delimiter
2150 | |
2151 | ([^\s>]*) # $3: unquoted attribute value
2152 | )
2153 | () # $4: make $3 always defined (avoid warnings)
2154 | }xs';
2155 |
2156 | # Regex to match any tag.
2157 | $tag_re = '{
2158 | ( # $2: Capture whole tag.
2159 | ? # Any opening or closing tag.
2160 | [\w:$]+ # Tag name.
2161 | (?:
2162 | (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
2163 | (?>
2164 | ".*?" | # Double quotes (can contain `>`)
2165 | \'.*?\' | # Single quotes (can contain `>`)
2166 | .+? # Anything but quotes and `>`.
2167 | )*?
2168 | )?
2169 | > # End of tag.
2170 | |
2171 | # HTML Comment
2172 | |
2173 | <\?.*?\?> | <%.*?%> # Processing instruction
2174 | |
2175 | # CData Block
2176 | )
2177 | }xs';
2178 |
2179 | $original_text = $text; # Save original text in case of faliure.
2180 |
2181 | $depth = 0; # Current depth inside the tag tree.
2182 | $block_text = ""; # Temporary text holder for current text.
2183 | $parsed = ""; # Parsed text that will be returned.
2184 |
2185 | #
2186 | # Get the name of the starting tag.
2187 | # (This pattern makes $base_tag_name_re safe without quoting.)
2188 | #
2189 | if (preg_match('/^<([\w:$]*)\b/', $text, $matches))
2190 | $base_tag_name_re = $matches[1];
2191 |
2192 | #
2193 | # Loop through every tag until we find the corresponding closing tag.
2194 | #
2195 | do {
2196 | #
2197 | # Split the text using the first $tag_match pattern found.
2198 | # Text before pattern will be first in the array, text after
2199 | # pattern will be at the end, and between will be any catches made
2200 | # by the pattern.
2201 | #
2202 | $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
2203 |
2204 | if (count($parts) < 3) {
2205 | #
2206 | # End of $text reached with unbalenced tag(s).
2207 | # In that case, we return original text unchanged and pass the
2208 | # first character as filtered to prevent an infinite loop in the
2209 | # parent function.
2210 | #
2211 | return array($original_text{0}, substr($original_text, 1));
2212 | }
2213 |
2214 | $block_text .= $parts[0]; # Text before current tag.
2215 | $tag = $parts[1]; # Tag to handle.
2216 | $text = $parts[2]; # Remaining text after current tag.
2217 |
2218 | #
2219 | # Check for: Auto-close tag (like
)
2220 | # Comments and Processing Instructions.
2221 | #
2222 | if (preg_match('{^?(?:'.$this->auto_close_tags_re.')\b}', $tag) ||
2223 | $tag{1} == '!' || $tag{1} == '?')
2224 | {
2225 | # Just add the tag to the block as if it was text.
2226 | $block_text .= $tag;
2227 | }
2228 | else {
2229 | #
2230 | # Increase/decrease nested tag count. Only do so if
2231 | # the tag's name match base tag's.
2232 | #
2233 | if (preg_match('{^?'.$base_tag_name_re.'\b}', $tag)) {
2234 | if ($tag{1} == '/') $depth--;
2235 | else if ($tag{strlen($tag)-2} != '/') $depth++;
2236 | }
2237 |
2238 | #
2239 | # Check for `markdown="1"` attribute and handle it.
2240 | #
2241 | if ($md_attr &&
2242 | preg_match($markdown_attr_re, $tag, $attr_m) &&
2243 | preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3]))
2244 | {
2245 | # Remove `markdown` attribute from opening tag.
2246 | $tag = preg_replace($markdown_attr_re, '', $tag);
2247 |
2248 | # Check if text inside this tag must be parsed in span mode.
2249 | $this->mode = $attr_m[2] . $attr_m[3];
2250 | $span_mode = $this->mode == 'span' || $this->mode != 'block' &&
2251 | preg_match('{^<(?:'.$this->contain_span_tags_re.')\b}', $tag);
2252 |
2253 | # Calculate indent before tag.
2254 | if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) {
2255 | $strlen = $this->utf8_strlen;
2256 | $indent = $strlen($matches[1], 'UTF-8');
2257 | } else {
2258 | $indent = 0;
2259 | }
2260 |
2261 | # End preceding block with this tag.
2262 | $block_text .= $tag;
2263 | $parsed .= $this->$hash_method($block_text);
2264 |
2265 | # Get enclosing tag name for the ParseMarkdown function.
2266 | # (This pattern makes $tag_name_re safe without quoting.)
2267 | preg_match('/^<([\w:$]*)\b/', $tag, $matches);
2268 | $tag_name_re = $matches[1];
2269 |
2270 | # Parse the content using the HTML-in-Markdown parser.
2271 | list ($block_text, $text)
2272 | = $this->_hashHTMLBlocks_inMarkdown($text, $indent,
2273 | $tag_name_re, $span_mode);
2274 |
2275 | # Outdent markdown text.
2276 | if ($indent > 0) {
2277 | $block_text = preg_replace("/^[ ]{1,$indent}/m", "",
2278 | $block_text);
2279 | }
2280 |
2281 | # Append tag content to parsed text.
2282 | if (!$span_mode) $parsed .= "\n\n$block_text\n\n";
2283 | else $parsed .= "$block_text";
2284 |
2285 | # Start over with a new block.
2286 | $block_text = "";
2287 | }
2288 | else $block_text .= $tag;
2289 | }
2290 |
2291 | } while ($depth > 0);
2292 |
2293 | #
2294 | # Hash last block text that wasn't processed inside the loop.
2295 | #
2296 | $parsed .= $this->$hash_method($block_text);
2297 |
2298 | return array($parsed, $text);
2299 | }
2300 |
2301 |
2302 | function hashClean($text) {
2303 | #
2304 | # Called whenever a tag must be hashed when a function inserts a "clean" tag
2305 | # in $text, it passes through this function and is automaticaly escaped,
2306 | # blocking invalid nested overlap.
2307 | #
2308 | return $this->hashPart($text, 'C');
2309 | }
2310 |
2311 |
2312 | function doHeaders($text) {
2313 | #
2314 | # Redefined to add id and class attribute support.
2315 | #
2316 | # Setext-style headers:
2317 | # Header 1 {#header1}
2318 | # ========
2319 | #
2320 | # Header 2 {#header2 .class1 .class2}
2321 | # --------
2322 | #
2323 | $text = preg_replace_callback(
2324 | '{
2325 | (^.+?) # $1: Header text
2326 | (?:[ ]+ '.$this->id_class_attr_catch_re.' )? # $3 = id/class attributes
2327 | [ ]*\n(=+|-+)[ ]*\n+ # $3: Header footer
2328 | }mx',
2329 | array(&$this, '_doHeaders_callback_setext'), $text);
2330 |
2331 | # atx-style headers:
2332 | # # Header 1 {#header1}
2333 | # ## Header 2 {#header2}
2334 | # ## Header 2 with closing hashes ## {#header3.class1.class2}
2335 | # ...
2336 | # ###### Header 6 {.class2}
2337 | #
2338 | $text = preg_replace_callback('{
2339 | ^(\#{1,6}) # $1 = string of #\'s
2340 | [ ]*
2341 | (.+?) # $2 = Header text
2342 | [ ]*
2343 | \#* # optional closing #\'s (not counted)
2344 | (?:[ ]+ '.$this->id_class_attr_catch_re.' )? # $3 = id/class attributes
2345 | [ ]*
2346 | \n+
2347 | }xm',
2348 | array(&$this, '_doHeaders_callback_atx'), $text);
2349 |
2350 | return $text;
2351 | }
2352 | function _doHeaders_callback_setext($matches) {
2353 | if ($matches[3] == '-' && preg_match('{^- }', $matches[1]))
2354 | return $matches[0];
2355 | $level = $matches[3]{0} == '=' ? 1 : 2;
2356 | $attr = $this->doExtraAttributes("h$level", $dummy =& $matches[2]);
2357 | $block = "".$this->runSpanGamut($matches[1])." ";
2358 | return "\n" . $this->hashBlock($block) . "\n\n";
2359 | }
2360 | function _doHeaders_callback_atx($matches) {
2361 | $level = strlen($matches[1]);
2362 | $attr = $this->doExtraAttributes("h$level", $dummy =& $matches[3]);
2363 | $block = "".$this->runSpanGamut($matches[2])." ";
2364 | return "\n" . $this->hashBlock($block) . "\n\n";
2365 | }
2366 |
2367 |
2368 | function doTables($text) {
2369 | #
2370 | # Form HTML tables.
2371 | #
2372 | $less_than_tab = $this->tab_width - 1;
2373 | #
2374 | # Find tables with leading pipe.
2375 | #
2376 | # | Header 1 | Header 2
2377 | # | -------- | --------
2378 | # | Cell 1 | Cell 2
2379 | # | Cell 3 | Cell 4
2380 | #
2381 | $text = preg_replace_callback('
2382 | {
2383 | ^ # Start of a line
2384 | [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
2385 | [|] # Optional leading pipe (present)
2386 | (.+) \n # $1: Header row (at least one pipe)
2387 |
2388 | [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
2389 | [|] ([ ]*[-:]+[-| :]*) \n # $2: Header underline
2390 |
2391 | ( # $3: Cells
2392 | (?>
2393 | [ ]* # Allowed whitespace.
2394 | [|] .* \n # Row content.
2395 | )*
2396 | )
2397 | (?=\n|\Z) # Stop at final double newline.
2398 | }xm',
2399 | array(&$this, '_doTable_leadingPipe_callback'), $text);
2400 |
2401 | #
2402 | # Find tables without leading pipe.
2403 | #
2404 | # Header 1 | Header 2
2405 | # -------- | --------
2406 | # Cell 1 | Cell 2
2407 | # Cell 3 | Cell 4
2408 | #
2409 | $text = preg_replace_callback('
2410 | {
2411 | ^ # Start of a line
2412 | [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
2413 | (\S.*[|].*) \n # $1: Header row (at least one pipe)
2414 |
2415 | [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
2416 | ([-:]+[ ]*[|][-| :]*) \n # $2: Header underline
2417 |
2418 | ( # $3: Cells
2419 | (?>
2420 | .* [|] .* \n # Row content
2421 | )*
2422 | )
2423 | (?=\n|\Z) # Stop at final double newline.
2424 | }xm',
2425 | array(&$this, '_DoTable_callback'), $text);
2426 |
2427 | return $text;
2428 | }
2429 | function _doTable_leadingPipe_callback($matches) {
2430 | $head = $matches[1];
2431 | $underline = $matches[2];
2432 | $content = $matches[3];
2433 |
2434 | # Remove leading pipe for each row.
2435 | $content = preg_replace('/^ *[|]/m', '', $content);
2436 |
2437 | return $this->_doTable_callback(array($matches[0], $head, $underline, $content));
2438 | }
2439 | function _doTable_callback($matches) {
2440 | $head = $matches[1];
2441 | $underline = $matches[2];
2442 | $content = $matches[3];
2443 |
2444 | # Remove any tailing pipes for each line.
2445 | $head = preg_replace('/[|] *$/m', '', $head);
2446 | $underline = preg_replace('/[|] *$/m', '', $underline);
2447 | $content = preg_replace('/[|] *$/m', '', $content);
2448 |
2449 | # Reading alignement from header underline.
2450 | $separators = preg_split('/ *[|] */', $underline);
2451 | foreach ($separators as $n => $s) {
2452 | if (preg_match('/^ *-+: *$/', $s)) $attr[$n] = ' align="right"';
2453 | else if (preg_match('/^ *:-+: *$/', $s))$attr[$n] = ' align="center"';
2454 | else if (preg_match('/^ *:-+ *$/', $s)) $attr[$n] = ' align="left"';
2455 | else $attr[$n] = '';
2456 | }
2457 |
2458 | # Parsing span elements, including code spans, character escapes,
2459 | # and inline HTML tags, so that pipes inside those gets ignored.
2460 | $head = $this->parseSpan($head);
2461 | $headers = preg_split('/ *[|] */', $head);
2462 | $col_count = count($headers);
2463 |
2464 | # Write column headers.
2465 | $text = "\n";
2466 | $text .= "\n";
2467 | $text .= "\n";
2468 | foreach ($headers as $n => $header)
2469 | $text .= " ".$this->runSpanGamut(trim($header))." \n";
2470 | $text .= " \n";
2471 | $text .= "\n";
2472 |
2473 | # Split content by row.
2474 | $rows = explode("\n", trim($content, "\n"));
2475 |
2476 | $text .= "\n";
2477 | foreach ($rows as $row) {
2478 | # Parsing span elements, including code spans, character escapes,
2479 | # and inline HTML tags, so that pipes inside those gets ignored.
2480 | $row = $this->parseSpan($row);
2481 |
2482 | # Split row by cell.
2483 | $row_cells = preg_split('/ *[|] */', $row, $col_count);
2484 | $row_cells = array_pad($row_cells, $col_count, '');
2485 |
2486 | $text .= "\n";
2487 | foreach ($row_cells as $n => $cell)
2488 | $text .= " ".$this->runSpanGamut(trim($cell))." \n";
2489 | $text .= " \n";
2490 | }
2491 | $text .= "\n";
2492 | $text .= "
";
2493 |
2494 | return $this->hashBlock($text) . "\n";
2495 | }
2496 |
2497 |
2498 | function doDefLists($text) {
2499 | #
2500 | # Form HTML definition lists.
2501 | #
2502 | $less_than_tab = $this->tab_width - 1;
2503 |
2504 | # Re-usable pattern to match any entire dl list:
2505 | $whole_list_re = '(?>
2506 | ( # $1 = whole list
2507 | ( # $2
2508 | [ ]{0,'.$less_than_tab.'}
2509 | ((?>.*\S.*\n)+) # $3 = defined term
2510 | \n?
2511 | [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
2512 | )
2513 | (?s:.+?)
2514 | ( # $4
2515 | \z
2516 | |
2517 | \n{2,}
2518 | (?=\S)
2519 | (?! # Negative lookahead for another term
2520 | [ ]{0,'.$less_than_tab.'}
2521 | (?: \S.*\n )+? # defined term
2522 | \n?
2523 | [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
2524 | )
2525 | (?! # Negative lookahead for another definition
2526 | [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
2527 | )
2528 | )
2529 | )
2530 | )'; // mx
2531 |
2532 | $text = preg_replace_callback('{
2533 | (?>\A\n?|(?<=\n\n))
2534 | '.$whole_list_re.'
2535 | }mx',
2536 | array(&$this, '_doDefLists_callback'), $text);
2537 |
2538 | return $text;
2539 | }
2540 | function _doDefLists_callback($matches) {
2541 | # Re-usable patterns to match list item bullets and number markers:
2542 | $list = $matches[1];
2543 |
2544 | # Turn double returns into triple returns, so that we can make a
2545 | # paragraph for the last item in a list, if necessary:
2546 | $result = trim($this->processDefListItems($list));
2547 | $result = "\n" . $result . "\n
";
2548 | return $this->hashBlock($result) . "\n\n";
2549 | }
2550 |
2551 |
2552 | function processDefListItems($list_str) {
2553 | #
2554 | # Process the contents of a single definition list, splitting it
2555 | # into individual term and definition list items.
2556 | #
2557 | $less_than_tab = $this->tab_width - 1;
2558 |
2559 | # trim trailing blank lines:
2560 | $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
2561 |
2562 | # Process definition terms.
2563 | $list_str = preg_replace_callback('{
2564 | (?>\A\n?|\n\n+) # leading line
2565 | ( # definition terms = $1
2566 | [ ]{0,'.$less_than_tab.'} # leading whitespace
2567 | (?![:][ ]|[ ]) # negative lookahead for a definition
2568 | # mark (colon) or more whitespace.
2569 | (?> \S.* \n)+? # actual term (not whitespace).
2570 | )
2571 | (?=\n?[ ]{0,3}:[ ]) # lookahead for following line feed
2572 | # with a definition mark.
2573 | }xm',
2574 | array(&$this, '_processDefListItems_callback_dt'), $list_str);
2575 |
2576 | # Process actual definitions.
2577 | $list_str = preg_replace_callback('{
2578 | \n(\n+)? # leading line = $1
2579 | ( # marker space = $2
2580 | [ ]{0,'.$less_than_tab.'} # whitespace before colon
2581 | [:][ ]+ # definition mark (colon)
2582 | )
2583 | ((?s:.+?)) # definition text = $3
2584 | (?= \n+ # stop at next definition mark,
2585 | (?: # next term or end of text
2586 | [ ]{0,'.$less_than_tab.'} [:][ ] |
2587 | | \z
2588 | )
2589 | )
2590 | }xm',
2591 | array(&$this, '_processDefListItems_callback_dd'), $list_str);
2592 |
2593 | return $list_str;
2594 | }
2595 | function _processDefListItems_callback_dt($matches) {
2596 | $terms = explode("\n", trim($matches[1]));
2597 | $text = '';
2598 | foreach ($terms as $term) {
2599 | $term = $this->runSpanGamut(trim($term));
2600 | $text .= "\n" . $term . " ";
2601 | }
2602 | return $text . "\n";
2603 | }
2604 | function _processDefListItems_callback_dd($matches) {
2605 | $leading_line = $matches[1];
2606 | $marker_space = $matches[2];
2607 | $def = $matches[3];
2608 |
2609 | if ($leading_line || preg_match('/\n{2,}/', $def)) {
2610 | # Replace marker with the appropriate whitespace indentation
2611 | $def = str_repeat(' ', strlen($marker_space)) . $def;
2612 | $def = $this->runBlockGamut($this->outdent($def . "\n\n"));
2613 | $def = "\n". $def ."\n";
2614 | }
2615 | else {
2616 | $def = rtrim($def);
2617 | $def = $this->runSpanGamut($this->outdent($def));
2618 | }
2619 |
2620 | return "\n " . $def . " \n";
2621 | }
2622 |
2623 |
2624 | function doFencedCodeBlocks($text) {
2625 | #
2626 | # Adding the fenced code block syntax to regular Markdown:
2627 | #
2628 | # ~~~
2629 | # Code block
2630 | # ~~~
2631 | #
2632 | $less_than_tab = $this->tab_width;
2633 |
2634 | $text = preg_replace_callback('{
2635 | (?:\n|\A)
2636 | # 1: Opening marker
2637 | (
2638 | ~{3,} # Marker: three tilde or more.
2639 | )
2640 | [ ]*
2641 | (?:
2642 | [.]?([-_:a-zA-Z0-9]+) # 2: standalone class name
2643 | |
2644 | '.$this->id_class_attr_catch_re.' # 3: Extra attributes
2645 | )?
2646 | [ ]* \n # Whitespace and newline following marker.
2647 |
2648 | # 4: Content
2649 | (
2650 | (?>
2651 | (?!\1 [ ]* \n) # Not a closing marker.
2652 | .*\n+
2653 | )+
2654 | )
2655 |
2656 | # Closing marker.
2657 | \1 [ ]* \n
2658 | }xm',
2659 | array(&$this, '_doFencedCodeBlocks_callback'), $text);
2660 |
2661 | return $text;
2662 | }
2663 | function _doFencedCodeBlocks_callback($matches) {
2664 | $classname =& $matches[2];
2665 | $attrs =& $matches[3];
2666 | $codeblock = $matches[4];
2667 | $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
2668 | $codeblock = preg_replace_callback('/^\n+/',
2669 | array(&$this, '_doFencedCodeBlocks_newlines'), $codeblock);
2670 |
2671 | if ($classname != "") {
2672 | if ($classname{0} == '.')
2673 | $classname = substr($classname, 1);
2674 | $attr_str = ' class="'.$this->code_class_prefix.$classname.'"';
2675 | } else {
2676 | $attr_str = $this->doExtraAttributes($this->code_attr_on_pre ? "pre" : "code", $attrs);
2677 | }
2678 | $pre_attr_str = $this->code_attr_on_pre ? $attr_str : '';
2679 | $code_attr_str = $this->code_attr_on_pre ? '' : $attr_str;
2680 | $codeblock = "$codeblock
";
2681 |
2682 | return "\n\n".$this->hashBlock($codeblock)."\n\n";
2683 | }
2684 | function _doFencedCodeBlocks_newlines($matches) {
2685 | return str_repeat("
empty_element_suffix",
2686 | strlen($matches[0]));
2687 | }
2688 |
2689 |
2690 | #
2691 | # Redefining emphasis markers so that emphasis by underscore does not
2692 | # work in the middle of a word.
2693 | #
2694 | var $em_relist = array(
2695 | '' => '(?:(? '(?<=\S|^)(? '(?<=\S|^)(? '(?:(? '(?<=\S|^)(? '(?<=\S|^)(? '(?:(? '(?<=\S|^)(? '(?<=\S|^)(? tags
2715 | #
2716 | # Strip leading and trailing lines:
2717 | $text = preg_replace('/\A\n+|\n+\z/', '', $text);
2718 |
2719 | $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
2720 |
2721 | #
2722 | # Wrap tags and unhashify HTML blocks
2723 | #
2724 | foreach ($grafs as $key => $value) {
2725 | $value = trim($this->runSpanGamut($value));
2726 |
2727 | # Check if this should be enclosed in a paragraph.
2728 | # Clean tag hashes & block tag hashes are left alone.
2729 | $is_p = !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value);
2730 |
2731 | if ($is_p) {
2732 | $value = "
$value
";
2733 | }
2734 | $grafs[$key] = $value;
2735 | }
2736 |
2737 | # Join grafs in one text, then unhash HTML tags.
2738 | $text = implode("\n\n", $grafs);
2739 |
2740 | # Finish by removing any tag hashes still present in $text.
2741 | $text = $this->unhash($text);
2742 |
2743 | return $text;
2744 | }
2745 |
2746 |
2747 | ### Footnotes
2748 |
2749 | function stripFootnotes($text) {
2750 | #
2751 | # Strips link definitions from text, stores the URLs and titles in
2752 | # hash references.
2753 | #
2754 | $less_than_tab = $this->tab_width - 1;
2755 |
2756 | # Link defs are in the form: [^id]: url "optional title"
2757 | $text = preg_replace_callback('{
2758 | ^[ ]{0,'.$less_than_tab.'}\[\^(.+?)\][ ]?: # note_id = $1
2759 | [ ]*
2760 | \n? # maybe *one* newline
2761 | ( # text = $2 (no blank lines allowed)
2762 | (?:
2763 | .+ # actual text
2764 | |
2765 | \n # newlines but
2766 | (?!\[\^.+?\]:\s)# negative lookahead for footnote marker.
2767 | (?!\n+[ ]{0,3}\S)# ensure line is not blank and followed
2768 | # by non-indented content
2769 | )*
2770 | )
2771 | }xm',
2772 | array(&$this, '_stripFootnotes_callback'),
2773 | $text);
2774 | return $text;
2775 | }
2776 | function _stripFootnotes_callback($matches) {
2777 | $note_id = $this->fn_id_prefix . $matches[1];
2778 | $this->footnotes[$note_id] = $this->outdent($matches[2]);
2779 | return ''; # String that will replace the block
2780 | }
2781 |
2782 |
2783 | function doFootnotes($text) {
2784 | #
2785 | # Replace footnote references in $text [^id] with a special text-token
2786 | # which will be replaced by the actual footnote marker in appendFootnotes.
2787 | #
2788 | if (!$this->in_anchor) {
2789 | $text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text);
2790 | }
2791 | return $text;
2792 | }
2793 |
2794 |
2795 | function appendFootnotes($text) {
2796 | #
2797 | # Append footnote list to text.
2798 | #
2799 | $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
2800 | array(&$this, '_appendFootnotes_callback'), $text);
2801 |
2802 | if (!empty($this->footnotes_ordered)) {
2803 | $text .= "\n\n";
2804 | $text .= "\n";
2805 | $text .= "
empty_element_suffix ."\n";
2806 | $text .= "\n\n";
2807 |
2808 | $attr = " rev=\"footnote\"";
2809 | if ($this->fn_backlink_class != "") {
2810 | $class = $this->fn_backlink_class;
2811 | $class = $this->encodeAttribute($class);
2812 | $attr .= " class=\"$class\"";
2813 | }
2814 | if ($this->fn_backlink_title != "") {
2815 | $title = $this->fn_backlink_title;
2816 | $title = $this->encodeAttribute($title);
2817 | $attr .= " title=\"$title\"";
2818 | }
2819 | $num = 0;
2820 |
2821 | while (!empty($this->footnotes_ordered)) {
2822 | $footnote = reset($this->footnotes_ordered);
2823 | $note_id = key($this->footnotes_ordered);
2824 | unset($this->footnotes_ordered[$note_id]);
2825 | $ref_count = $this->footnotes_ref_count[$note_id];
2826 | unset($this->footnotes_ref_count[$note_id]);
2827 | unset($this->footnotes[$note_id]);
2828 |
2829 | $footnote .= "\n"; # Need to append newline before parsing.
2830 | $footnote = $this->runBlockGamut("$footnote\n");
2831 | $footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
2832 | array(&$this, '_appendFootnotes_callback'), $footnote);
2833 |
2834 | $attr = str_replace("%%", ++$num, $attr);
2835 | $note_id = $this->encodeAttribute($note_id);
2836 |
2837 | # Prepare backlink, multiple backlinks if multiple references
2838 | $backlink = "↩";
2839 | for ($ref_num = 2; $ref_num <= $ref_count; ++$ref_num) {
2840 | $backlink .= " ↩";
2841 | }
2842 | # Add backlink to last paragraph; create new paragraph if needed.
2843 | if (preg_match('{$}', $footnote)) {
2844 | $footnote = substr($footnote, 0, -4) . " $backlink";
2845 | } else {
2846 | $footnote .= "\n\n$backlink
";
2847 | }
2848 |
2849 | $text .= "- \n";
2850 | $text .= $footnote . "\n";
2851 | $text .= "
\n\n";
2852 | }
2853 |
2854 | $text .= "
\n";
2855 | $text .= "";
2856 | }
2857 | return $text;
2858 | }
2859 | function _appendFootnotes_callback($matches) {
2860 | $node_id = $this->fn_id_prefix . $matches[1];
2861 |
2862 | # Create footnote marker only if it has a corresponding footnote *and*
2863 | # the footnote hasn't been used by another marker.
2864 | if (isset($this->footnotes[$node_id])) {
2865 | $num =& $this->footnotes_numbers[$node_id];
2866 | if (!isset($num)) {
2867 | # Transfer footnote content to the ordered list and give it its
2868 | # number
2869 | $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id];
2870 | $this->footnotes_ref_count[$node_id] = 1;
2871 | $num = $this->footnote_counter++;
2872 | $ref_count_mark = '';
2873 | } else {
2874 | $ref_count_mark = $this->footnotes_ref_count[$node_id] += 1;
2875 | }
2876 |
2877 | $attr = " rel=\"footnote\"";
2878 | if ($this->fn_link_class != "") {
2879 | $class = $this->fn_link_class;
2880 | $class = $this->encodeAttribute($class);
2881 | $attr .= " class=\"$class\"";
2882 | }
2883 | if ($this->fn_link_title != "") {
2884 | $title = $this->fn_link_title;
2885 | $title = $this->encodeAttribute($title);
2886 | $attr .= " title=\"$title\"";
2887 | }
2888 |
2889 | $attr = str_replace("%%", $num, $attr);
2890 | $node_id = $this->encodeAttribute($node_id);
2891 |
2892 | return
2893 | "".
2894 | "$num".
2895 | "";
2896 | }
2897 |
2898 | return "[^".$matches[1]."]";
2899 | }
2900 |
2901 |
2902 | ### Abbreviations ###
2903 |
2904 | function stripAbbreviations($text) {
2905 | #
2906 | # Strips abbreviations from text, stores titles in hash references.
2907 | #
2908 | $less_than_tab = $this->tab_width - 1;
2909 |
2910 | # Link defs are in the form: [id]*: url "optional title"
2911 | $text = preg_replace_callback('{
2912 | ^[ ]{0,'.$less_than_tab.'}\*\[(.+?)\][ ]?: # abbr_id = $1
2913 | (.*) # text = $2 (no blank lines allowed)
2914 | }xm',
2915 | array(&$this, '_stripAbbreviations_callback'),
2916 | $text);
2917 | return $text;
2918 | }
2919 | function _stripAbbreviations_callback($matches) {
2920 | $abbr_word = $matches[1];
2921 | $abbr_desc = $matches[2];
2922 | if ($this->abbr_word_re)
2923 | $this->abbr_word_re .= '|';
2924 | $this->abbr_word_re .= preg_quote($abbr_word);
2925 | $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
2926 | return ''; # String that will replace the block
2927 | }
2928 |
2929 |
2930 | function doAbbreviations($text) {
2931 | #
2932 | # Find defined abbreviations in text and wrap them in elements.
2933 | #
2934 | if ($this->abbr_word_re) {
2935 | // cannot use the /x modifier because abbr_word_re may
2936 | // contain significant spaces:
2937 | $text = preg_replace_callback('{'.
2938 | '(?abbr_word_re.')'.
2940 | '(?![\w\x1A])'.
2941 | '}',
2942 | array(&$this, '_doAbbreviations_callback'), $text);
2943 | }
2944 | return $text;
2945 | }
2946 | function _doAbbreviations_callback($matches) {
2947 | $abbr = $matches[0];
2948 | if (isset($this->abbr_desciptions[$abbr])) {
2949 | $desc = $this->abbr_desciptions[$abbr];
2950 | if (empty($desc)) {
2951 | return $this->hashPart("$abbr");
2952 | } else {
2953 | $desc = $this->encodeAttribute($desc);
2954 | return $this->hashPart("$abbr");
2955 | }
2956 | } else {
2957 | return $matches[0];
2958 | }
2959 | }
2960 |
2961 | }
2962 |
2963 |
2964 | /*
2965 |
2966 | PHP Markdown Extra
2967 | ==================
2968 |
2969 | Description
2970 | -----------
2971 |
2972 | This is a PHP port of the original Markdown formatter written in Perl
2973 | by John Gruber. This special "Extra" version of PHP Markdown features
2974 | further enhancements to the syntax for making additional constructs
2975 | such as tables and definition list.
2976 |
2977 | Markdown is a text-to-HTML filter; it translates an easy-to-read /
2978 | easy-to-write structured text format into HTML. Markdown's text format
2979 | is mostly similar to that of plain text email, and supports features such
2980 | as headers, *emphasis*, code blocks, blockquotes, and links.
2981 |
2982 | Markdown's syntax is designed not as a generic markup language, but
2983 | specifically to serve as a front-end to (X)HTML. You can use span-level
2984 | HTML tags anywhere in a Markdown document, and you can use block level
2985 | HTML tags (like and as well).
2986 |
2987 | For more information about Markdown's syntax, see:
2988 |
2989 |
2990 |
2991 |
2992 | Bugs
2993 | ----
2994 |
2995 | To file bug reports please send email to:
2996 |
2997 |
2998 |
2999 | Please include with your report: (1) the example input; (2) the output you
3000 | expected; (3) the output Markdown actually produced.
3001 |
3002 |
3003 | Version History
3004 | ---------------
3005 |
3006 | See the readme file for detailed release notes for this version.
3007 |
3008 |
3009 | Copyright and License
3010 | ---------------------
3011 |
3012 | PHP Markdown & Extra
3013 | Copyright (c) 2004-2013 Michel Fortin
3014 |
3015 | All rights reserved.
3016 |
3017 | Based on Markdown
3018 | Copyright (c) 2003-2006 John Gruber
3019 |
3020 | All rights reserved.
3021 |
3022 | Redistribution and use in source and binary forms, with or without
3023 | modification, are permitted provided that the following conditions are
3024 | met:
3025 |
3026 | * Redistributions of source code must retain the above copyright notice,
3027 | this list of conditions and the following disclaimer.
3028 |
3029 | * Redistributions in binary form must reproduce the above copyright
3030 | notice, this list of conditions and the following disclaimer in the
3031 | documentation and/or other materials provided with the distribution.
3032 |
3033 | * Neither the name "Markdown" nor the names of its contributors may
3034 | be used to endorse or promote products derived from this software
3035 | without specific prior written permission.
3036 |
3037 | This software is provided by the copyright holders and contributors "as
3038 | is" and any express or implied warranties, including, but not limited
3039 | to, the implied warranties of merchantability and fitness for a
3040 | particular purpose are disclaimed. In no event shall the copyright owner
3041 | or contributors be liable for any direct, indirect, incidental, special,
3042 | exemplary, or consequential damages (including, but not limited to,
3043 | procurement of substitute goods or services; loss of use, data, or
3044 | profits; or business interruption) however caused and on any theory of
3045 | liability, whether in contract, strict liability, or tort (including
3046 | negligence or otherwise) arising in any way out of the use of this
3047 | software, even if advised of the possibility of such damage.
3048 |
3049 | */
3050 |
--------------------------------------------------------------------------------