├── 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 | Extract Plugin Meta 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 |
13 | 24 |
25 | 31 | 32 |
33 | 34 |
35 | 36 |
37 | 38 |
39 | 40 |
41 | $sectionContent) { 44 | printf( 45 | "

%s

\n%s\n", 46 | ucwords(str_replace('_', ' ', $sectionHeader)), 47 | $sectionContent 48 | ); 49 | } 50 | } else { 51 | ?> 52 | No sections found in readme.txt 53 | 56 |
57 | 58 |
59 | $sectionContent) { 62 | printf( 63 | "

%s

", 64 | ucwords(str_replace('_', ' ', $sectionHeader)), 65 | htmlentities($sectionContent) 66 | ); 67 | } 68 | } else { 69 | ?> 70 | No sections found in readme.txt 71 | 74 |
75 |
76 | 77 | 82 | 83 | 92 | 93 | -------------------------------------------------------------------------------- /demo/style.css: -------------------------------------------------------------------------------- 1 | .ui-tabs-nav { 2 | margin: 0; 3 | padding: 0 0 0.2em 0; 4 | } 5 | 6 | .ui-tabs-nav li { 7 | display: inline-block; 8 | } 9 | 10 | .ui-tabs-nav li a { 11 | display: inline-block; 12 | padding: 0.5em; 13 | border: 1px solid #bbb; 14 | font-weight: bold; 15 | color: #bbb; 16 | background: #f5f5f5; 17 | text-decoration: none; 18 | 19 | border-radius: 5px; 20 | -moz-border-radius: 5px; 21 | text-shadow: #ffffff 1px 1px 1px; 22 | } 23 | 24 | .ui-tabs-nav .ui-state-hover a { 25 | color: #888; 26 | } 27 | 28 | .ui-tabs-nav .ui-tabs-selected a { 29 | color: black; 30 | background: white; 31 | } 32 | 33 | .ui-tabs-hide { 34 | display: none; 35 | } 36 | 37 | textarea { 38 | width: 70em; 39 | height: 30em; 40 | } -------------------------------------------------------------------------------- /extension-meta.php: -------------------------------------------------------------------------------- 1 | open($packageFilename) !== true ){ 34 | return false; 35 | } 36 | 37 | //Find and parse the plugin or theme file and (optionally) readme.txt. 38 | $header = null; 39 | $readme = null; 40 | $pluginFile = null; 41 | $stylesheet = null; 42 | $type = null; 43 | 44 | for ( $fileIndex = 0; ($fileIndex < $zip->numFiles) && (empty($readme) || empty($header)); $fileIndex++ ){ 45 | $info = $zip->statIndex($fileIndex); 46 | 47 | //Normalize filename: convert backslashes to slashes, remove leading slashes. 48 | $fileName = trim(str_replace('\\', '/', $info['name']), '/'); 49 | $fileName = ltrim($fileName, '/'); 50 | 51 | $parts = explode('.', $fileName); 52 | $extension = strtolower(end($parts)); 53 | $depth = substr_count($fileName, '/'); 54 | 55 | //Skip empty files, directories and everything that's more than 1 sub-directory deep. 56 | if ( ($depth > 1) || ($info['size'] == 0) ) { 57 | continue; 58 | } 59 | 60 | //readme.txt (for plugins)? 61 | if ( empty($readme) && (strtolower(basename($fileName)) == 'readme.txt') ){ 62 | //Try to parse the readme. 63 | $readme = self::parseReadme($zip->getFromIndex($fileIndex), $applyMarkdown); 64 | } 65 | 66 | //Theme stylesheet? 67 | if ( empty($header) && (strtolower(basename($fileName)) == 'style.css') ) { 68 | $fileContents = substr($zip->getFromIndex($fileIndex), 0, 8*1024); 69 | $header = self::getThemeHeaders($fileContents); 70 | if ( !empty($header) ){ 71 | $stylesheet = $fileName; 72 | $type = 'theme'; 73 | } 74 | } 75 | 76 | //Main plugin file? 77 | if ( empty($header) && ($extension === 'php') ){ 78 | $fileContents = substr($zip->getFromIndex($fileIndex), 0, 8*1024); 79 | $header = self::getPluginHeaders($fileContents); 80 | if ( !empty($header) ){ 81 | $pluginFile = $fileName; 82 | $type = 'plugin'; 83 | } 84 | } 85 | } 86 | 87 | if ( empty($type) ){ 88 | return false; 89 | } else { 90 | return compact('header', 'readme', 'pluginFile', 'stylesheet', 'type'); 91 | } 92 | } 93 | 94 | /** 95 | * Parse a plugin's readme.txt to extract various plugin metadata. 96 | * 97 | * Returns an array with the following fields: 98 | * 'name' - Name of the plugin. 99 | * 'contributors' - An array of wordpress.org usernames. 100 | * 'donate' - The plugin's donation link. 101 | * 'tags' - An array of the plugin's tags. 102 | * 'requires' - The minimum version of WordPress that the plugin will run on. 103 | * 'tested' - The latest version of WordPress that the plugin has been tested on. 104 | * 'stable' - The SVN tag of the latest stable release, or 'trunk'. 105 | * 'short_description' - The plugin's "short description". 106 | * 'sections' - An associative array of sections present in the readme.txt. 107 | * Case and formatting of section headers will be preserved. 108 | * 109 | * Be warned that this function does *not* perfectly emulate the way that WordPress.org 110 | * parses plugin readme's. In particular, it may mangle certain HTML markup that wp.org 111 | * handles correctly. 112 | * 113 | * @see http://wordpress.org/extend/plugins/about/readme.txt 114 | * 115 | * @param string $readmeTxtContents The contents of a plugin's readme.txt file. 116 | * @param bool $applyMarkdown Whether to transform Markdown used in readme.txt sections to HTML. Defaults to false. 117 | * @return array|null Associative array, or NULL if the input isn't a valid readme.txt file. 118 | */ 119 | public static function parseReadme($readmeTxtContents, $applyMarkdown = false){ 120 | $readmeTxtContents = trim($readmeTxtContents, " \t\n\r"); 121 | $readme = array( 122 | 'name' => '', 123 | 'contributors' => array(), 124 | 'donate' => '', 125 | 'tags' => array(), 126 | 'requires' => '', 127 | 'tested' => '', 128 | 'stable' => '', 129 | 'short_description' => '', 130 | 'sections' => array(), 131 | ); 132 | 133 | //The readme.txt header has a fairly fixed structure, so we can parse it line-by-line 134 | $lines = explode("\n", $readmeTxtContents); 135 | //Plugin name is at the very top, e.g. === My Plugin === 136 | if ( preg_match('@===\s*(.+?)\s*===@', array_shift($lines), $matches) ){ 137 | $readme['name'] = $matches[1]; 138 | } else { 139 | return null; 140 | } 141 | 142 | //Then there's a bunch of meta fields formatted as "Field: value" 143 | $headers = array(); 144 | $headerMap = array( 145 | 'Contributors' => 'contributors', 146 | 'Donate link' => 'donate', 147 | 'Tags' => 'tags', 148 | 'Requires at least' => 'requires', 149 | 'Tested up to' => 'tested', 150 | 'Stable tag' => 'stable', 151 | ); 152 | do { //Parse each readme.txt header 153 | $pieces = explode(':', array_shift($lines), 2); 154 | if ( array_key_exists($pieces[0], $headerMap) ){ 155 | if ( isset($pieces[1]) ){ 156 | $headers[ $headerMap[$pieces[0]] ] = trim($pieces[1]); 157 | } else { 158 | $headers[ $headerMap[$pieces[0]] ] = ''; 159 | } 160 | } 161 | } while ( trim($pieces[0]) != '' ); //Until an empty line is encountered 162 | 163 | //"Contributors" is a comma-separated list. Convert it to an array. 164 | if ( !empty($headers['contributors']) ){ 165 | $headers['contributors'] = array_map('trim', explode(',', $headers['contributors'])); 166 | } 167 | 168 | //Likewise for "Tags" 169 | if ( !empty($headers['tags']) ){ 170 | $headers['tags'] = array_map('trim', explode(',', $headers['tags'])); 171 | } 172 | 173 | $readme = array_merge($readme, $headers); 174 | 175 | //After the headers comes the short description 176 | $readme['short_description'] = array_shift($lines); 177 | 178 | //Finally, a valid readme.txt also contains one or more "sections" identified by "== Section Name ==" 179 | $sections = array(); 180 | $contentBuffer = array(); 181 | $currentSection = ''; 182 | foreach($lines as $line){ 183 | //Is this a section header? 184 | if ( preg_match('@^\s*==\s+(.+?)\s+==\s*$@m', $line, $matches) ){ 185 | //Flush the content buffer for the previous section, if any 186 | if ( !empty($currentSection) ){ 187 | $sectionContent = trim(implode("\n", $contentBuffer)); 188 | $sections[$currentSection] = $sectionContent; 189 | } 190 | //Start reading a new section 191 | $currentSection = $matches[1]; 192 | $contentBuffer = array(); 193 | } else { 194 | //Buffer all section content 195 | $contentBuffer[] = $line; 196 | } 197 | } 198 | //Flush the buffer for the last section 199 | if ( !empty($currentSection) ){ 200 | $sections[$currentSection] = trim(implode("\n", $contentBuffer)); 201 | } 202 | 203 | //Apply Markdown to sections 204 | if ( $applyMarkdown ){ 205 | $sections = array_map(__CLASS__ . '::applyMarkdown', $sections); 206 | } 207 | 208 | //This is only necessary if you intend to later json_encode() the sections. 209 | //json_encode() may encode certain strings as NULL if they're not in UTF-8. 210 | $sections = array_map('utf8_encode', $sections); 211 | 212 | $readme['sections'] = $sections; 213 | 214 | return $readme; 215 | } 216 | 217 | /** @noinspection PhpUnusedPrivateMethodInspection Actually used in parseReadme(). */ 218 | /** 219 | * Transform Markdown markup to HTML. 220 | * 221 | * Tries (in vain) to emulate the transformation that WordPress.org applies to readme.txt files. 222 | * 223 | * @param string $text 224 | * @return string 225 | */ 226 | private static function applyMarkdown($text){ 227 | //The WP standard for readme files uses some custom markup, like "= H4 headers =" 228 | $text = preg_replace('@^\s*=\s*(.+?)\s*=\s*$@m', "

$1

\n", $text); 229 | return Markdown($text); 230 | } 231 | 232 | /** 233 | * Parse the plugin contents to retrieve plugin's metadata headers. 234 | * 235 | * Adapted from the get_plugin_data() function used by WordPress. 236 | * Returns an array that contains the following: 237 | * 'Name' - Name of the plugin. 238 | * 'Title' - Title of the plugin and the link to the plugin's web site. 239 | * 'Description' - Description of what the plugin does and/or notes from the author. 240 | * 'Author' - The author's name. 241 | * 'AuthorURI' - The author's web site address. 242 | * 'Version' - The plugin version number. 243 | * 'PluginURI' - Plugin web site address. 244 | * 'TextDomain' - Plugin's text domain for localization. 245 | * 'DomainPath' - Plugin's relative directory path to .mo files. 246 | * 'Network' - Boolean. Whether the plugin can only be activated network wide. 247 | * 248 | * If the input string doesn't appear to contain a valid plugin header, the function 249 | * will return NULL. 250 | * 251 | * @param string $fileContents Contents of the plugin file 252 | * @return array|null See above for description. 253 | */ 254 | public static function getPluginHeaders($fileContents) { 255 | //[Internal name => Name used in the plugin file] 256 | $pluginHeaderNames = array( 257 | 'Name' => 'Plugin Name', 258 | 'PluginURI' => 'Plugin URI', 259 | 'Version' => 'Version', 260 | 'Description' => 'Description', 261 | 'Author' => 'Author', 262 | 'AuthorURI' => 'Author URI', 263 | 'TextDomain' => 'Text Domain', 264 | 'DomainPath' => 'Domain Path', 265 | 'Network' => 'Network', 266 | //Site Wide Only is deprecated in favor of Network. 267 | '_sitewide' => 'Site Wide Only', 268 | ); 269 | 270 | $headers = self::getFileHeaders($fileContents, $pluginHeaderNames); 271 | 272 | //Site Wide Only is the old header for Network. 273 | if ( empty($headers['Network']) && !empty($headers['_sitewide']) ) { 274 | $headers['Network'] = $headers['_sitewide']; 275 | } 276 | unset($headers['_sitewide']); 277 | $headers['Network'] = (strtolower($headers['Network']) === 'true'); 278 | 279 | //For backward compatibility by default Title is the same as Name. 280 | $headers['Title'] = $headers['Name']; 281 | 282 | //If it doesn't have a name, it's probably not a plugin. 283 | if ( empty($headers['Name']) ){ 284 | return null; 285 | } else { 286 | return $headers; 287 | } 288 | } 289 | 290 | /** 291 | * Parse the theme stylesheet to retrieve its metadata headers. 292 | * 293 | * Adapted from the get_theme_data() function and the WP_Theme class in WordPress. 294 | * Returns an array that contains the following: 295 | * 'Name' - Name of the theme. 296 | * 'Description' - Theme description. 297 | * 'Author' - The author's name 298 | * 'AuthorURI' - The authors web site address. 299 | * 'Version' - The theme version number. 300 | * 'ThemeURI' - Theme web site address. 301 | * 'Template' - The slug of the parent theme. Only applies to child themes. 302 | * 'Status' - Unknown. Included for completeness. 303 | * 'Tags' - An array of tags. 304 | * 'TextDomain' - Theme's text domain for localization. 305 | * 'DomainPath' - Theme's relative directory path to .mo files. 306 | * 307 | * If the input string doesn't appear to contain a valid theme header, the function 308 | * will return NULL. 309 | * 310 | * @param string $fileContents Contents of the theme stylesheet. 311 | * @return array|null See above for description. 312 | */ 313 | public static function getThemeHeaders($fileContents) { 314 | $themeHeaderNames = array( 315 | 'Name' => 'Theme Name', 316 | 'ThemeURI' => 'Theme URI', 317 | 'Description' => 'Description', 318 | 'Author' => 'Author', 319 | 'AuthorURI' => 'Author URI', 320 | 'Version' => 'Version', 321 | 'Template' => 'Template', 322 | 'Status' => 'Status', 323 | 'Tags' => 'Tags', 324 | 'TextDomain' => 'Text Domain', 325 | 'DomainPath' => 'Domain Path', 326 | 'DetailsURI' => 'Details URI', 327 | ); 328 | $headers = self::getFileHeaders($fileContents, $themeHeaderNames); 329 | 330 | $headers['Tags'] = array_filter(array_map('trim', explode(',', strip_tags( $headers['Tags'])))); 331 | 332 | //If it doesn't have a name, it's probably not a valid theme. 333 | if ( empty($headers['Name']) ){ 334 | return null; 335 | } else { 336 | return $headers; 337 | } 338 | } 339 | 340 | /** 341 | * Parse the file contents to retrieve its metadata. 342 | * 343 | * Searches for metadata for a file, such as a plugin or theme. Each piece of 344 | * metadata must be on its own line. For a field spanning multiple lines, it 345 | * must not have any newlines or only parts of it will be displayed. 346 | * 347 | * @param string $fileContents File contents. Can be safely truncated to 8kiB as that's all WP itself scans. 348 | * @param array $headerMap The list of headers to search for in the file. 349 | * @return array 350 | */ 351 | public static function getFileHeaders($fileContents, $headerMap ) { 352 | $headers = array(); 353 | 354 | //Support systems that use CR as a line ending. 355 | $fileContents = str_replace("\r", "\n", $fileContents); 356 | 357 | foreach ($headerMap as $field => $prettyName) { 358 | $found = preg_match('/^[ \t\/*#@]*' . preg_quote($prettyName, '/') . ':(.*)$/mi', $fileContents, $matches); 359 | if ( ($found > 0) && !empty($matches[1]) ) { 360 | //Strip comment markers and closing PHP tags. 361 | $value = trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $matches[1])); 362 | $headers[$field] = $value; 363 | } else { 364 | $headers[$field] = ''; 365 | } 366 | } 367 | 368 | return $headers; 369 | } 370 | } 371 | 372 | /** 373 | * Extract plugin metadata from a plugin's ZIP file and transform it into a structure 374 | * compatible with the custom update checker. 375 | * 376 | * Deprecated. Included for backwards-compatibility. 377 | * 378 | * This is an utility function that scans the input file (assumed to be a ZIP archive) 379 | * to find and parse the plugin's main PHP file and readme.txt file. Plugin metadata from 380 | * both files is assembled into an associative array. The structure if this array is 381 | * compatible with the format of the metadata file used by the custom plugin update checker 382 | * library available at the below URL. 383 | * 384 | * @see http://w-shadow.com/blog/2010/09/02/automatic-updates-for-any-plugin/ 385 | * @see https://spreadsheets.google.com/pub?key=0AqP80E74YcUWdEdETXZLcXhjd2w0cHMwX2U1eDlWTHc&authkey=CK7h9toK&hl=en&single=true&gid=0&output=html 386 | * 387 | * Requires the ZIP extension for PHP. 388 | * @see http://php.net/manual/en/book.zip.php 389 | * 390 | * @param string|array $packageInfo Either path to a ZIP file containing a WP plugin, or the return value of analysePluginPackage(). 391 | * @return array Associative array 392 | */ 393 | function getPluginPackageMeta($packageInfo){ 394 | if ( is_string($packageInfo) && file_exists($packageInfo) ){ 395 | $packageInfo = WshWordPressPackageParser::parsePackage($packageInfo, true); 396 | } 397 | 398 | $meta = array(); 399 | 400 | if ( isset($packageInfo['header']) && !empty($packageInfo['header']) ){ 401 | $mapping = array( 402 | 'Name' => 'name', 403 | 'Version' => 'version', 404 | 'PluginURI' => 'homepage', 405 | 'Author' => 'author', 406 | 'AuthorURI' => 'author_homepage', 407 | ); 408 | foreach($mapping as $headerField => $metaField){ 409 | if ( array_key_exists($headerField, $packageInfo['header']) && !empty($packageInfo['header'][$headerField]) ){ 410 | $meta[$metaField] = $packageInfo['header'][$headerField]; 411 | } 412 | } 413 | } 414 | 415 | if ( !empty($packageInfo['readme']) ){ 416 | $mapping = array('requires', 'tested'); 417 | foreach($mapping as $readmeField){ 418 | if ( !empty($packageInfo['readme'][$readmeField]) ){ 419 | $meta[$readmeField] = $packageInfo['readme'][$readmeField]; 420 | } 421 | } 422 | if ( !empty($packageInfo['readme']['sections']) && is_array($packageInfo['readme']['sections']) ){ 423 | foreach($packageInfo['readme']['sections'] as $sectionName => $sectionContent){ 424 | $sectionName = str_replace(' ', '_', strtolower($sectionName)); 425 | $meta['sections'][$sectionName] = $sectionContent; 426 | } 427 | } 428 | 429 | //Check if we have an upgrade notice for this version 430 | if ( isset($meta['sections']['upgrade_notice']) && isset($meta['version']) ){ 431 | $regex = "@

\s*" . preg_quote($meta['version']) . "\s*

[^<>]*?

(.+?)

@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 | # 12 | # 13 | 14 | 15 | define( 'MARKDOWN_VERSION', "1.0.1p" ); # Sun 13 Jan 2013 16 | define( 'MARKDOWNEXTRA_VERSION', "1.2.6" ); # Sun 13 Jan 2013 17 | 18 | 19 | # 20 | # Global default settings: 21 | # 22 | 23 | # Change to ">" for HTML output 24 | @define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX', " />"); 25 | 26 | # Define the width of a tab for code blocks. 27 | @define( 'MARKDOWN_TAB_WIDTH', 4 ); 28 | 29 | # Optional title attribute for footnote links and backlinks. 30 | @define( 'MARKDOWN_FN_LINK_TITLE', "" ); 31 | @define( 'MARKDOWN_FN_BACKLINK_TITLE', "" ); 32 | 33 | # Optional class attribute for footnote links and backlinks. 34 | @define( 'MARKDOWN_FN_LINK_CLASS', "" ); 35 | @define( 'MARKDOWN_FN_BACKLINK_CLASS', "" ); 36 | 37 | # Optional class prefix for fenced code block. 38 | @define( 'MARKDOWN_CODE_CLASS_PREFIX', "" ); 39 | 40 | # Class attribute for code blocks goes on the `code` tag; 41 | # setting this to true will put attributes on the `pre` tag instead. 42 | @define( 'MARKDOWN_CODE_ATTR_ON_PRE', false ); 43 | 44 | 45 | # 46 | # WordPress settings: 47 | # 48 | 49 | # Change to false to remove Markdown from posts and/or comments. 50 | @define( 'MARKDOWN_WP_POSTS', true ); 51 | @define( 'MARKDOWN_WP_COMMENTS', true ); 52 | 53 | 54 | 55 | ### Standard Function Interface ### 56 | 57 | @define( 'MARKDOWN_PARSER_CLASS', 'MarkdownExtra_Parser' ); 58 | 59 | function Markdown($text) { 60 | # 61 | # Initialize the parser and return the result of its transform method. 62 | # 63 | # Setup static parser variable. 64 | static $parser; 65 | if (!isset($parser)) { 66 | $parser_class = MARKDOWN_PARSER_CLASS; 67 | $parser = new $parser_class; 68 | } 69 | 70 | # Transform text using parser. 71 | return $parser->transform($text); 72 | } 73 | 74 | 75 | ### WordPress Plugin Interface ### 76 | 77 | /* 78 | Plugin Name: Markdown Extra 79 | Plugin Name: Markdown 80 | Plugin URI: http://michelf.ca/projects/php-markdown/ 81 | Description: 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... 82 | Version: 1.2.6 83 | Author: Michel Fortin 84 | Author URI: http://michelf.ca/ 85 | */ 86 | 87 | if (isset($wp_version)) { 88 | # More details about how it works here: 89 | # 90 | 91 | # Post content and excerpts 92 | # - Remove WordPress paragraph generator. 93 | # - Run Markdown on excerpt, then remove all tags. 94 | # - Add paragraph tag around the excerpt, but remove it for the excerpt rss. 95 | if (MARKDOWN_WP_POSTS) { 96 | remove_filter('the_content', 'wpautop'); 97 | remove_filter('the_content_rss', 'wpautop'); 98 | remove_filter('the_excerpt', 'wpautop'); 99 | add_filter('the_content', 'mdwp_MarkdownPost', 6); 100 | add_filter('the_content_rss', 'mdwp_MarkdownPost', 6); 101 | add_filter('get_the_excerpt', 'mdwp_MarkdownPost', 6); 102 | add_filter('get_the_excerpt', 'trim', 7); 103 | add_filter('the_excerpt', 'mdwp_add_p'); 104 | add_filter('the_excerpt_rss', 'mdwp_strip_p'); 105 | 106 | remove_filter('content_save_pre', 'balanceTags', 50); 107 | remove_filter('excerpt_save_pre', 'balanceTags', 50); 108 | add_filter('the_content', 'balanceTags', 50); 109 | add_filter('get_the_excerpt', 'balanceTags', 9); 110 | } 111 | 112 | # Add a footnote id prefix to posts when inside a loop. 113 | function mdwp_MarkdownPost($text) { 114 | static $parser; 115 | if (!$parser) { 116 | $parser_class = MARKDOWN_PARSER_CLASS; 117 | $parser = new $parser_class; 118 | } 119 | if (is_single() || is_page() || is_feed()) { 120 | $parser->fn_id_prefix = ""; 121 | } else { 122 | $parser->fn_id_prefix = get_the_ID() . "."; 123 | } 124 | return $parser->transform($text); 125 | } 126 | 127 | # Comments 128 | # - Remove WordPress paragraph generator. 129 | # - Remove WordPress auto-link generator. 130 | # - Scramble important tags before passing them to the kses filter. 131 | # - Run Markdown on excerpt then remove paragraph tags. 132 | if (MARKDOWN_WP_COMMENTS) { 133 | remove_filter('comment_text', 'wpautop', 30); 134 | remove_filter('comment_text', 'make_clickable'); 135 | add_filter('pre_comment_content', 'Markdown', 6); 136 | add_filter('pre_comment_content', 'mdwp_hide_tags', 8); 137 | add_filter('pre_comment_content', 'mdwp_show_tags', 12); 138 | add_filter('get_comment_text', 'Markdown', 6); 139 | add_filter('get_comment_excerpt', 'Markdown', 6); 140 | add_filter('get_comment_excerpt', 'mdwp_strip_p', 7); 141 | 142 | global $mdwp_hidden_tags, $mdwp_placeholders; 143 | $mdwp_hidden_tags = explode(' ', 144 | '

 
  • '); 145 | $mdwp_placeholders = explode(' ', str_rot13( 146 | 'pEj07ZbbBZ U1kqgh4w4p pre2zmeN6K QTi31t9pre ol0MP1jzJR '. 147 | 'ML5IjmbRol ulANi1NsGY J7zRLJqPul liA8ctl16T K9nhooUHli')); 148 | } 149 | 150 | function mdwp_add_p($text) { 151 | if (!preg_match('{^$|^<(p|ul|ol|dl|pre|blockquote)>}i', $text)) { 152 | $text = '

    '.$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('{}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 | # 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 | #

    466 | #
    467 | # tags for inner block must be indented. 468 | #
    469 | #
    470 | # 471 | # The outermost tags must start at the left margin for this to match, and 472 | # the inner nested divs must be indented. 473 | # We need to do this before the next, more liberal match, because the next 474 | # match will start at the first `
    ` and stop at the first `
    `. 475 | $text = preg_replace_callback('{(?> 476 | (?> 477 | (?<=\n\n) # Starting after a blank line 478 | | # or 479 | \A\n? # the beginning of the doc 480 | ) 481 | ( # save in $1 482 | 483 | # Match from `\n` to `\n`, handling nested tags 484 | # in between. 485 | 486 | [ ]{0,'.$less_than_tab.'} 487 | <('.$block_tags_b_re.')# start tag = $2 488 | '.$attr.'> # attributes followed by > and \n 489 | '.$content.' # content, support nesting 490 | # the matching end tag 491 | [ ]* # trailing spaces/tabs 492 | (?=\n+|\Z) # followed by a newline or end of document 493 | 494 | | # Special version for tags of group a. 495 | 496 | [ ]{0,'.$less_than_tab.'} 497 | <('.$block_tags_a_re.')# start tag = $3 498 | '.$attr.'>[ ]*\n # attributes followed by > 499 | '.$content2.' # content, support nesting 500 | # the matching end tag 501 | [ ]* # trailing spaces/tabs 502 | (?=\n+|\Z) # followed by a newline or end of document 503 | 504 | | # Special case just for
    . It was easier to make a special 505 | # case than to make the other regex more complicated. 506 | 507 | [ ]{0,'.$less_than_tab.'} 508 | <(hr) # start tag = $2 509 | '.$attr.' # attributes 510 | /?> # the matching end tag 511 | [ ]* 512 | (?=\n{2,}|\Z) # followed by a blank line or end of document 513 | 514 | | # Special case for standalone HTML comments: 515 | 516 | [ ]{0,'.$less_than_tab.'} 517 | (?s: 518 | 519 | ) 520 | [ ]* 521 | (?=\n{2,}|\Z) # followed by a blank line or end of document 522 | 523 | | # PHP and ASP-style processor instructions ( 530 | ) 531 | [ ]* 532 | (?=\n{2,}|\Z) # followed by a blank line or end of document 533 | 534 | ) 535 | )}Sxmi', 536 | array(&$this, '_hashHTMLBlocks_callback'), 537 | $text); 538 | 539 | return $text; 540 | } 541 | function _hashHTMLBlocks_callback($matches) { 542 | $text = $matches[1]; 543 | $key = $this->hashBlock($text); 544 | return "\n\n$key\n\n"; 545 | } 546 | 547 | 548 | function hashPart($text, $boundary = 'X') { 549 | # 550 | # Called whenever a tag must be hashed when a function insert an atomic 551 | # element in the text stream. Passing $text to through this function gives 552 | # a unique text-token which will be reverted back when calling unhash. 553 | # 554 | # The $boundary argument specify what character should be used to surround 555 | # the token. By convension, "B" is used for block elements that needs not 556 | # to be wrapped into paragraph tags at the end, ":" is used for elements 557 | # that are word separators and "X" is used in the general case. 558 | # 559 | # Swap back any tag hash found in $text so we do not have to `unhash` 560 | # multiple times at the end. 561 | $text = $this->unhash($text); 562 | 563 | # Then hash the block. 564 | static $i = 0; 565 | $key = "$boundary\x1A" . ++$i . $boundary; 566 | $this->html_hashes[$key] = $text; 567 | return $key; # String that will replace the tag. 568 | } 569 | 570 | 571 | function hashBlock($text) { 572 | # 573 | # Shortcut function for hashPart with block-level boundaries. 574 | # 575 | return $this->hashPart($text, 'B'); 576 | } 577 | 578 | 579 | var $block_gamut = array( 580 | # 581 | # These are all the transformations that form block-level 582 | # tags like paragraphs, headers, and list items. 583 | # 584 | "doHeaders" => 10, 585 | "doHorizontalRules" => 20, 586 | 587 | "doLists" => 40, 588 | "doCodeBlocks" => 50, 589 | "doBlockQuotes" => 60, 590 | ); 591 | 592 | function runBlockGamut($text) { 593 | # 594 | # Run block gamut tranformations. 595 | # 596 | # We need to escape raw HTML in Markdown source before doing anything 597 | # else. This need to be done for each block, and not only at the 598 | # begining in the Markdown function since hashed blocks can be part of 599 | # list items and could have been indented. Indented blocks would have 600 | # been seen as a code block in a previous pass of hashHTMLBlocks. 601 | $text = $this->hashHTMLBlocks($text); 602 | 603 | return $this->runBasicBlockGamut($text); 604 | } 605 | 606 | function runBasicBlockGamut($text) { 607 | # 608 | # Run block gamut tranformations, without hashing HTML blocks. This is 609 | # useful when HTML blocks are known to be already hashed, like in the first 610 | # whole-document pass. 611 | # 612 | foreach ($this->block_gamut as $method => $priority) { 613 | $text = $this->$method($text); 614 | } 615 | 616 | # Finally form paragraph and restore hashed blocks. 617 | $text = $this->formParagraphs($text); 618 | 619 | return $text; 620 | } 621 | 622 | 623 | function doHorizontalRules($text) { 624 | # Do Horizontal Rules: 625 | return preg_replace( 626 | '{ 627 | ^[ ]{0,3} # Leading space 628 | ([-*_]) # $1: First marker 629 | (?> # Repeated marker group 630 | [ ]{0,2} # Zero, one, or two spaces. 631 | \1 # Marker character 632 | ){2,} # Group repeated at least twice 633 | [ ]* # Tailing spaces 634 | $ # End of line. 635 | }mx', 636 | "\n".$this->hashBlock("empty_element_suffix")."\n", 637 | $text); 638 | } 639 | 640 | 641 | var $span_gamut = array( 642 | # 643 | # These are all the transformations that occur *within* block-level 644 | # tags like paragraphs, headers, and list items. 645 | # 646 | # Process character escapes, code spans, and inline HTML 647 | # in one shot. 648 | "parseSpan" => -30, 649 | 650 | # Process anchor and image tags. Images must come first, 651 | # because ![foo][f] looks like an anchor. 652 | "doImages" => 10, 653 | "doAnchors" => 20, 654 | 655 | # Make links out of things like `` 656 | # Must come after doAnchors, because you can use < and > 657 | # delimiters in inline links like [this](). 658 | "doAutoLinks" => 30, 659 | "encodeAmpsAndAngles" => 40, 660 | 661 | "doItalicsAndBold" => 50, 662 | "doHardBreaks" => 60, 663 | ); 664 | 665 | function runSpanGamut($text) { 666 | # 667 | # Run span gamut tranformations. 668 | # 669 | foreach ($this->span_gamut as $method => $priority) { 670 | $text = $this->$method($text); 671 | } 672 | 673 | return $text; 674 | } 675 | 676 | 677 | function doHardBreaks($text) { 678 | # Do hard breaks: 679 | return preg_replace_callback('/ {2,}\n/', 680 | array(&$this, '_doHardBreaks_callback'), $text); 681 | } 682 | function _doHardBreaks_callback($matches) { 683 | return $this->hashPart("empty_element_suffix\n"); 684 | } 685 | 686 | 687 | function doAnchors($text) { 688 | # 689 | # Turn Markdown link shortcuts into XHTML tags. 690 | # 691 | if ($this->in_anchor) return $text; 692 | $this->in_anchor = true; 693 | 694 | # 695 | # First, handle reference-style links: [link text] [id] 696 | # 697 | $text = preg_replace_callback('{ 698 | ( # wrap whole match in $1 699 | \[ 700 | ('.$this->nested_brackets_re.') # link text = $2 701 | \] 702 | 703 | [ ]? # one optional space 704 | (?:\n[ ]*)? # one optional newline followed by spaces 705 | 706 | \[ 707 | (.*?) # id = $3 708 | \] 709 | ) 710 | }xs', 711 | array(&$this, '_doAnchors_reference_callback'), $text); 712 | 713 | # 714 | # Next, inline-style links: [link text](url "optional title") 715 | # 716 | $text = preg_replace_callback('{ 717 | ( # wrap whole match in $1 718 | \[ 719 | ('.$this->nested_brackets_re.') # link text = $2 720 | \] 721 | \( # literal paren 722 | [ \n]* 723 | (?: 724 | <(.+?)> # href = $3 725 | | 726 | ('.$this->nested_url_parenthesis_re.') # href = $4 727 | ) 728 | [ \n]* 729 | ( # $5 730 | ([\'"]) # quote char = $6 731 | (.*?) # Title = $7 732 | \6 # matching quote 733 | [ \n]* # ignore any spaces/tabs between closing quote and ) 734 | )? # title is optional 735 | \) 736 | ) 737 | }xs', 738 | array(&$this, '_doAnchors_inline_callback'), $text); 739 | 740 | # 741 | # Last, handle reference-style shortcuts: [link text] 742 | # These must come last in case you've also got [link text][1] 743 | # or [link text](/foo) 744 | # 745 | $text = preg_replace_callback('{ 746 | ( # wrap whole match in $1 747 | \[ 748 | ([^\[\]]+) # link text = $2; can\'t contain [ or ] 749 | \] 750 | ) 751 | }xs', 752 | array(&$this, '_doAnchors_reference_callback'), $text); 753 | 754 | $this->in_anchor = false; 755 | return $text; 756 | } 757 | function _doAnchors_reference_callback($matches) { 758 | $whole_match = $matches[1]; 759 | $link_text = $matches[2]; 760 | $link_id =& $matches[3]; 761 | 762 | if ($link_id == "") { 763 | # for shortcut links like [this][] or [this]. 764 | $link_id = $link_text; 765 | } 766 | 767 | # lower-case and turn embedded newlines into spaces 768 | $link_id = strtolower($link_id); 769 | $link_id = preg_replace('{[ ]?\n}', ' ', $link_id); 770 | 771 | if (isset($this->urls[$link_id])) { 772 | $url = $this->urls[$link_id]; 773 | $url = $this->encodeAttribute($url); 774 | 775 | $result = "titles[$link_id] ) ) { 777 | $title = $this->titles[$link_id]; 778 | $title = $this->encodeAttribute($title); 779 | $result .= " title=\"$title\""; 780 | } 781 | 782 | $link_text = $this->runSpanGamut($link_text); 783 | $result .= ">$link_text"; 784 | $result = $this->hashPart($result); 785 | } 786 | else { 787 | $result = $whole_match; 788 | } 789 | return $result; 790 | } 791 | function _doAnchors_inline_callback($matches) { 792 | $whole_match = $matches[1]; 793 | $link_text = $this->runSpanGamut($matches[2]); 794 | $url = $matches[3] == '' ? $matches[4] : $matches[3]; 795 | $title =& $matches[7]; 796 | 797 | $url = $this->encodeAttribute($url); 798 | 799 | $result = "encodeAttribute($title); 802 | $result .= " title=\"$title\""; 803 | } 804 | 805 | $link_text = $this->runSpanGamut($link_text); 806 | $result .= ">$link_text"; 807 | 808 | return $this->hashPart($result); 809 | } 810 | 811 | 812 | function doImages($text) { 813 | # 814 | # Turn Markdown image shortcuts into tags. 815 | # 816 | # 817 | # First, handle reference-style labeled images: ![alt text][id] 818 | # 819 | $text = preg_replace_callback('{ 820 | ( # wrap whole match in $1 821 | !\[ 822 | ('.$this->nested_brackets_re.') # alt text = $2 823 | \] 824 | 825 | [ ]? # one optional space 826 | (?:\n[ ]*)? # one optional newline followed by spaces 827 | 828 | \[ 829 | (.*?) # id = $3 830 | \] 831 | 832 | ) 833 | }xs', 834 | array(&$this, '_doImages_reference_callback'), $text); 835 | 836 | # 837 | # Next, handle inline images: ![alt text](url "optional title") 838 | # Don't forget: encode * and _ 839 | # 840 | $text = preg_replace_callback('{ 841 | ( # wrap whole match in $1 842 | !\[ 843 | ('.$this->nested_brackets_re.') # alt text = $2 844 | \] 845 | \s? # One optional whitespace character 846 | \( # literal paren 847 | [ \n]* 848 | (?: 849 | <(\S*)> # src url = $3 850 | | 851 | ('.$this->nested_url_parenthesis_re.') # src url = $4 852 | ) 853 | [ \n]* 854 | ( # $5 855 | ([\'"]) # quote char = $6 856 | (.*?) # title = $7 857 | \6 # matching quote 858 | [ \n]* 859 | )? # title is optional 860 | \) 861 | ) 862 | }xs', 863 | array(&$this, '_doImages_inline_callback'), $text); 864 | 865 | return $text; 866 | } 867 | function _doImages_reference_callback($matches) { 868 | $whole_match = $matches[1]; 869 | $alt_text = $matches[2]; 870 | $link_id = strtolower($matches[3]); 871 | 872 | if ($link_id == "") { 873 | $link_id = strtolower($alt_text); # for shortcut links like ![this][]. 874 | } 875 | 876 | $alt_text = $this->encodeAttribute($alt_text); 877 | if (isset($this->urls[$link_id])) { 878 | $url = $this->encodeAttribute($this->urls[$link_id]); 879 | $result = "\"$alt_text\"";titles[$link_id])) { 881 | $title = $this->titles[$link_id]; 882 | $title = $this->encodeAttribute($title); 883 | $result .= " title=\"$title\""; 884 | } 885 | $result .= $this->empty_element_suffix; 886 | $result = $this->hashPart($result); 887 | } 888 | else { 889 | # If there's no such link ID, leave intact: 890 | $result = $whole_match; 891 | } 892 | 893 | return $result; 894 | } 895 | function _doImages_inline_callback($matches) { 896 | $whole_match = $matches[1]; 897 | $alt_text = $matches[2]; 898 | $url = $matches[3] == '' ? $matches[4] : $matches[3]; 899 | $title =& $matches[7]; 900 | 901 | $alt_text = $this->encodeAttribute($alt_text); 902 | $url = $this->encodeAttribute($url); 903 | $result = "\"$alt_text\"";encodeAttribute($title); 906 | $result .= " title=\"$title\""; # $title already quoted 907 | } 908 | $result .= $this->empty_element_suffix; 909 | 910 | return $this->hashPart($result); 911 | } 912 | 913 | 914 | function doHeaders($text) { 915 | # Setext-style headers: 916 | # Header 1 917 | # ======== 918 | # 919 | # Header 2 920 | # -------- 921 | # 922 | $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx', 923 | array(&$this, '_doHeaders_callback_setext'), $text); 924 | 925 | # atx-style headers: 926 | # # Header 1 927 | # ## Header 2 928 | # ## Header 2 with closing hashes ## 929 | # ... 930 | # ###### Header 6 931 | # 932 | $text = preg_replace_callback('{ 933 | ^(\#{1,6}) # $1 = string of #\'s 934 | [ ]* 935 | (.+?) # $2 = Header text 936 | [ ]* 937 | \#* # optional closing #\'s (not counted) 938 | \n+ 939 | }xm', 940 | array(&$this, '_doHeaders_callback_atx'), $text); 941 | 942 | return $text; 943 | } 944 | function _doHeaders_callback_setext($matches) { 945 | # Terrible hack to check we haven't found an empty list item. 946 | if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1])) 947 | return $matches[0]; 948 | 949 | $level = $matches[2]{0} == '=' ? 1 : 2; 950 | $block = "".$this->runSpanGamut($matches[1]).""; 951 | return "\n" . $this->hashBlock($block) . "\n\n"; 952 | } 953 | function _doHeaders_callback_atx($matches) { 954 | $level = strlen($matches[1]); 955 | $block = "".$this->runSpanGamut($matches[2]).""; 956 | return "\n" . $this->hashBlock($block) . "\n\n"; 957 | } 958 | 959 | 960 | function doLists($text) { 961 | # 962 | # Form HTML ordered (numbered) and unordered (bulleted) lists. 963 | # 964 | $less_than_tab = $this->tab_width - 1; 965 | 966 | # Re-usable patterns to match list item bullets and number markers: 967 | $marker_ul_re = '[*+-]'; 968 | $marker_ol_re = '\d+[\.]'; 969 | $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; 970 | 971 | $markers_relist = array( 972 | $marker_ul_re => $marker_ol_re, 973 | $marker_ol_re => $marker_ul_re, 974 | ); 975 | 976 | foreach ($markers_relist as $marker_re => $other_marker_re) { 977 | # Re-usable pattern to match any entirel ul or ol list: 978 | $whole_list_re = ' 979 | ( # $1 = whole list 980 | ( # $2 981 | ([ ]{0,'.$less_than_tab.'}) # $3 = number of spaces 982 | ('.$marker_re.') # $4 = first list item marker 983 | [ ]+ 984 | ) 985 | (?s:.+?) 986 | ( # $5 987 | \z 988 | | 989 | \n{2,} 990 | (?=\S) 991 | (?! # Negative lookahead for another list item marker 992 | [ ]* 993 | '.$marker_re.'[ ]+ 994 | ) 995 | | 996 | (?= # Lookahead for another kind of list 997 | \n 998 | \3 # Must have the same indentation 999 | '.$other_marker_re.'[ ]+ 1000 | ) 1001 | ) 1002 | ) 1003 | '; // mx 1004 | 1005 | # We use a different prefix before nested lists than top-level lists. 1006 | # See extended comment in _ProcessListItems(). 1007 | 1008 | if ($this->list_level) { 1009 | $text = preg_replace_callback('{ 1010 | ^ 1011 | '.$whole_list_re.' 1012 | }mx', 1013 | array(&$this, '_doLists_callback'), $text); 1014 | } 1015 | else { 1016 | $text = preg_replace_callback('{ 1017 | (?:(?<=\n)\n|\A\n?) # Must eat the newline 1018 | '.$whole_list_re.' 1019 | }mx', 1020 | array(&$this, '_doLists_callback'), $text); 1021 | } 1022 | } 1023 | 1024 | return $text; 1025 | } 1026 | function _doLists_callback($matches) { 1027 | # Re-usable patterns to match list item bullets and number markers: 1028 | $marker_ul_re = '[*+-]'; 1029 | $marker_ol_re = '\d+[\.]'; 1030 | $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; 1031 | 1032 | $list = $matches[1]; 1033 | $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol"; 1034 | 1035 | $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re ); 1036 | 1037 | $list .= "\n"; 1038 | $result = $this->processListItems($list, $marker_any_re); 1039 | 1040 | $result = $this->hashBlock("<$list_type>\n" . $result . ""); 1041 | return "\n". $result ."\n\n"; 1042 | } 1043 | 1044 | var $list_level = 0; 1045 | 1046 | function processListItems($list_str, $marker_any_re) { 1047 | # 1048 | # Process the contents of a single ordered or unordered list, splitting it 1049 | # into individual list items. 1050 | # 1051 | # The $this->list_level global keeps track of when we're inside a list. 1052 | # Each time we enter a list, we increment it; when we leave a list, 1053 | # we decrement. If it's zero, we're not in a list anymore. 1054 | # 1055 | # We do this because when we're not inside a list, we want to treat 1056 | # something like this: 1057 | # 1058 | # I recommend upgrading to version 1059 | # 8. Oops, now this line is treated 1060 | # as a sub-list. 1061 | # 1062 | # As a single paragraph, despite the fact that the second line starts 1063 | # with a digit-period-space sequence. 1064 | # 1065 | # Whereas when we're inside a list (or sub-list), that line will be 1066 | # treated as the start of a sub-list. What a kludge, huh? This is 1067 | # an aspect of Markdown's syntax that's hard to parse perfectly 1068 | # without resorting to mind-reading. Perhaps the solution is to 1069 | # change the syntax rules such that sub-lists must start with a 1070 | # starting cardinal number; e.g. "1." or "a.". 1071 | 1072 | $this->list_level++; 1073 | 1074 | # trim trailing blank lines: 1075 | $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str); 1076 | 1077 | $list_str = preg_replace_callback('{ 1078 | (\n)? # leading line = $1 1079 | (^[ ]*) # leading whitespace = $2 1080 | ('.$marker_any_re.' # list marker and space = $3 1081 | (?:[ ]+|(?=\n)) # space only required if item is not empty 1082 | ) 1083 | ((?s:.*?)) # list item text = $4 1084 | (?:(\n+(?=\n))|\n) # tailing blank line = $5 1085 | (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n)))) 1086 | }xm', 1087 | array(&$this, '_processListItems_callback'), $list_str); 1088 | 1089 | $this->list_level--; 1090 | return $list_str; 1091 | } 1092 | function _processListItems_callback($matches) { 1093 | $item = $matches[4]; 1094 | $leading_line =& $matches[1]; 1095 | $leading_space =& $matches[2]; 1096 | $marker_space = $matches[3]; 1097 | $tailing_blank_line =& $matches[5]; 1098 | 1099 | if ($leading_line || $tailing_blank_line || 1100 | preg_match('/\n{2,}/', $item)) 1101 | { 1102 | # Replace marker with the appropriate whitespace indentation 1103 | $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item; 1104 | $item = $this->runBlockGamut($this->outdent($item)."\n"); 1105 | } 1106 | else { 1107 | # Recursion for sub-lists: 1108 | $item = $this->doLists($this->outdent($item)); 1109 | $item = preg_replace('/\n+$/', '', $item); 1110 | $item = $this->runSpanGamut($item); 1111 | } 1112 | 1113 | return "
  • " . $item . "
  • \n"; 1114 | } 1115 | 1116 | 1117 | function doCodeBlocks($text) { 1118 | # 1119 | # Process Markdown `
    ` 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"; 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"; 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 | #

    foo@exampl 1508 | # e.com

    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] = '&#x'.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 | # 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 | # 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('{^= 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 | 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('{^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('{^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 .= "
    1. \n"; 2850 | $text .= $footnote . "\n"; 2851 | $text .= "
    2. \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 | --------------------------------------------------------------------------------