├── plugins ├── index.html ├── helloworld │ └── helloworld.php └── cimarkdown │ ├── cimarkdown.php │ └── markdown.php ├── plugins.sql ├── README.md └── application └── libraries └── Plugins.php /plugins/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 403 Forbidden 4 | 5 | 6 | 7 |

Directory access is forbidden.

8 | 9 | 10 | -------------------------------------------------------------------------------- /plugins/helloworld/helloworld.php: -------------------------------------------------------------------------------- 1 |
"; 18 | } 19 | 20 | function helloworld_install() 21 | { 22 | // Install logic is run when plugin is installed 23 | return true; 24 | } 25 | 26 | function helloworld_activate() 27 | { 28 | // When plugin is activated 29 | return true; 30 | } 31 | 32 | function helloworld_deactivate() 33 | { 34 | // when plugin is deactivated 35 | return true; 36 | } 37 | 38 | -------------------------------------------------------------------------------- /plugins/cimarkdown/cimarkdown.php: -------------------------------------------------------------------------------- 1 | _ci =& get_instance(); 61 | 62 | $this->_ci->load->database(); 63 | $this->_ci->load->helper('directory'); 64 | $this->_ci->load->helper('file'); 65 | $this->_ci->load->helper('url'); 66 | 67 | // Set the plugins directory if passed via paramater 68 | if (array_key_exists('plugins_dir', $params)) 69 | { 70 | $this->set_plugin_dir($params['plugins_dir']); 71 | } 72 | else // else set to default value 73 | { 74 | $basepath = str_replace("\\", "/", FCPATH); 75 | $this->set_plugin_dir($basepath . "plugins/"); 76 | } 77 | 78 | // Remove index.php string on the plugins directory if any 79 | $this->plugins_dir = str_replace("index.php", "", $this->plugins_dir); 80 | 81 | // Find all plugins 82 | $this->find_plugins(); 83 | 84 | // Get all activated plugins 85 | $this->get_activated_plugins(); 86 | 87 | // Include plugins 88 | $this->include_plugins(); 89 | 90 | self::$messages = ""; // Clear messages 91 | self::$errors = ""; // Clear errors 92 | } 93 | 94 | /** 95 | * Set Plugin Dir 96 | * Set the location of where all of the plugins are located 97 | * 98 | * @param mixed $directory 99 | */ 100 | public function set_plugin_dir($directory) 101 | { 102 | if (!empty($directory)) 103 | { 104 | $this->plugins_dir = trim($directory); 105 | } 106 | } 107 | 108 | /** 109 | * Instance 110 | * The instance of this plugin class 111 | * 112 | */ 113 | public static function instance() 114 | { 115 | if (!self::$instance) 116 | { 117 | self::$instance = new Plugins(); 118 | } 119 | 120 | return self::$instance; 121 | } 122 | 123 | 124 | /** 125 | * Find Plugins 126 | * 127 | * Find plugins in the plugins directory. 128 | * 129 | */ 130 | public function find_plugins() 131 | { 132 | $plugins = directory_map($this->plugins_dir, 1); // Find plugins 133 | 134 | if ($plugins != false) 135 | { 136 | foreach ($plugins AS $key => $name) 137 | { 138 | $name = strtolower(trim($name)); 139 | 140 | // If the plugin hasn't already been added and isn't a file 141 | if (!isset(self::$plugins_pool[$name]) AND !stripos($name, ".")) 142 | { 143 | // Make sure a valid plugin file by the same name as the folder exists 144 | if (file_exists($this->plugins_dir.$name."/".$name.".php")) 145 | { 146 | // Register the plugin 147 | self::$plugins_pool[$name]['plugin'] = $name; 148 | } 149 | else 150 | { 151 | self::$errors[$name][] = "Plugin file ".$name.".php does not exist."; 152 | } 153 | } 154 | } 155 | } 156 | } 157 | 158 | 159 | /** 160 | * Get Activated Plugins 161 | * Get all activated plugins from the database 162 | * 163 | */ 164 | public function get_activated_plugins() 165 | { 166 | // Only plugins in the database are active ones 167 | $plugins = $this->_ci->db->get('plugins'); 168 | 169 | // If we have activated plugins 170 | if ($plugins->num_rows() > 0) 171 | { 172 | // For every plugin, store it 173 | foreach ($plugins->result_array() AS $plugin) 174 | { 175 | $this->get_plugin_headers($plugin['plugin_system_name']); 176 | self::$plugins_active[$plugin['plugin_system_name']] = $plugin['plugin_system_name']; 177 | } 178 | } 179 | else 180 | { 181 | return true; 182 | } 183 | } 184 | 185 | /** 186 | * Include Plugins 187 | * Include all active plugins that are in the database 188 | * 189 | */ 190 | public function include_plugins() 191 | { 192 | if(self::$plugins_active AND !empty(self::$plugins_active)) 193 | { 194 | // Validate and include our found plugins 195 | foreach (self::$plugins_active AS $name => $value) 196 | { 197 | // The plugin information being added to the database 198 | $data = array( 199 | "plugin_system_name" => $name, 200 | "plugin_name" => trim(self::$plugins_pool[$name]['plugin_info']['plugin_name']), 201 | "plugin_uri" => trim(self::$plugins_pool[$name]['plugin_info']['plugin_uri']), 202 | "plugin_version" => trim(self::$plugins_pool[$name]['plugin_info']['plugin_version']), 203 | "plugin_description" => trim(self::$plugins_pool[$name]['plugin_info']['plugin_description']), 204 | "plugin_author" => trim(self::$plugins_pool[$name]['plugin_info']['plugin_author']), 205 | "plugin_author_uri" => trim(self::$plugins_pool[$name]['plugin_info']['plugin_author_uri']) 206 | ); 207 | $this->_ci->db->where('plugin_system_name', $name)->update('plugins', $data); 208 | 209 | // If the file was included 210 | include_once $this->plugins_dir.$name."/".$name.".php"; 211 | 212 | // Run the install action for this plugin 213 | self::do_action('install_' . $name); 214 | } 215 | } 216 | } 217 | 218 | 219 | /** 220 | * Get Plugin Headers 221 | * 222 | * Get the header information from all plugins in 223 | * the plugins pool for use later on. 224 | * 225 | * @param mixed $plugin 226 | */ 227 | public function get_plugin_headers($plugin) 228 | { 229 | if (self::$plugins_pool !== false AND !empty(self::$plugins_pool)) 230 | { 231 | $plugin = strtolower(trim($plugin)); // Lowercase and trim the plugin name 232 | 233 | $plugin_data = read_file($this->plugins_dir.$plugin."/".$plugin.".php"); // Load the plugin we want 234 | 235 | preg_match ('|Plugin Name:(.*)$|mi', $plugin_data, $name); 236 | preg_match ('|Plugin URI:(.*)$|mi', $plugin_data, $uri); 237 | preg_match ('|Version:(.*)|i', $plugin_data, $version); 238 | preg_match ('|Description:(.*)$|mi', $plugin_data, $description); 239 | preg_match ('|Author:(.*)$|mi', $plugin_data, $author_name); 240 | preg_match ('|Author URI:(.*)$|mi', $plugin_data, $author_uri); 241 | 242 | if (isset($name[1])) 243 | { 244 | $arr['plugin_name'] = trim($name[1]); 245 | } 246 | 247 | if (isset($uri[1])) 248 | { 249 | 250 | $arr['plugin_uri'] = trim($uri[1]); 251 | } 252 | 253 | if (isset($version[1])) 254 | { 255 | $arr['plugin_version'] = trim($version[1]); 256 | } 257 | 258 | if (isset($description[1])) 259 | { 260 | $arr['plugin_description'] = trim($description[1]); 261 | } 262 | 263 | if (isset($author_name[1])) 264 | { 265 | $arr['plugin_author'] = trim($author_name[1]); 266 | } 267 | 268 | if (isset($author_uri[1])) 269 | { 270 | $arr['plugin_author_uri'] = trim($author_uri[1]); 271 | } 272 | 273 | // For every plugin header item 274 | foreach ($arr AS $k => $v) 275 | { 276 | // If the key doesn't exist or the value is not the same, update the array 277 | if (!isset(self::$plugins_pool[$plugin]['plugin_info'][$k]) OR self::$plugins_pool[$plugin]['plugin_info'][$k] != $v) 278 | { 279 | self::$plugins_pool[$plugin]['plugin_info'][$k] = trim($v); 280 | } 281 | else 282 | { 283 | return true; 284 | } 285 | } 286 | } 287 | } 288 | 289 | /** 290 | * Activate Plugin 291 | * 292 | * Activates a plugin only if it exists in the 293 | * plugins_pool. After activating, reload page 294 | * to get the newly activated plugin 295 | * 296 | * @param mixed $name 297 | */ 298 | public function activate_plugin($name) 299 | { 300 | $name = strtolower(trim($name)); // Make sure the name is lowercase and no spaces 301 | 302 | // Okay the plugin exists, push it to the activated array 303 | if (isset(self::$plugins_pool[$name]) AND !isset(self::$plugins_active[$name])) 304 | { 305 | $db = $this->_ci->db->select('plugin_system_name')->where('plugin_system_name', $name)->get('plugins', 1); 306 | 307 | if ($db->num_rows() == 0) 308 | { 309 | $this->_ci->db->insert('plugins', array('plugin_system_name' => $name)); 310 | } 311 | 312 | // Run the activate hook 313 | self::do_action('activate_' . $name); 314 | } 315 | } 316 | 317 | /** 318 | * Deactivate Plugin 319 | * 320 | * Deactivates a plugin 321 | * 322 | * @param string $name 323 | */ 324 | public function deactivate_plugin($name) 325 | { 326 | $name = strtolower(trim($name)); // Make sure the name is lowercase and no spaces 327 | 328 | // Okay the plugin exists 329 | if (isset(self::$plugins_active[$name])) 330 | { 331 | $this->_ci->db->where('plugin_system_name', $name)->delete('plugins'); 332 | self::$messages[] = "Plugin ".self::$plugins_pool[$name]['plugin_info']['plugin_name']." has been deactivated!"; 333 | 334 | // Deactivate hook 335 | self::do_action('deactivate_' . $name); 336 | } 337 | } 338 | 339 | 340 | /** 341 | * Plugin Info 342 | * 343 | * Get information about a specific plugin 344 | * 345 | * @param mixed $name 346 | */ 347 | public function plugin_info($name) 348 | { 349 | if (isset(self::$plugins_pool[$name])) 350 | { 351 | return self::$plugins_pool[$name]['plugin_info']; 352 | } 353 | else 354 | { 355 | return true; 356 | } 357 | } 358 | 359 | 360 | /** 361 | * Print Plugins 362 | * 363 | * This plugin returns the array of all plugins found 364 | * 365 | */ 366 | public function print_plugins() 367 | { 368 | return self::$plugins_pool; 369 | } 370 | 371 | 372 | /** 373 | * Add Action 374 | * 375 | * Add a new hook trigger action 376 | * 377 | * @param mixed $name 378 | * @param mixed $function 379 | * @param mixed $priority 380 | */ 381 | public function add_action($name, $function, $priority=10) 382 | { 383 | // If we have already registered this action return true 384 | if (isset(self::$actions[$name][$priority][$function])) 385 | { 386 | return true; 387 | } 388 | 389 | /** 390 | * Allows us to iterate through multiple action hooks. 391 | */ 392 | if (is_array($name)) 393 | { 394 | foreach ($name AS $name) 395 | { 396 | // Store the action hook in the $hooks array 397 | self::$actions[$name][$priority][$function] = array("function" => $function); 398 | } 399 | } 400 | else 401 | { 402 | // Store the action hook in the $hooks array 403 | self::$actions[$name][$priority][$function] = array("function" => $function); 404 | } 405 | 406 | return true; 407 | } 408 | 409 | 410 | /** 411 | * Do Action 412 | * 413 | * Trigger an action for a particular action hook 414 | * 415 | * @param mixed $name 416 | * @param mixed $arguments 417 | * @return mixed 418 | */ 419 | public function do_action($name, $arguments = "") 420 | { 421 | // Oh, no you didn't. Are you trying to run an action hook that doesn't exist? 422 | if (!isset(self::$actions[$name])) 423 | { 424 | return $arguments; 425 | } 426 | 427 | // Set the current running hook to this 428 | self::$current_action = $name; 429 | 430 | // Key sort our action hooks 431 | ksort(self::$actions[$name]); 432 | 433 | foreach(self::$actions[$name] AS $priority => $names) 434 | { 435 | if (is_array($names)) 436 | { 437 | foreach($names AS $name) 438 | { 439 | // This line runs our function and stores the result in a variable 440 | $returnargs = call_user_func_array($name['function'], array(&$arguments)); 441 | 442 | if ($returnargs) 443 | { 444 | $arguments = $returnargs; 445 | } 446 | 447 | // Store our run hooks in the hooks history array 448 | self::$run_actions[$name][$priority]; 449 | } 450 | } 451 | } 452 | 453 | // No hook is running any more 454 | self::$current_action = ''; 455 | 456 | return $arguments; 457 | } 458 | 459 | 460 | /** 461 | * Remove Action 462 | * 463 | * Remove an action hook. No more needs to be said. 464 | * 465 | * @param mixed $name 466 | * @param mixed $function 467 | * @param mixed $priority 468 | */ 469 | public function remove_action($name, $function, $priority=10) 470 | { 471 | // If the action hook doesn't, just return true 472 | if (!isset(self::$actions[$name][$priority][$function])) 473 | { 474 | return true; 475 | } 476 | 477 | // Remove the action hook from our hooks array 478 | unset(self::$actions[$name][$priority][$function]); 479 | } 480 | 481 | 482 | /** 483 | * Current Action 484 | * 485 | * Get the currently running action hook 486 | * 487 | */ 488 | public function current_action() 489 | { 490 | return self::$current_action; 491 | } 492 | 493 | 494 | /** 495 | * Has Run 496 | * 497 | * Check if a particular hook has been run 498 | * 499 | * @param mixed $hook 500 | * @param mixed $priority 501 | */ 502 | public function has_run($action, $priority = 10) 503 | { 504 | if (isset(self::$actions[$action][$priority])) 505 | { 506 | return true; 507 | } 508 | else 509 | { 510 | return false; 511 | } 512 | } 513 | 514 | 515 | /** 516 | * Action Exists 517 | * 518 | * Does a particular action hook even exist? 519 | * 520 | * @param mixed $name 521 | */ 522 | public function action_exists($name) 523 | { 524 | if (isset(self::$actions[$name])) 525 | { 526 | return true; 527 | } 528 | else 529 | { 530 | return false; 531 | } 532 | } 533 | 534 | 535 | /** 536 | * Will print our information about all plugins and actions 537 | * neatly presented to the user. 538 | * 539 | */ 540 | public static function debug_class() 541 | { 542 | if (isset(self::$plugins_pool)) 543 | { 544 | echo "

Found plugins

"; 545 | echo "

All plugins found in the plugins directory.

"; 546 | echo "
";
547 |             print_r(self::$plugins_pool);
548 |             echo "
"; 549 | echo "
"; 550 | echo "
"; 551 | } 552 | 553 | if (isset(self::$plugins_active)) 554 | { 555 | echo "

Activated plugins

"; 556 | echo "

Activated plugins that have already been included and are usable.

"; 557 | echo "
";
558 |             print_r(self::$plugins_active);
559 |             echo "
"; 560 | echo "
"; 561 | echo "
"; 562 | } 563 | 564 | if (isset(self::$actions)) 565 | { 566 | echo "

Register action hooks

"; 567 | echo "

Action hooks that have been registered by the application and can be called via plugin files.

"; 568 | echo "
";
569 |             print_r(self::$actions);
570 |             echo "
"; 571 | echo "
"; 572 | echo "
"; 573 | } 574 | 575 | if (isset(self::$run_actions)) 576 | { 577 | echo "

Previously run action hooks

"; 578 | echo "

Hooks that have been called previously.

"; 579 | echo "
";
580 |             print_r(self::$run_actions);
581 |             echo "
"; 582 | echo "
"; 583 | echo "
"; 584 | } 585 | } 586 | } 587 | 588 | /** 589 | * Add a new action hook 590 | * 591 | * @param mixed $name 592 | * @param mixed $function 593 | * @param mixed $priority 594 | */ 595 | function add_action($name, $function, $priority=10) 596 | { 597 | return Plugins::instance()->add_action($name, $function, $priority); 598 | } 599 | 600 | /** 601 | * Run an action 602 | * 603 | * @param mixed $name 604 | * @param mixed $arguments 605 | * @return mixed 606 | */ 607 | function do_action($name, $arguments = "") 608 | { 609 | return Plugins::instance()->do_action($name, $arguments); 610 | } 611 | 612 | /** 613 | * Remove an action 614 | * 615 | * @param mixed $name 616 | * @param mixed $function 617 | * @param mixed $priority 618 | */ 619 | function remove_action($name, $function, $priority=10) 620 | { 621 | return Plugins::instance()->remove_action($name, $function, $priority); 622 | } 623 | 624 | /** 625 | * Check if an action actually exists 626 | * 627 | * @param mixed $name 628 | */ 629 | function action_exists($name) 630 | { 631 | return Plugins::instance()->action_exists($name); 632 | } 633 | 634 | /** 635 | * Set the location of where our plugins are located 636 | * 637 | * @param mixed $directory 638 | */ 639 | function set_plugin_dir($directory) 640 | { 641 | Plugins::instance()->set_plugin_dir($directory); 642 | } 643 | 644 | /** 645 | * Activate a specific plugin 646 | * 647 | * @param mixed $name 648 | */ 649 | function activate($name) 650 | { 651 | return Plugins::instance()->activate_plugin($name); 652 | } 653 | 654 | /** 655 | * Deactivate a specific plugin 656 | * 657 | * @param mixed $name 658 | */ 659 | function deactivate($name) 660 | { 661 | return Plugins::instance()->deactivate_plugin($name); 662 | } 663 | 664 | /** 665 | * Print Plugins 666 | * Returns the list of plugins 667 | * 668 | */ 669 | function print_plugins() 670 | { 671 | return Plugins::instance()->print_plugins(); 672 | } 673 | 674 | /** 675 | * Return the number of plugins found 676 | * 677 | */ 678 | function count_found_plugins() 679 | { 680 | return count(Plugins::$plugins_pool); 681 | } 682 | 683 | /** 684 | * Return number of plugins activated 685 | * 686 | */ 687 | function count_activated_plugins() 688 | { 689 | return count(Plugins::$plugins_active); 690 | } 691 | 692 | /** 693 | * Debug function will return all plugins registered and hooks 694 | * 695 | */ 696 | function debug_class() 697 | { 698 | Plugins::debug_class(); 699 | } 700 | 701 | /** 702 | * Return all errors 703 | * 704 | */ 705 | function plugin_errors() 706 | { 707 | if (is_array(Plugins::$errors)) 708 | { 709 | foreach (Plugins::$errors AS $k => $error) 710 | { 711 | echo $error."\n\r"; 712 | } 713 | } 714 | else 715 | { 716 | return true; 717 | } 718 | } 719 | 720 | /** 721 | * Return all messages 722 | * 723 | */ 724 | function plugin_messages() 725 | { 726 | if (is_array(Plugins::$messages)) 727 | { 728 | foreach (Plugins::$messages AS $k => $message) 729 | { 730 | echo $message."\n\r"; 731 | } 732 | } 733 | else 734 | { 735 | return true; 736 | } 737 | } -------------------------------------------------------------------------------- /plugins/cimarkdown/markdown.php: -------------------------------------------------------------------------------- 1 | 8 | # 9 | # Original Markdown 10 | # Copyright (c) 2004-2006 John Gruber 11 | # 12 | # 13 | 14 | 15 | define( 'MARKDOWN_VERSION', "1.0.1n" ); # Sat 10 Oct 2009 16 | define( 'MARKDOWNEXTRA_VERSION', "1.2.4" ); # Sat 10 Oct 2009 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 | 38 | # 39 | # WordPress settings: 40 | # 41 | 42 | # Change to false to remove Markdown from posts and/or comments. 43 | @define( 'MARKDOWN_WP_POSTS', true ); 44 | @define( 'MARKDOWN_WP_COMMENTS', true ); 45 | 46 | 47 | 48 | ### Standard Function Interface ### 49 | 50 | @define( 'MARKDOWN_PARSER_CLASS', 'MarkdownExtra_Parser' ); 51 | 52 | function Markdown($text) { 53 | # 54 | # Initialize the parser and return the result of its transform method. 55 | # 56 | # Setup static parser variable. 57 | static $parser; 58 | if (!isset($parser)) { 59 | $parser_class = MARKDOWN_PARSER_CLASS; 60 | $parser = new $parser_class; 61 | } 62 | 63 | # Transform text using parser. 64 | return $parser->transform($text); 65 | } 66 | 67 | ### Smarty Modifier Interface ### 68 | 69 | function smarty_modifier_markdown($text) { 70 | return Markdown($text); 71 | } 72 | 73 | # 74 | # Markdown Parser Class 75 | # 76 | 77 | class Markdown_Parser { 78 | 79 | # Regex to match balanced [brackets]. 80 | # Needed to insert a maximum bracked depth while converting to PHP. 81 | var $nested_brackets_depth = 6; 82 | var $nested_brackets_re; 83 | 84 | var $nested_url_parenthesis_depth = 4; 85 | var $nested_url_parenthesis_re; 86 | 87 | # Table of hash values for escaped characters: 88 | var $escape_chars = '\`*_{}[]()>#+-.!'; 89 | var $escape_chars_re; 90 | 91 | # Change to ">" for HTML output. 92 | var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX; 93 | var $tab_width = MARKDOWN_TAB_WIDTH; 94 | 95 | # Change to `true` to disallow markup or entities. 96 | var $no_markup = false; 97 | var $no_entities = false; 98 | 99 | # Predefined urls and titles for reference links and images. 100 | var $predef_urls = array(); 101 | var $predef_titles = array(); 102 | 103 | 104 | function Markdown_Parser() { 105 | # 106 | # Constructor function. Initialize appropriate member variables. 107 | # 108 | $this->_initDetab(); 109 | $this->prepareItalicsAndBold(); 110 | 111 | $this->nested_brackets_re = 112 | str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth). 113 | str_repeat('\])*', $this->nested_brackets_depth); 114 | 115 | $this->nested_url_parenthesis_re = 116 | str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth). 117 | str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth); 118 | 119 | $this->escape_chars_re = '['.preg_quote($this->escape_chars).']'; 120 | 121 | # Sort document, block, and span gamut in ascendent priority order. 122 | asort($this->document_gamut); 123 | asort($this->block_gamut); 124 | asort($this->span_gamut); 125 | } 126 | 127 | 128 | # Internal hashes used during transformation. 129 | var $urls = array(); 130 | var $titles = array(); 131 | var $html_hashes = array(); 132 | 133 | # Status flag to avoid invalid nesting. 134 | var $in_anchor = false; 135 | 136 | 137 | function setup() { 138 | # 139 | # Called before the transformation process starts to setup parser 140 | # states. 141 | # 142 | # Clear global hashes. 143 | $this->urls = $this->predef_urls; 144 | $this->titles = $this->predef_titles; 145 | $this->html_hashes = array(); 146 | 147 | $in_anchor = false; 148 | } 149 | 150 | function teardown() { 151 | # 152 | # Called after the transformation process to clear any variable 153 | # which may be taking up memory unnecessarly. 154 | # 155 | $this->urls = array(); 156 | $this->titles = array(); 157 | $this->html_hashes = array(); 158 | } 159 | 160 | 161 | function transform($text) { 162 | # 163 | # Main function. Performs some preprocessing on the input text 164 | # and pass it through the document gamut. 165 | # 166 | $this->setup(); 167 | 168 | # Remove UTF-8 BOM and marker character in input, if present. 169 | $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text); 170 | 171 | # Standardize line endings: 172 | # DOS to Unix and Mac to Unix 173 | $text = preg_replace('{\r\n?}', "\n", $text); 174 | 175 | # Make sure $text ends with a couple of newlines: 176 | $text .= "\n\n"; 177 | 178 | # Convert all tabs to spaces. 179 | $text = $this->detab($text); 180 | 181 | # Turn block-level HTML blocks into hash entries 182 | $text = $this->hashHTMLBlocks($text); 183 | 184 | # Strip any lines consisting only of spaces and tabs. 185 | # This makes subsequent regexen easier to write, because we can 186 | # match consecutive blank lines with /\n+/ instead of something 187 | # contorted like /[ ]*\n+/ . 188 | $text = preg_replace('/^[ ]+$/m', '', $text); 189 | 190 | # Run document gamut methods. 191 | foreach ($this->document_gamut as $method => $priority) { 192 | $text = $this->$method($text); 193 | } 194 | 195 | $this->teardown(); 196 | 197 | return $text . "\n"; 198 | } 199 | 200 | var $document_gamut = array( 201 | # Strip link definitions, store in hashes. 202 | "stripLinkDefinitions" => 20, 203 | 204 | "runBasicBlockGamut" => 30, 205 | ); 206 | 207 | 208 | function stripLinkDefinitions($text) { 209 | # 210 | # Strips link definitions from text, stores the URLs and titles in 211 | # hash references. 212 | # 213 | $less_than_tab = $this->tab_width - 1; 214 | 215 | # Link defs are in the form: ^[id]: url "optional title" 216 | $text = preg_replace_callback('{ 217 | ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1 218 | [ ]* 219 | \n? # maybe *one* newline 220 | [ ]* 221 | (?: 222 | <(.+?)> # url = $2 223 | | 224 | (\S+?) # url = $3 225 | ) 226 | [ ]* 227 | \n? # maybe one newline 228 | [ ]* 229 | (?: 230 | (?<=\s) # lookbehind for whitespace 231 | ["(] 232 | (.*?) # title = $4 233 | [")] 234 | [ ]* 235 | )? # title is optional 236 | (?:\n+|\Z) 237 | }xm', 238 | array(&$this, '_stripLinkDefinitions_callback'), 239 | $text); 240 | return $text; 241 | } 242 | function _stripLinkDefinitions_callback($matches) { 243 | $link_id = strtolower($matches[1]); 244 | $url = $matches[2] == '' ? $matches[3] : $matches[2]; 245 | $this->urls[$link_id] = $url; 246 | $this->titles[$link_id] =& $matches[4]; 247 | return ''; # String that will replace the block 248 | } 249 | 250 | 251 | function hashHTMLBlocks($text) { 252 | if ($this->no_markup) return $text; 253 | 254 | $less_than_tab = $this->tab_width - 1; 255 | 256 | # Hashify HTML blocks: 257 | # We only want to do this for block-level HTML tags, such as headers, 258 | # lists, and tables. That's because we still want to wrap

s around 259 | # "paragraphs" that are wrapped in non-block-level tags, such as anchors, 260 | # phrase emphasis, and spans. The list of tags we're looking for is 261 | # hard-coded: 262 | # 263 | # * List "a" is made of tags which can be both inline or block-level. 264 | # These will be treated block-level when the start tag is alone on 265 | # its line, otherwise they're not matched here and will be taken as 266 | # inline later. 267 | # * List "b" is made of tags which are always block-level; 268 | # 269 | $block_tags_a_re = 'ins|del'; 270 | $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'. 271 | 'script|noscript|form|fieldset|iframe|math'; 272 | 273 | # Regular expression for the content of a block tag. 274 | $nested_tags_level = 4; 275 | $attr = ' 276 | (?> # optional tag attributes 277 | \s # starts with whitespace 278 | (?> 279 | [^>"/]+ # text outside quotes 280 | | 281 | /+(?!>) # slash not followed by ">" 282 | | 283 | "[^"]*" # text inside double quotes (tolerate ">") 284 | | 285 | \'[^\']*\' # text inside single quotes (tolerate ">") 286 | )* 287 | )? 288 | '; 289 | $content = 290 | str_repeat(' 291 | (?> 292 | [^<]+ # content without tag 293 | | 294 | <\2 # nested opening tag 295 | '.$attr.' # attributes 296 | (?> 297 | /> 298 | | 299 | >', $nested_tags_level). # end of opening tag 300 | '.*?'. # last level nested tag content 301 | str_repeat(' 302 | # closing nested tag 303 | ) 304 | | 305 | <(?!/\2\s*> # other tags with a different name 306 | ) 307 | )*', 308 | $nested_tags_level); 309 | $content2 = str_replace('\2', '\3', $content); 310 | 311 | # First, look for nested blocks, e.g.: 312 | #

313 | #
314 | # tags for inner block must be indented. 315 | #
316 | #
317 | # 318 | # The outermost tags must start at the left margin for this to match, and 319 | # the inner nested divs must be indented. 320 | # We need to do this before the next, more liberal match, because the next 321 | # match will start at the first `
` and stop at the first `
`. 322 | $text = preg_replace_callback('{(?> 323 | (?> 324 | (?<=\n\n) # Starting after a blank line 325 | | # or 326 | \A\n? # the beginning of the doc 327 | ) 328 | ( # save in $1 329 | 330 | # Match from `\n` to `\n`, handling nested tags 331 | # in between. 332 | 333 | [ ]{0,'.$less_than_tab.'} 334 | <('.$block_tags_b_re.')# start tag = $2 335 | '.$attr.'> # attributes followed by > and \n 336 | '.$content.' # content, support nesting 337 | # the matching end tag 338 | [ ]* # trailing spaces/tabs 339 | (?=\n+|\Z) # followed by a newline or end of document 340 | 341 | | # Special version for tags of group a. 342 | 343 | [ ]{0,'.$less_than_tab.'} 344 | <('.$block_tags_a_re.')# start tag = $3 345 | '.$attr.'>[ ]*\n # attributes followed by > 346 | '.$content2.' # content, support nesting 347 | # the matching end tag 348 | [ ]* # trailing spaces/tabs 349 | (?=\n+|\Z) # followed by a newline or end of document 350 | 351 | | # Special case just for
. It was easier to make a special 352 | # case than to make the other regex more complicated. 353 | 354 | [ ]{0,'.$less_than_tab.'} 355 | <(hr) # start tag = $2 356 | '.$attr.' # attributes 357 | /?> # the matching end tag 358 | [ ]* 359 | (?=\n{2,}|\Z) # followed by a blank line or end of document 360 | 361 | | # Special case for standalone HTML comments: 362 | 363 | [ ]{0,'.$less_than_tab.'} 364 | (?s: 365 | 366 | ) 367 | [ ]* 368 | (?=\n{2,}|\Z) # followed by a blank line or end of document 369 | 370 | | # PHP and ASP-style processor instructions ( 377 | ) 378 | [ ]* 379 | (?=\n{2,}|\Z) # followed by a blank line or end of document 380 | 381 | ) 382 | )}Sxmi', 383 | array(&$this, '_hashHTMLBlocks_callback'), 384 | $text); 385 | 386 | return $text; 387 | } 388 | function _hashHTMLBlocks_callback($matches) { 389 | $text = $matches[1]; 390 | $key = $this->hashBlock($text); 391 | return "\n\n$key\n\n"; 392 | } 393 | 394 | 395 | function hashPart($text, $boundary = 'X') { 396 | # 397 | # Called whenever a tag must be hashed when a function insert an atomic 398 | # element in the text stream. Passing $text to through this function gives 399 | # a unique text-token which will be reverted back when calling unhash. 400 | # 401 | # The $boundary argument specify what character should be used to surround 402 | # the token. By convension, "B" is used for block elements that needs not 403 | # to be wrapped into paragraph tags at the end, ":" is used for elements 404 | # that are word separators and "X" is used in the general case. 405 | # 406 | # Swap back any tag hash found in $text so we do not have to `unhash` 407 | # multiple times at the end. 408 | $text = $this->unhash($text); 409 | 410 | # Then hash the block. 411 | static $i = 0; 412 | $key = "$boundary\x1A" . ++$i . $boundary; 413 | $this->html_hashes[$key] = $text; 414 | return $key; # String that will replace the tag. 415 | } 416 | 417 | 418 | function hashBlock($text) { 419 | # 420 | # Shortcut function for hashPart with block-level boundaries. 421 | # 422 | return $this->hashPart($text, 'B'); 423 | } 424 | 425 | 426 | var $block_gamut = array( 427 | # 428 | # These are all the transformations that form block-level 429 | # tags like paragraphs, headers, and list items. 430 | # 431 | "doHeaders" => 10, 432 | "doHorizontalRules" => 20, 433 | 434 | "doLists" => 40, 435 | "doCodeBlocks" => 50, 436 | "doBlockQuotes" => 60, 437 | ); 438 | 439 | function runBlockGamut($text) { 440 | # 441 | # Run block gamut tranformations. 442 | # 443 | # We need to escape raw HTML in Markdown source before doing anything 444 | # else. This need to be done for each block, and not only at the 445 | # begining in the Markdown function since hashed blocks can be part of 446 | # list items and could have been indented. Indented blocks would have 447 | # been seen as a code block in a previous pass of hashHTMLBlocks. 448 | $text = $this->hashHTMLBlocks($text); 449 | 450 | return $this->runBasicBlockGamut($text); 451 | } 452 | 453 | function runBasicBlockGamut($text) { 454 | # 455 | # Run block gamut tranformations, without hashing HTML blocks. This is 456 | # useful when HTML blocks are known to be already hashed, like in the first 457 | # whole-document pass. 458 | # 459 | foreach ($this->block_gamut as $method => $priority) { 460 | $text = $this->$method($text); 461 | } 462 | 463 | # Finally form paragraph and restore hashed blocks. 464 | $text = $this->formParagraphs($text); 465 | 466 | return $text; 467 | } 468 | 469 | 470 | function doHorizontalRules($text) { 471 | # Do Horizontal Rules: 472 | return preg_replace( 473 | '{ 474 | ^[ ]{0,3} # Leading space 475 | ([-*_]) # $1: First marker 476 | (?> # Repeated marker group 477 | [ ]{0,2} # Zero, one, or two spaces. 478 | \1 # Marker character 479 | ){2,} # Group repeated at least twice 480 | [ ]* # Tailing spaces 481 | $ # End of line. 482 | }mx', 483 | "\n".$this->hashBlock("empty_element_suffix")."\n", 484 | $text); 485 | } 486 | 487 | 488 | var $span_gamut = array( 489 | # 490 | # These are all the transformations that occur *within* block-level 491 | # tags like paragraphs, headers, and list items. 492 | # 493 | # Process character escapes, code spans, and inline HTML 494 | # in one shot. 495 | "parseSpan" => -30, 496 | 497 | # Process anchor and image tags. Images must come first, 498 | # because ![foo][f] looks like an anchor. 499 | "doImages" => 10, 500 | "doAnchors" => 20, 501 | 502 | # Make links out of things like `` 503 | # Must come after doAnchors, because you can use < and > 504 | # delimiters in inline links like [this](). 505 | "doAutoLinks" => 30, 506 | "encodeAmpsAndAngles" => 40, 507 | 508 | "doItalicsAndBold" => 50, 509 | "doHardBreaks" => 60, 510 | ); 511 | 512 | function runSpanGamut($text) { 513 | # 514 | # Run span gamut tranformations. 515 | # 516 | foreach ($this->span_gamut as $method => $priority) { 517 | $text = $this->$method($text); 518 | } 519 | 520 | return $text; 521 | } 522 | 523 | 524 | function doHardBreaks($text) { 525 | # Do hard breaks: 526 | return preg_replace_callback('/ {2,}\n/', 527 | array(&$this, '_doHardBreaks_callback'), $text); 528 | } 529 | function _doHardBreaks_callback($matches) { 530 | return $this->hashPart("empty_element_suffix\n"); 531 | } 532 | 533 | 534 | function doAnchors($text) { 535 | # 536 | # Turn Markdown link shortcuts into XHTML tags. 537 | # 538 | if ($this->in_anchor) return $text; 539 | $this->in_anchor = true; 540 | 541 | # 542 | # First, handle reference-style links: [link text] [id] 543 | # 544 | $text = preg_replace_callback('{ 545 | ( # wrap whole match in $1 546 | \[ 547 | ('.$this->nested_brackets_re.') # link text = $2 548 | \] 549 | 550 | [ ]? # one optional space 551 | (?:\n[ ]*)? # one optional newline followed by spaces 552 | 553 | \[ 554 | (.*?) # id = $3 555 | \] 556 | ) 557 | }xs', 558 | array(&$this, '_doAnchors_reference_callback'), $text); 559 | 560 | # 561 | # Next, inline-style links: [link text](url "optional title") 562 | # 563 | $text = preg_replace_callback('{ 564 | ( # wrap whole match in $1 565 | \[ 566 | ('.$this->nested_brackets_re.') # link text = $2 567 | \] 568 | \( # literal paren 569 | [ \n]* 570 | (?: 571 | <(.+?)> # href = $3 572 | | 573 | ('.$this->nested_url_parenthesis_re.') # href = $4 574 | ) 575 | [ \n]* 576 | ( # $5 577 | ([\'"]) # quote char = $6 578 | (.*?) # Title = $7 579 | \6 # matching quote 580 | [ \n]* # ignore any spaces/tabs between closing quote and ) 581 | )? # title is optional 582 | \) 583 | ) 584 | }xs', 585 | array(&$this, '_doAnchors_inline_callback'), $text); 586 | 587 | # 588 | # Last, handle reference-style shortcuts: [link text] 589 | # These must come last in case you've also got [link text][1] 590 | # or [link text](/foo) 591 | # 592 | $text = preg_replace_callback('{ 593 | ( # wrap whole match in $1 594 | \[ 595 | ([^\[\]]+) # link text = $2; can\'t contain [ or ] 596 | \] 597 | ) 598 | }xs', 599 | array(&$this, '_doAnchors_reference_callback'), $text); 600 | 601 | $this->in_anchor = false; 602 | return $text; 603 | } 604 | function _doAnchors_reference_callback($matches) { 605 | $whole_match = $matches[1]; 606 | $link_text = $matches[2]; 607 | $link_id =& $matches[3]; 608 | 609 | if ($link_id == "") { 610 | # for shortcut links like [this][] or [this]. 611 | $link_id = $link_text; 612 | } 613 | 614 | # lower-case and turn embedded newlines into spaces 615 | $link_id = strtolower($link_id); 616 | $link_id = preg_replace('{[ ]?\n}', ' ', $link_id); 617 | 618 | if (isset($this->urls[$link_id])) { 619 | $url = $this->urls[$link_id]; 620 | $url = $this->encodeAttribute($url); 621 | 622 | $result = "titles[$link_id] ) ) { 624 | $title = $this->titles[$link_id]; 625 | $title = $this->encodeAttribute($title); 626 | $result .= " title=\"$title\""; 627 | } 628 | 629 | $link_text = $this->runSpanGamut($link_text); 630 | $result .= ">$link_text"; 631 | $result = $this->hashPart($result); 632 | } 633 | else { 634 | $result = $whole_match; 635 | } 636 | return $result; 637 | } 638 | function _doAnchors_inline_callback($matches) { 639 | $whole_match = $matches[1]; 640 | $link_text = $this->runSpanGamut($matches[2]); 641 | $url = $matches[3] == '' ? $matches[4] : $matches[3]; 642 | $title =& $matches[7]; 643 | 644 | $url = $this->encodeAttribute($url); 645 | 646 | $result = "encodeAttribute($title); 649 | $result .= " title=\"$title\""; 650 | } 651 | 652 | $link_text = $this->runSpanGamut($link_text); 653 | $result .= ">$link_text"; 654 | 655 | return $this->hashPart($result); 656 | } 657 | 658 | 659 | function doImages($text) { 660 | # 661 | # Turn Markdown image shortcuts into tags. 662 | # 663 | # 664 | # First, handle reference-style labeled images: ![alt text][id] 665 | # 666 | $text = preg_replace_callback('{ 667 | ( # wrap whole match in $1 668 | !\[ 669 | ('.$this->nested_brackets_re.') # alt text = $2 670 | \] 671 | 672 | [ ]? # one optional space 673 | (?:\n[ ]*)? # one optional newline followed by spaces 674 | 675 | \[ 676 | (.*?) # id = $3 677 | \] 678 | 679 | ) 680 | }xs', 681 | array(&$this, '_doImages_reference_callback'), $text); 682 | 683 | # 684 | # Next, handle inline images: ![alt text](url "optional title") 685 | # Don't forget: encode * and _ 686 | # 687 | $text = preg_replace_callback('{ 688 | ( # wrap whole match in $1 689 | !\[ 690 | ('.$this->nested_brackets_re.') # alt text = $2 691 | \] 692 | \s? # One optional whitespace character 693 | \( # literal paren 694 | [ \n]* 695 | (?: 696 | <(\S*)> # src url = $3 697 | | 698 | ('.$this->nested_url_parenthesis_re.') # src url = $4 699 | ) 700 | [ \n]* 701 | ( # $5 702 | ([\'"]) # quote char = $6 703 | (.*?) # title = $7 704 | \6 # matching quote 705 | [ \n]* 706 | )? # title is optional 707 | \) 708 | ) 709 | }xs', 710 | array(&$this, '_doImages_inline_callback'), $text); 711 | 712 | return $text; 713 | } 714 | function _doImages_reference_callback($matches) { 715 | $whole_match = $matches[1]; 716 | $alt_text = $matches[2]; 717 | $link_id = strtolower($matches[3]); 718 | 719 | if ($link_id == "") { 720 | $link_id = strtolower($alt_text); # for shortcut links like ![this][]. 721 | } 722 | 723 | $alt_text = $this->encodeAttribute($alt_text); 724 | if (isset($this->urls[$link_id])) { 725 | $url = $this->encodeAttribute($this->urls[$link_id]); 726 | $result = "\"$alt_text\"";titles[$link_id])) { 728 | $title = $this->titles[$link_id]; 729 | $title = $this->encodeAttribute($title); 730 | $result .= " title=\"$title\""; 731 | } 732 | $result .= $this->empty_element_suffix; 733 | $result = $this->hashPart($result); 734 | } 735 | else { 736 | # If there's no such link ID, leave intact: 737 | $result = $whole_match; 738 | } 739 | 740 | return $result; 741 | } 742 | function _doImages_inline_callback($matches) { 743 | $whole_match = $matches[1]; 744 | $alt_text = $matches[2]; 745 | $url = $matches[3] == '' ? $matches[4] : $matches[3]; 746 | $title =& $matches[7]; 747 | 748 | $alt_text = $this->encodeAttribute($alt_text); 749 | $url = $this->encodeAttribute($url); 750 | $result = "\"$alt_text\"";encodeAttribute($title); 753 | $result .= " title=\"$title\""; # $title already quoted 754 | } 755 | $result .= $this->empty_element_suffix; 756 | 757 | return $this->hashPart($result); 758 | } 759 | 760 | 761 | function doHeaders($text) { 762 | # Setext-style headers: 763 | # Header 1 764 | # ======== 765 | # 766 | # Header 2 767 | # -------- 768 | # 769 | $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx', 770 | array(&$this, '_doHeaders_callback_setext'), $text); 771 | 772 | # atx-style headers: 773 | # # Header 1 774 | # ## Header 2 775 | # ## Header 2 with closing hashes ## 776 | # ... 777 | # ###### Header 6 778 | # 779 | $text = preg_replace_callback('{ 780 | ^(\#{1,6}) # $1 = string of #\'s 781 | [ ]* 782 | (.+?) # $2 = Header text 783 | [ ]* 784 | \#* # optional closing #\'s (not counted) 785 | \n+ 786 | }xm', 787 | array(&$this, '_doHeaders_callback_atx'), $text); 788 | 789 | return $text; 790 | } 791 | function _doHeaders_callback_setext($matches) { 792 | # Terrible hack to check we haven't found an empty list item. 793 | if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1])) 794 | return $matches[0]; 795 | 796 | $level = $matches[2]{0} == '=' ? 1 : 2; 797 | $block = "".$this->runSpanGamut($matches[1]).""; 798 | return "\n" . $this->hashBlock($block) . "\n\n"; 799 | } 800 | function _doHeaders_callback_atx($matches) { 801 | $level = strlen($matches[1]); 802 | $block = "".$this->runSpanGamut($matches[2]).""; 803 | return "\n" . $this->hashBlock($block) . "\n\n"; 804 | } 805 | 806 | 807 | function doLists($text) { 808 | # 809 | # Form HTML ordered (numbered) and unordered (bulleted) lists. 810 | # 811 | $less_than_tab = $this->tab_width - 1; 812 | 813 | # Re-usable patterns to match list item bullets and number markers: 814 | $marker_ul_re = '[*+-]'; 815 | $marker_ol_re = '\d+[.]'; 816 | $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; 817 | 818 | $markers_relist = array( 819 | $marker_ul_re => $marker_ol_re, 820 | $marker_ol_re => $marker_ul_re, 821 | ); 822 | 823 | foreach ($markers_relist as $marker_re => $other_marker_re) { 824 | # Re-usable pattern to match any entirel ul or ol list: 825 | $whole_list_re = ' 826 | ( # $1 = whole list 827 | ( # $2 828 | ([ ]{0,'.$less_than_tab.'}) # $3 = number of spaces 829 | ('.$marker_re.') # $4 = first list item marker 830 | [ ]+ 831 | ) 832 | (?s:.+?) 833 | ( # $5 834 | \z 835 | | 836 | \n{2,} 837 | (?=\S) 838 | (?! # Negative lookahead for another list item marker 839 | [ ]* 840 | '.$marker_re.'[ ]+ 841 | ) 842 | | 843 | (?= # Lookahead for another kind of list 844 | \n 845 | \3 # Must have the same indentation 846 | '.$other_marker_re.'[ ]+ 847 | ) 848 | ) 849 | ) 850 | '; // mx 851 | 852 | # We use a different prefix before nested lists than top-level lists. 853 | # See extended comment in _ProcessListItems(). 854 | 855 | if ($this->list_level) { 856 | $text = preg_replace_callback('{ 857 | ^ 858 | '.$whole_list_re.' 859 | }mx', 860 | array(&$this, '_doLists_callback'), $text); 861 | } 862 | else { 863 | $text = preg_replace_callback('{ 864 | (?:(?<=\n)\n|\A\n?) # Must eat the newline 865 | '.$whole_list_re.' 866 | }mx', 867 | array(&$this, '_doLists_callback'), $text); 868 | } 869 | } 870 | 871 | return $text; 872 | } 873 | function _doLists_callback($matches) { 874 | # Re-usable patterns to match list item bullets and number markers: 875 | $marker_ul_re = '[*+-]'; 876 | $marker_ol_re = '\d+[.]'; 877 | $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; 878 | 879 | $list = $matches[1]; 880 | $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol"; 881 | 882 | $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re ); 883 | 884 | $list .= "\n"; 885 | $result = $this->processListItems($list, $marker_any_re); 886 | 887 | $result = $this->hashBlock("<$list_type>\n" . $result . ""); 888 | return "\n". $result ."\n\n"; 889 | } 890 | 891 | var $list_level = 0; 892 | 893 | function processListItems($list_str, $marker_any_re) { 894 | # 895 | # Process the contents of a single ordered or unordered list, splitting it 896 | # into individual list items. 897 | # 898 | # The $this->list_level global keeps track of when we're inside a list. 899 | # Each time we enter a list, we increment it; when we leave a list, 900 | # we decrement. If it's zero, we're not in a list anymore. 901 | # 902 | # We do this because when we're not inside a list, we want to treat 903 | # something like this: 904 | # 905 | # I recommend upgrading to version 906 | # 8. Oops, now this line is treated 907 | # as a sub-list. 908 | # 909 | # As a single paragraph, despite the fact that the second line starts 910 | # with a digit-period-space sequence. 911 | # 912 | # Whereas when we're inside a list (or sub-list), that line will be 913 | # treated as the start of a sub-list. What a kludge, huh? This is 914 | # an aspect of Markdown's syntax that's hard to parse perfectly 915 | # without resorting to mind-reading. Perhaps the solution is to 916 | # change the syntax rules such that sub-lists must start with a 917 | # starting cardinal number; e.g. "1." or "a.". 918 | 919 | $this->list_level++; 920 | 921 | # trim trailing blank lines: 922 | $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str); 923 | 924 | $list_str = preg_replace_callback('{ 925 | (\n)? # leading line = $1 926 | (^[ ]*) # leading whitespace = $2 927 | ('.$marker_any_re.' # list marker and space = $3 928 | (?:[ ]+|(?=\n)) # space only required if item is not empty 929 | ) 930 | ((?s:.*?)) # list item text = $4 931 | (?:(\n+(?=\n))|\n) # tailing blank line = $5 932 | (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n)))) 933 | }xm', 934 | array(&$this, '_processListItems_callback'), $list_str); 935 | 936 | $this->list_level--; 937 | return $list_str; 938 | } 939 | function _processListItems_callback($matches) { 940 | $item = $matches[4]; 941 | $leading_line =& $matches[1]; 942 | $leading_space =& $matches[2]; 943 | $marker_space = $matches[3]; 944 | $tailing_blank_line =& $matches[5]; 945 | 946 | if ($leading_line || $tailing_blank_line || 947 | preg_match('/\n{2,}/', $item)) 948 | { 949 | # Replace marker with the appropriate whitespace indentation 950 | $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item; 951 | $item = $this->runBlockGamut($this->outdent($item)."\n"); 952 | } 953 | else { 954 | # Recursion for sub-lists: 955 | $item = $this->doLists($this->outdent($item)); 956 | $item = preg_replace('/\n+$/', '', $item); 957 | $item = $this->runSpanGamut($item); 958 | } 959 | 960 | return "
  • " . $item . "
  • \n"; 961 | } 962 | 963 | 964 | function doCodeBlocks($text) { 965 | # 966 | # Process Markdown `
    ` blocks.
     967 | 	#
     968 | 		$text = preg_replace_callback('{
     969 | 				(?:\n\n|\A\n?)
     970 | 				(	            # $1 = the code block -- one or more lines, starting with a space/tab
     971 | 				  (?>
     972 | 					[ ]{'.$this->tab_width.'}  # Lines must start with a tab or a tab-width of spaces
     973 | 					.*\n+
     974 | 				  )+
     975 | 				)
     976 | 				((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z)	# Lookahead for non-space at line-start, or end of doc
     977 | 			}xm',
     978 | 			array(&$this, '_doCodeBlocks_callback'), $text);
     979 | 
     980 | 		return $text;
     981 | 	}
     982 | 	function _doCodeBlocks_callback($matches) {
     983 | 		$codeblock = $matches[1];
     984 | 
     985 | 		$codeblock = $this->outdent($codeblock);
     986 | 		$codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
     987 | 
     988 | 		# trim leading newlines and trailing newlines
     989 | 		$codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
     990 | 
     991 | 		$codeblock = "
    $codeblock\n
    "; 992 | return "\n\n".$this->hashBlock($codeblock)."\n\n"; 993 | } 994 | 995 | 996 | function makeCodeSpan($code) { 997 | # 998 | # Create a code span markup for $code. Called from handleSpanToken. 999 | # 1000 | $code = htmlspecialchars(trim($code), ENT_NOQUOTES); 1001 | return $this->hashPart("$code"); 1002 | } 1003 | 1004 | 1005 | var $em_relist = array( 1006 | '' => '(?:(? '(?<=\S|^)(? '(?<=\S|^)(? '(?:(? '(?<=\S|^)(? '(?<=\S|^)(? '(?:(? '(?<=\S|^)(? '(?<=\S|^)(?em_relist as $em => $em_re) { 1028 | foreach ($this->strong_relist as $strong => $strong_re) { 1029 | # Construct list of allowed token expressions. 1030 | $token_relist = array(); 1031 | if (isset($this->em_strong_relist["$em$strong"])) { 1032 | $token_relist[] = $this->em_strong_relist["$em$strong"]; 1033 | } 1034 | $token_relist[] = $em_re; 1035 | $token_relist[] = $strong_re; 1036 | 1037 | # Construct master expression from list. 1038 | $token_re = '{('. implode('|', $token_relist) .')}'; 1039 | $this->em_strong_prepared_relist["$em$strong"] = $token_re; 1040 | } 1041 | } 1042 | } 1043 | 1044 | function doItalicsAndBold($text) { 1045 | $token_stack = array(''); 1046 | $text_stack = array(''); 1047 | $em = ''; 1048 | $strong = ''; 1049 | $tree_char_em = false; 1050 | 1051 | while (1) { 1052 | # 1053 | # Get prepared regular expression for seraching emphasis tokens 1054 | # in current context. 1055 | # 1056 | $token_re = $this->em_strong_prepared_relist["$em$strong"]; 1057 | 1058 | # 1059 | # Each loop iteration search for the next emphasis token. 1060 | # Each token is then passed to handleSpanToken. 1061 | # 1062 | $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); 1063 | $text_stack[0] .= $parts[0]; 1064 | $token =& $parts[1]; 1065 | $text =& $parts[2]; 1066 | 1067 | if (empty($token)) { 1068 | # Reached end of text span: empty stack without emitting. 1069 | # any more emphasis. 1070 | while ($token_stack[0]) { 1071 | $text_stack[1] .= array_shift($token_stack); 1072 | $text_stack[0] .= array_shift($text_stack); 1073 | } 1074 | break; 1075 | } 1076 | 1077 | $token_len = strlen($token); 1078 | if ($tree_char_em) { 1079 | # Reached closing marker while inside a three-char emphasis. 1080 | if ($token_len == 3) { 1081 | # Three-char closing marker, close em and strong. 1082 | array_shift($token_stack); 1083 | $span = array_shift($text_stack); 1084 | $span = $this->runSpanGamut($span); 1085 | $span = "$span"; 1086 | $text_stack[0] .= $this->hashPart($span); 1087 | $em = ''; 1088 | $strong = ''; 1089 | } else { 1090 | # Other closing marker: close one em or strong and 1091 | # change current token state to match the other 1092 | $token_stack[0] = str_repeat($token{0}, 3-$token_len); 1093 | $tag = $token_len == 2 ? "strong" : "em"; 1094 | $span = $text_stack[0]; 1095 | $span = $this->runSpanGamut($span); 1096 | $span = "<$tag>$span"; 1097 | $text_stack[0] = $this->hashPart($span); 1098 | $$tag = ''; # $$tag stands for $em or $strong 1099 | } 1100 | $tree_char_em = false; 1101 | } else if ($token_len == 3) { 1102 | if ($em) { 1103 | # Reached closing marker for both em and strong. 1104 | # Closing strong marker: 1105 | for ($i = 0; $i < 2; ++$i) { 1106 | $shifted_token = array_shift($token_stack); 1107 | $tag = strlen($shifted_token) == 2 ? "strong" : "em"; 1108 | $span = array_shift($text_stack); 1109 | $span = $this->runSpanGamut($span); 1110 | $span = "<$tag>$span"; 1111 | $text_stack[0] .= $this->hashPart($span); 1112 | $$tag = ''; # $$tag stands for $em or $strong 1113 | } 1114 | } else { 1115 | # Reached opening three-char emphasis marker. Push on token 1116 | # stack; will be handled by the special condition above. 1117 | $em = $token{0}; 1118 | $strong = "$em$em"; 1119 | array_unshift($token_stack, $token); 1120 | array_unshift($text_stack, ''); 1121 | $tree_char_em = true; 1122 | } 1123 | } else if ($token_len == 2) { 1124 | if ($strong) { 1125 | # Unwind any dangling emphasis marker: 1126 | if (strlen($token_stack[0]) == 1) { 1127 | $text_stack[1] .= array_shift($token_stack); 1128 | $text_stack[0] .= array_shift($text_stack); 1129 | } 1130 | # Closing strong marker: 1131 | array_shift($token_stack); 1132 | $span = array_shift($text_stack); 1133 | $span = $this->runSpanGamut($span); 1134 | $span = "$span"; 1135 | $text_stack[0] .= $this->hashPart($span); 1136 | $strong = ''; 1137 | } else { 1138 | array_unshift($token_stack, $token); 1139 | array_unshift($text_stack, ''); 1140 | $strong = $token; 1141 | } 1142 | } else { 1143 | # Here $token_len == 1 1144 | if ($em) { 1145 | if (strlen($token_stack[0]) == 1) { 1146 | # Closing emphasis marker: 1147 | array_shift($token_stack); 1148 | $span = array_shift($text_stack); 1149 | $span = $this->runSpanGamut($span); 1150 | $span = "$span"; 1151 | $text_stack[0] .= $this->hashPart($span); 1152 | $em = ''; 1153 | } else { 1154 | $text_stack[0] .= $token; 1155 | } 1156 | } else { 1157 | array_unshift($token_stack, $token); 1158 | array_unshift($text_stack, ''); 1159 | $em = $token; 1160 | } 1161 | } 1162 | } 1163 | return $text_stack[0]; 1164 | } 1165 | 1166 | 1167 | function doBlockQuotes($text) { 1168 | $text = preg_replace_callback('/ 1169 | ( # Wrap whole match in $1 1170 | (?> 1171 | ^[ ]*>[ ]? # ">" at the start of a line 1172 | .+\n # rest of the first line 1173 | (.+\n)* # subsequent consecutive lines 1174 | \n* # blanks 1175 | )+ 1176 | ) 1177 | /xm', 1178 | array(&$this, '_doBlockQuotes_callback'), $text); 1179 | 1180 | return $text; 1181 | } 1182 | function _doBlockQuotes_callback($matches) { 1183 | $bq = $matches[1]; 1184 | # trim one level of quoting - trim whitespace-only lines 1185 | $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq); 1186 | $bq = $this->runBlockGamut($bq); # recurse 1187 | 1188 | $bq = preg_replace('/^/m', " ", $bq); 1189 | # These leading spaces cause problem with
     content, 
    1190 | 		# so we need to fix that:
    1191 | 		$bq = preg_replace_callback('{(\s*
    .+?
    )}sx', 1192 | array(&$this, '_doBlockQuotes_callback2'), $bq); 1193 | 1194 | return "\n". $this->hashBlock("
    \n$bq\n
    ")."\n\n"; 1195 | } 1196 | function _doBlockQuotes_callback2($matches) { 1197 | $pre = $matches[1]; 1198 | $pre = preg_replace('/^ /m', '', $pre); 1199 | return $pre; 1200 | } 1201 | 1202 | 1203 | function formParagraphs($text) { 1204 | # 1205 | # Params: 1206 | # $text - string to process with html

    tags 1207 | # 1208 | # Strip leading and trailing lines: 1209 | $text = preg_replace('/\A\n+|\n+\z/', '', $text); 1210 | 1211 | $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY); 1212 | 1213 | # 1214 | # Wrap

    tags and unhashify HTML blocks 1215 | # 1216 | foreach ($grafs as $key => $value) { 1217 | if (!preg_match('/^B\x1A[0-9]+B$/', $value)) { 1218 | # Is a paragraph. 1219 | $value = $this->runSpanGamut($value); 1220 | $value = preg_replace('/^([ ]*)/', "

    ", $value); 1221 | $value .= "

    "; 1222 | $grafs[$key] = $this->unhash($value); 1223 | } 1224 | else { 1225 | # Is a block. 1226 | # Modify elements of @grafs in-place... 1227 | $graf = $value; 1228 | $block = $this->html_hashes[$graf]; 1229 | $graf = $block; 1230 | // if (preg_match('{ 1231 | // \A 1232 | // ( # $1 =
    tag 1233 | //
    ]* 1235 | // \b 1236 | // markdown\s*=\s* ([\'"]) # $2 = attr quote char 1237 | // 1 1238 | // \2 1239 | // [^>]* 1240 | // > 1241 | // ) 1242 | // ( # $3 = contents 1243 | // .* 1244 | // ) 1245 | // (
    ) # $4 = closing tag 1246 | // \z 1247 | // }xs', $block, $matches)) 1248 | // { 1249 | // list(, $div_open, , $div_content, $div_close) = $matches; 1250 | // 1251 | // # We can't call Markdown(), because that resets the hash; 1252 | // # that initialization code should be pulled into its own sub, though. 1253 | // $div_content = $this->hashHTMLBlocks($div_content); 1254 | // 1255 | // # Run document gamut methods on the content. 1256 | // foreach ($this->document_gamut as $method => $priority) { 1257 | // $div_content = $this->$method($div_content); 1258 | // } 1259 | // 1260 | // $div_open = preg_replace( 1261 | // '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open); 1262 | // 1263 | // $graf = $div_open . "\n" . $div_content . "\n" . $div_close; 1264 | // } 1265 | $grafs[$key] = $graf; 1266 | } 1267 | } 1268 | 1269 | return implode("\n\n", $grafs); 1270 | } 1271 | 1272 | 1273 | function encodeAttribute($text) { 1274 | # 1275 | # Encode text for a double-quoted HTML attribute. This function 1276 | # is *not* suitable for attributes enclosed in single quotes. 1277 | # 1278 | $text = $this->encodeAmpsAndAngles($text); 1279 | $text = str_replace('"', '"', $text); 1280 | return $text; 1281 | } 1282 | 1283 | 1284 | function encodeAmpsAndAngles($text) { 1285 | # 1286 | # Smart processing for ampersands and angle brackets that need to 1287 | # be encoded. Valid character entities are left alone unless the 1288 | # no-entities mode is set. 1289 | # 1290 | if ($this->no_entities) { 1291 | $text = str_replace('&', '&', $text); 1292 | } else { 1293 | # Ampersand-encoding based entirely on Nat Irons's Amputator 1294 | # MT plugin: 1295 | $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/', 1296 | '&', $text);; 1297 | } 1298 | # Encode remaining <'s 1299 | $text = str_replace('<', '<', $text); 1300 | 1301 | return $text; 1302 | } 1303 | 1304 | 1305 | function doAutoLinks($text) { 1306 | $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i', 1307 | array(&$this, '_doAutoLinks_url_callback'), $text); 1308 | 1309 | # Email addresses: 1310 | $text = preg_replace_callback('{ 1311 | < 1312 | (?:mailto:)? 1313 | ( 1314 | (?: 1315 | [-!#$%&\'*+/=?^_`.{|}~\w\x80-\xFF]+ 1316 | | 1317 | ".*?" 1318 | ) 1319 | \@ 1320 | (?: 1321 | [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+ 1322 | | 1323 | \[[\d.a-fA-F:]+\] # IPv4 & IPv6 1324 | ) 1325 | ) 1326 | > 1327 | }xi', 1328 | array(&$this, '_doAutoLinks_email_callback'), $text); 1329 | 1330 | return $text; 1331 | } 1332 | function _doAutoLinks_url_callback($matches) { 1333 | $url = $this->encodeAttribute($matches[1]); 1334 | $link = "$url"; 1335 | return $this->hashPart($link); 1336 | } 1337 | function _doAutoLinks_email_callback($matches) { 1338 | $address = $matches[1]; 1339 | $link = $this->encodeEmailAddress($address); 1340 | return $this->hashPart($link); 1341 | } 1342 | 1343 | 1344 | function encodeEmailAddress($addr) { 1345 | # 1346 | # Input: an email address, e.g. "foo@example.com" 1347 | # 1348 | # Output: the email address as a mailto link, with each character 1349 | # of the address encoded as either a decimal or hex entity, in 1350 | # the hopes of foiling most address harvesting spam bots. E.g.: 1351 | # 1352 | #

    foo@exampl 1355 | # e.com

    1356 | # 1357 | # Based by a filter by Matthew Wickline, posted to BBEdit-Talk. 1358 | # With some optimizations by Milian Wolff. 1359 | # 1360 | $addr = "mailto:" . $addr; 1361 | $chars = preg_split('/(? $char) { 1365 | $ord = ord($char); 1366 | # Ignore non-ascii chars. 1367 | if ($ord < 128) { 1368 | $r = ($seed * (1 + $key)) % 100; # Pseudo-random function. 1369 | # roughly 10% raw, 45% hex, 45% dec 1370 | # '@' *must* be encoded. I insist. 1371 | if ($r > 90 && $char != '@') /* do nothing */; 1372 | else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';'; 1373 | else $chars[$key] = '&#'.$ord.';'; 1374 | } 1375 | } 1376 | 1377 | $addr = implode('', $chars); 1378 | $text = implode('', array_slice($chars, 7)); # text without `mailto:` 1379 | $addr = "$text"; 1380 | 1381 | return $addr; 1382 | } 1383 | 1384 | 1385 | function parseSpan($str) { 1386 | # 1387 | # Take the string $str and parse it into tokens, hashing embeded HTML, 1388 | # escaped characters and handling code spans. 1389 | # 1390 | $output = ''; 1391 | 1392 | $span_re = '{ 1393 | ( 1394 | \\\\'.$this->escape_chars_re.' 1395 | | 1396 | (?no_markup ? '' : ' 1399 | | 1400 | # comment 1401 | | 1402 | <\?.*?\?> | <%.*?%> # processing instruction 1403 | | 1404 | <[/!$]?[-a-zA-Z0-9:_]+ # regular tags 1405 | (?> 1406 | \s 1407 | (?>[^"\'>]+|"[^"]*"|\'[^\']*\')* 1408 | )? 1409 | > 1410 | ').' 1411 | ) 1412 | }xs'; 1413 | 1414 | while (1) { 1415 | # 1416 | # Each loop iteration seach for either the next tag, the next 1417 | # openning code span marker, or the next escaped character. 1418 | # Each token is then passed to handleSpanToken. 1419 | # 1420 | $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE); 1421 | 1422 | # Create token from text preceding tag. 1423 | if ($parts[0] != "") { 1424 | $output .= $parts[0]; 1425 | } 1426 | 1427 | # Check if we reach the end. 1428 | if (isset($parts[1])) { 1429 | $output .= $this->handleSpanToken($parts[1], $parts[2]); 1430 | $str = $parts[2]; 1431 | } 1432 | else { 1433 | break; 1434 | } 1435 | } 1436 | 1437 | return $output; 1438 | } 1439 | 1440 | 1441 | function handleSpanToken($token, &$str) { 1442 | # 1443 | # Handle $token provided by parseSpan by determining its nature and 1444 | # returning the corresponding value that should replace it. 1445 | # 1446 | switch ($token{0}) { 1447 | case "\\": 1448 | return $this->hashPart("&#". ord($token{1}). ";"); 1449 | case "`": 1450 | # Search for end marker in remaining text. 1451 | if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm', 1452 | $str, $matches)) 1453 | { 1454 | $str = $matches[2]; 1455 | $codespan = $this->makeCodeSpan($matches[1]); 1456 | return $this->hashPart($codespan); 1457 | } 1458 | return $token; // return as text since no ending marker found. 1459 | default: 1460 | return $this->hashPart($token); 1461 | } 1462 | } 1463 | 1464 | 1465 | function outdent($text) { 1466 | # 1467 | # Remove one level of line-leading tabs or spaces 1468 | # 1469 | return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text); 1470 | } 1471 | 1472 | 1473 | # String length function for detab. `_initDetab` will create a function to 1474 | # hanlde UTF-8 if the default function does not exist. 1475 | var $utf8_strlen = 'mb_strlen'; 1476 | 1477 | function detab($text) { 1478 | # 1479 | # Replace tabs with the appropriate amount of space. 1480 | # 1481 | # For each line we separate the line in blocks delemited by 1482 | # tab characters. Then we reconstruct every line by adding the 1483 | # appropriate number of space between each blocks. 1484 | 1485 | $text = preg_replace_callback('/^.*\t.*$/m', 1486 | array(&$this, '_detab_callback'), $text); 1487 | 1488 | return $text; 1489 | } 1490 | function _detab_callback($matches) { 1491 | $line = $matches[0]; 1492 | $strlen = $this->utf8_strlen; # strlen function for UTF-8. 1493 | 1494 | # Split in blocks. 1495 | $blocks = explode("\t", $line); 1496 | # Add each blocks to the line. 1497 | $line = $blocks[0]; 1498 | unset($blocks[0]); # Do not add first block twice. 1499 | foreach ($blocks as $block) { 1500 | # Calculate amount of space, insert spaces, insert block. 1501 | $amount = $this->tab_width - 1502 | $strlen($line, 'UTF-8') % $this->tab_width; 1503 | $line .= str_repeat(" ", $amount) . $block; 1504 | } 1505 | return $line; 1506 | } 1507 | function _initDetab() { 1508 | # 1509 | # Check for the availability of the function in the `utf8_strlen` property 1510 | # (initially `mb_strlen`). If the function is not available, create a 1511 | # function that will loosely count the number of UTF-8 characters with a 1512 | # regular expression. 1513 | # 1514 | if (function_exists($this->utf8_strlen)) return; 1515 | $this->utf8_strlen = create_function('$text', 'return preg_match_all( 1516 | "/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/", 1517 | $text, $m);'); 1518 | } 1519 | 1520 | 1521 | function unhash($text) { 1522 | # 1523 | # Swap back in all the tags hashed by _HashHTMLBlocks. 1524 | # 1525 | return preg_replace_callback('/(.)\x1A[0-9]+\1/', 1526 | array(&$this, '_unhash_callback'), $text); 1527 | } 1528 | function _unhash_callback($matches) { 1529 | return $this->html_hashes[$matches[0]]; 1530 | } 1531 | 1532 | } 1533 | 1534 | 1535 | # 1536 | # Markdown Extra Parser Class 1537 | # 1538 | 1539 | class MarkdownExtra_Parser extends Markdown_Parser { 1540 | 1541 | # Prefix for footnote ids. 1542 | var $fn_id_prefix = ""; 1543 | 1544 | # Optional title attribute for footnote links and backlinks. 1545 | var $fn_link_title = MARKDOWN_FN_LINK_TITLE; 1546 | var $fn_backlink_title = MARKDOWN_FN_BACKLINK_TITLE; 1547 | 1548 | # Optional class attribute for footnote links and backlinks. 1549 | var $fn_link_class = MARKDOWN_FN_LINK_CLASS; 1550 | var $fn_backlink_class = MARKDOWN_FN_BACKLINK_CLASS; 1551 | 1552 | # Predefined abbreviations. 1553 | var $predef_abbr = array(); 1554 | 1555 | 1556 | function MarkdownExtra_Parser() { 1557 | # 1558 | # Constructor function. Initialize the parser object. 1559 | # 1560 | # Add extra escapable characters before parent constructor 1561 | # initialize the table. 1562 | $this->escape_chars .= ':|'; 1563 | 1564 | # Insert extra document, block, and span transformations. 1565 | # Parent constructor will do the sorting. 1566 | $this->document_gamut += array( 1567 | "doFencedCodeBlocks" => 5, 1568 | "stripFootnotes" => 15, 1569 | "stripAbbreviations" => 25, 1570 | "appendFootnotes" => 50, 1571 | ); 1572 | $this->block_gamut += array( 1573 | "doFencedCodeBlocks" => 5, 1574 | "doTables" => 15, 1575 | "doDefLists" => 45, 1576 | ); 1577 | $this->span_gamut += array( 1578 | "doFootnotes" => 5, 1579 | "doAbbreviations" => 70, 1580 | ); 1581 | 1582 | parent::Markdown_Parser(); 1583 | } 1584 | 1585 | 1586 | # Extra variables used during extra transformations. 1587 | var $footnotes = array(); 1588 | var $footnotes_ordered = array(); 1589 | var $abbr_desciptions = array(); 1590 | var $abbr_word_re = ''; 1591 | 1592 | # Give the current footnote number. 1593 | var $footnote_counter = 1; 1594 | 1595 | 1596 | function setup() { 1597 | # 1598 | # Setting up Extra-specific variables. 1599 | # 1600 | parent::setup(); 1601 | 1602 | $this->footnotes = array(); 1603 | $this->footnotes_ordered = array(); 1604 | $this->abbr_desciptions = array(); 1605 | $this->abbr_word_re = ''; 1606 | $this->footnote_counter = 1; 1607 | 1608 | foreach ($this->predef_abbr as $abbr_word => $abbr_desc) { 1609 | if ($this->abbr_word_re) 1610 | $this->abbr_word_re .= '|'; 1611 | $this->abbr_word_re .= preg_quote($abbr_word); 1612 | $this->abbr_desciptions[$abbr_word] = trim($abbr_desc); 1613 | } 1614 | } 1615 | 1616 | function teardown() { 1617 | # 1618 | # Clearing Extra-specific variables. 1619 | # 1620 | $this->footnotes = array(); 1621 | $this->footnotes_ordered = array(); 1622 | $this->abbr_desciptions = array(); 1623 | $this->abbr_word_re = ''; 1624 | 1625 | parent::teardown(); 1626 | } 1627 | 1628 | 1629 | ### HTML Block Parser ### 1630 | 1631 | # Tags that are always treated as block tags: 1632 | var $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend'; 1633 | 1634 | # Tags treated as block tags only if the opening tag is alone on it's line: 1635 | var $context_block_tags_re = 'script|noscript|math|ins|del'; 1636 | 1637 | # Tags where markdown="1" default to span mode: 1638 | var $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address'; 1639 | 1640 | # Tags which must not have their contents modified, no matter where 1641 | # they appear: 1642 | var $clean_tags_re = 'script|math'; 1643 | 1644 | # Tags that do not need to be closed. 1645 | var $auto_close_tags_re = 'hr|img'; 1646 | 1647 | 1648 | function hashHTMLBlocks($text) { 1649 | # 1650 | # Hashify HTML Blocks and "clean tags". 1651 | # 1652 | # We only want to do this for block-level HTML tags, such as headers, 1653 | # lists, and tables. That's because we still want to wrap

    s around 1654 | # "paragraphs" that are wrapped in non-block-level tags, such as anchors, 1655 | # phrase emphasis, and spans. The list of tags we're looking for is 1656 | # hard-coded. 1657 | # 1658 | # This works by calling _HashHTMLBlocks_InMarkdown, which then calls 1659 | # _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1" 1660 | # attribute is found whitin a tag, _HashHTMLBlocks_InHTML calls back 1661 | # _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag. 1662 | # These two functions are calling each other. It's recursive! 1663 | # 1664 | # 1665 | # Call the HTML-in-Markdown hasher. 1666 | # 1667 | list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text); 1668 | 1669 | return $text; 1670 | } 1671 | function _hashHTMLBlocks_inMarkdown($text, $indent = 0, 1672 | $enclosing_tag_re = '', $span = false) 1673 | { 1674 | # 1675 | # Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags. 1676 | # 1677 | # * $indent is the number of space to be ignored when checking for code 1678 | # blocks. This is important because if we don't take the indent into 1679 | # account, something like this (which looks right) won't work as expected: 1680 | # 1681 | #

    1682 | #
    1683 | # Hello World. <-- Is this a Markdown code block or text? 1684 | #
    <-- Is this a Markdown code block or a real tag? 1685 | #
    1686 | # 1687 | # If you don't like this, just don't indent the tag on which 1688 | # you apply the markdown="1" attribute. 1689 | # 1690 | # * If $enclosing_tag_re is not empty, stops at the first unmatched closing 1691 | # tag with that name. Nested tags supported. 1692 | # 1693 | # * If $span is true, text inside must treated as span. So any double 1694 | # newline will be replaced by a single newline so that it does not create 1695 | # paragraphs. 1696 | # 1697 | # Returns an array of that form: ( processed text , remaining text ) 1698 | # 1699 | if ($text === '') return array('', ''); 1700 | 1701 | # Regex to check for the presense of newlines around a block tag. 1702 | $newline_before_re = '/(?:^\n?|\n\n)*$/'; 1703 | $newline_after_re = 1704 | '{ 1705 | ^ # Start of text following the tag. 1706 | (?>[ ]*)? # Optional comment. 1707 | [ ]*\n # Must be followed by newline. 1708 | }xs'; 1709 | 1710 | # Regex to match any tag. 1711 | $block_tag_re = 1712 | '{ 1713 | ( # $2: Capture hole tag. 1714 | # Tag name. 1716 | '.$this->block_tags_re.' | 1717 | '.$this->context_block_tags_re.' | 1718 | '.$this->clean_tags_re.' | 1719 | (?!\s)'.$enclosing_tag_re.' 1720 | ) 1721 | (?: 1722 | (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name. 1723 | (?> 1724 | ".*?" | # Double quotes (can contain `>`) 1725 | \'.*?\' | # Single quotes (can contain `>`) 1726 | .+? # Anything but quotes and `>`. 1727 | )*? 1728 | )? 1729 | > # End of tag. 1730 | | 1731 | # HTML Comment 1732 | | 1733 | <\?.*?\?> | <%.*?%> # Processing instruction 1734 | | 1735 | # CData Block 1736 | | 1737 | # Code span marker 1738 | `+ 1739 | '. ( !$span ? ' # If not in span. 1740 | | 1741 | # Indented code block 1742 | (?: ^[ ]*\n | ^ | \n[ ]*\n ) 1743 | [ ]{'.($indent+4).'}[^\n]* \n 1744 | (?> 1745 | (?: [ ]{'.($indent+4).'}[^\n]* | [ ]* ) \n 1746 | )* 1747 | | 1748 | # Fenced code block marker 1749 | (?> ^ | \n ) 1750 | [ ]{'.($indent).'}~~~+[ ]*\n 1751 | ' : '' ). ' # End (if not is span). 1752 | ) 1753 | }xs'; 1754 | 1755 | 1756 | $depth = 0; # Current depth inside the tag tree. 1757 | $parsed = ""; # Parsed text that will be returned. 1758 | 1759 | # 1760 | # Loop through every tag until we find the closing tag of the parent 1761 | # or loop until reaching the end of text if no parent tag specified. 1762 | # 1763 | do { 1764 | # 1765 | # Split the text using the first $tag_match pattern found. 1766 | # Text before pattern will be first in the array, text after 1767 | # pattern will be at the end, and between will be any catches made 1768 | # by the pattern. 1769 | # 1770 | $parts = preg_split($block_tag_re, $text, 2, 1771 | PREG_SPLIT_DELIM_CAPTURE); 1772 | 1773 | # If in Markdown span mode, add a empty-string span-level hash 1774 | # after each newline to prevent triggering any block element. 1775 | if ($span) { 1776 | $void = $this->hashPart("", ':'); 1777 | $newline = "$void\n"; 1778 | $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void; 1779 | } 1780 | 1781 | $parsed .= $parts[0]; # Text before current tag. 1782 | 1783 | # If end of $text has been reached. Stop loop. 1784 | if (count($parts) < 3) { 1785 | $text = ""; 1786 | break; 1787 | } 1788 | 1789 | $tag = $parts[1]; # Tag to handle. 1790 | $text = $parts[2]; # Remaining text after current tag. 1791 | $tag_re = preg_quote($tag); # For use in a regular expression. 1792 | 1793 | # 1794 | # Check for: Code span marker 1795 | # 1796 | if ($tag{0} == "`") { 1797 | # Find corresponding end marker. 1798 | $tag_re = preg_quote($tag); 1799 | if (preg_match('{^(?>.+?|\n(?!\n))*?(?.*\n)+?'.$tag_re.' *\n}', $text, 1826 | $matches)) 1827 | { 1828 | # End marker found: pass text unchanged until marker. 1829 | $parsed .= $tag . $matches[0]; 1830 | $text = substr($text, strlen($matches[0])); 1831 | } 1832 | else { 1833 | # No end marker: just skip it. 1834 | $parsed .= $tag; 1835 | } 1836 | } 1837 | # 1838 | # Check for: Opening Block level tag or 1839 | # Opening Context Block tag (like ins and del) 1840 | # used as a block tag (tag is alone on it's line). 1841 | # 1842 | else if (preg_match('{^<(?:'.$this->block_tags_re.')\b}', $tag) || 1843 | ( preg_match('{^<(?:'.$this->context_block_tags_re.')\b}', $tag) && 1844 | preg_match($newline_before_re, $parsed) && 1845 | preg_match($newline_after_re, $text) ) 1846 | ) 1847 | { 1848 | # Need to parse tag and following text using the HTML parser. 1849 | list($block_text, $text) = 1850 | $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true); 1851 | 1852 | # Make sure it stays outside of any paragraph by adding newlines. 1853 | $parsed .= "\n\n$block_text\n\n"; 1854 | } 1855 | # 1856 | # Check for: Clean tag (like script, math) 1857 | # HTML Comments, processing instructions. 1858 | # 1859 | else if (preg_match('{^<(?:'.$this->clean_tags_re.')\b}', $tag) || 1860 | $tag{1} == '!' || $tag{1} == '?') 1861 | { 1862 | # Need to parse tag and following text using the HTML parser. 1863 | # (don't check for markdown attribute) 1864 | list($block_text, $text) = 1865 | $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false); 1866 | 1867 | $parsed .= $block_text; 1868 | } 1869 | # 1870 | # Check for: Tag with same name as enclosing tag. 1871 | # 1872 | else if ($enclosing_tag_re !== '' && 1873 | # Same name as enclosing tag. 1874 | preg_match('{^= 0); 1897 | 1898 | return array($parsed, $text); 1899 | } 1900 | function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) { 1901 | # 1902 | # Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags. 1903 | # 1904 | # * Calls $hash_method to convert any blocks. 1905 | # * Stops when the first opening tag closes. 1906 | # * $md_attr indicate if the use of the `markdown="1"` attribute is allowed. 1907 | # (it is not inside clean tags) 1908 | # 1909 | # Returns an array of that form: ( processed text , remaining text ) 1910 | # 1911 | if ($text === '') return array('', ''); 1912 | 1913 | # Regex to match `markdown` attribute inside of a tag. 1914 | $markdown_attr_re = ' 1915 | { 1916 | \s* # Eat whitespace before the `markdown` attribute 1917 | markdown 1918 | \s*=\s* 1919 | (?> 1920 | (["\']) # $1: quote delimiter 1921 | (.*?) # $2: attribute value 1922 | \1 # matching delimiter 1923 | | 1924 | ([^\s>]*) # $3: unquoted attribute value 1925 | ) 1926 | () # $4: make $3 always defined (avoid warnings) 1927 | }xs'; 1928 | 1929 | # Regex to match any tag. 1930 | $tag_re = '{ 1931 | ( # $2: Capture hole tag. 1932 | 1937 | ".*?" | # Double quotes (can contain `>`) 1938 | \'.*?\' | # Single quotes (can contain `>`) 1939 | .+? # Anything but quotes and `>`. 1940 | )*? 1941 | )? 1942 | > # End of tag. 1943 | | 1944 | # HTML Comment 1945 | | 1946 | <\?.*?\?> | <%.*?%> # Processing instruction 1947 | | 1948 | # CData Block 1949 | ) 1950 | }xs'; 1951 | 1952 | $original_text = $text; # Save original text in case of faliure. 1953 | 1954 | $depth = 0; # Current depth inside the tag tree. 1955 | $block_text = ""; # Temporary text holder for current text. 1956 | $parsed = ""; # Parsed text that will be returned. 1957 | 1958 | # 1959 | # Get the name of the starting tag. 1960 | # (This pattern makes $base_tag_name_re safe without quoting.) 1961 | # 1962 | if (preg_match('/^<([\w:$]*)\b/', $text, $matches)) 1963 | $base_tag_name_re = $matches[1]; 1964 | 1965 | # 1966 | # Loop through every tag until we find the corresponding closing tag. 1967 | # 1968 | do { 1969 | # 1970 | # Split the text using the first $tag_match pattern found. 1971 | # Text before pattern will be first in the array, text after 1972 | # pattern will be at the end, and between will be any catches made 1973 | # by the pattern. 1974 | # 1975 | $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); 1976 | 1977 | if (count($parts) < 3) { 1978 | # 1979 | # End of $text reached with unbalenced tag(s). 1980 | # In that case, we return original text unchanged and pass the 1981 | # first character as filtered to prevent an infinite loop in the 1982 | # parent function. 1983 | # 1984 | return array($original_text{0}, substr($original_text, 1)); 1985 | } 1986 | 1987 | $block_text .= $parts[0]; # Text before current tag. 1988 | $tag = $parts[1]; # Tag to handle. 1989 | $text = $parts[2]; # Remaining text after current tag. 1990 | 1991 | # 1992 | # Check for: Auto-close tag (like
    ) 1993 | # Comments and Processing Instructions. 1994 | # 1995 | if (preg_match('{^auto_close_tags_re.')\b}', $tag) || 1996 | $tag{1} == '!' || $tag{1} == '?') 1997 | { 1998 | # Just add the tag to the block as if it was text. 1999 | $block_text .= $tag; 2000 | } 2001 | else { 2002 | # 2003 | # Increase/decrease nested tag count. Only do so if 2004 | # the tag's name match base tag's. 2005 | # 2006 | if (preg_match('{^mode = $attr_m[2] . $attr_m[3]; 2023 | $span_mode = $this->mode == 'span' || $this->mode != 'block' && 2024 | preg_match('{^<(?:'.$this->contain_span_tags_re.')\b}', $tag); 2025 | 2026 | # Calculate indent before tag. 2027 | if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) { 2028 | $strlen = $this->utf8_strlen; 2029 | $indent = $strlen($matches[1], 'UTF-8'); 2030 | } else { 2031 | $indent = 0; 2032 | } 2033 | 2034 | # End preceding block with this tag. 2035 | $block_text .= $tag; 2036 | $parsed .= $this->$hash_method($block_text); 2037 | 2038 | # Get enclosing tag name for the ParseMarkdown function. 2039 | # (This pattern makes $tag_name_re safe without quoting.) 2040 | preg_match('/^<([\w:$]*)\b/', $tag, $matches); 2041 | $tag_name_re = $matches[1]; 2042 | 2043 | # Parse the content using the HTML-in-Markdown parser. 2044 | list ($block_text, $text) 2045 | = $this->_hashHTMLBlocks_inMarkdown($text, $indent, 2046 | $tag_name_re, $span_mode); 2047 | 2048 | # Outdent markdown text. 2049 | if ($indent > 0) { 2050 | $block_text = preg_replace("/^[ ]{1,$indent}/m", "", 2051 | $block_text); 2052 | } 2053 | 2054 | # Append tag content to parsed text. 2055 | if (!$span_mode) $parsed .= "\n\n$block_text\n\n"; 2056 | else $parsed .= "$block_text"; 2057 | 2058 | # Start over a new block. 2059 | $block_text = ""; 2060 | } 2061 | else $block_text .= $tag; 2062 | } 2063 | 2064 | } while ($depth > 0); 2065 | 2066 | # 2067 | # Hash last block text that wasn't processed inside the loop. 2068 | # 2069 | $parsed .= $this->$hash_method($block_text); 2070 | 2071 | return array($parsed, $text); 2072 | } 2073 | 2074 | 2075 | function hashClean($text) { 2076 | # 2077 | # Called whenever a tag must be hashed when a function insert a "clean" tag 2078 | # in $text, it pass through this function and is automaticaly escaped, 2079 | # blocking invalid nested overlap. 2080 | # 2081 | return $this->hashPart($text, 'C'); 2082 | } 2083 | 2084 | 2085 | function doHeaders($text) { 2086 | # 2087 | # Redefined to add id attribute support. 2088 | # 2089 | # Setext-style headers: 2090 | # Header 1 {#header1} 2091 | # ======== 2092 | # 2093 | # Header 2 {#header2} 2094 | # -------- 2095 | # 2096 | $text = preg_replace_callback( 2097 | '{ 2098 | (^.+?) # $1: Header text 2099 | (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # $2: Id attribute 2100 | [ ]*\n(=+|-+)[ ]*\n+ # $3: Header footer 2101 | }mx', 2102 | array(&$this, '_doHeaders_callback_setext'), $text); 2103 | 2104 | # atx-style headers: 2105 | # # Header 1 {#header1} 2106 | # ## Header 2 {#header2} 2107 | # ## Header 2 with closing hashes ## {#header3} 2108 | # ... 2109 | # ###### Header 6 {#header2} 2110 | # 2111 | $text = preg_replace_callback('{ 2112 | ^(\#{1,6}) # $1 = string of #\'s 2113 | [ ]* 2114 | (.+?) # $2 = Header text 2115 | [ ]* 2116 | \#* # optional closing #\'s (not counted) 2117 | (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # id attribute 2118 | [ ]* 2119 | \n+ 2120 | }xm', 2121 | array(&$this, '_doHeaders_callback_atx'), $text); 2122 | 2123 | return $text; 2124 | } 2125 | function _doHeaders_attr($attr) { 2126 | if (empty($attr)) return ""; 2127 | return " id=\"$attr\""; 2128 | } 2129 | function _doHeaders_callback_setext($matches) { 2130 | if ($matches[3] == '-' && preg_match('{^- }', $matches[1])) 2131 | return $matches[0]; 2132 | $level = $matches[3]{0} == '=' ? 1 : 2; 2133 | $attr = $this->_doHeaders_attr($id =& $matches[2]); 2134 | $block = "".$this->runSpanGamut($matches[1]).""; 2135 | return "\n" . $this->hashBlock($block) . "\n\n"; 2136 | } 2137 | function _doHeaders_callback_atx($matches) { 2138 | $level = strlen($matches[1]); 2139 | $attr = $this->_doHeaders_attr($id =& $matches[3]); 2140 | $block = "".$this->runSpanGamut($matches[2]).""; 2141 | return "\n" . $this->hashBlock($block) . "\n\n"; 2142 | } 2143 | 2144 | 2145 | function doTables($text) { 2146 | # 2147 | # Form HTML tables. 2148 | # 2149 | $less_than_tab = $this->tab_width - 1; 2150 | # 2151 | # Find tables with leading pipe. 2152 | # 2153 | # | Header 1 | Header 2 2154 | # | -------- | -------- 2155 | # | Cell 1 | Cell 2 2156 | # | Cell 3 | Cell 4 2157 | # 2158 | $text = preg_replace_callback(' 2159 | { 2160 | ^ # Start of a line 2161 | [ ]{0,'.$less_than_tab.'} # Allowed whitespace. 2162 | [|] # Optional leading pipe (present) 2163 | (.+) \n # $1: Header row (at least one pipe) 2164 | 2165 | [ ]{0,'.$less_than_tab.'} # Allowed whitespace. 2166 | [|] ([ ]*[-:]+[-| :]*) \n # $2: Header underline 2167 | 2168 | ( # $3: Cells 2169 | (?> 2170 | [ ]* # Allowed whitespace. 2171 | [|] .* \n # Row content. 2172 | )* 2173 | ) 2174 | (?=\n|\Z) # Stop at final double newline. 2175 | }xm', 2176 | array(&$this, '_doTable_leadingPipe_callback'), $text); 2177 | 2178 | # 2179 | # Find tables without leading pipe. 2180 | # 2181 | # Header 1 | Header 2 2182 | # -------- | -------- 2183 | # Cell 1 | Cell 2 2184 | # Cell 3 | Cell 4 2185 | # 2186 | $text = preg_replace_callback(' 2187 | { 2188 | ^ # Start of a line 2189 | [ ]{0,'.$less_than_tab.'} # Allowed whitespace. 2190 | (\S.*[|].*) \n # $1: Header row (at least one pipe) 2191 | 2192 | [ ]{0,'.$less_than_tab.'} # Allowed whitespace. 2193 | ([-:]+[ ]*[|][-| :]*) \n # $2: Header underline 2194 | 2195 | ( # $3: Cells 2196 | (?> 2197 | .* [|] .* \n # Row content 2198 | )* 2199 | ) 2200 | (?=\n|\Z) # Stop at final double newline. 2201 | }xm', 2202 | array(&$this, '_DoTable_callback'), $text); 2203 | 2204 | return $text; 2205 | } 2206 | function _doTable_leadingPipe_callback($matches) { 2207 | $head = $matches[1]; 2208 | $underline = $matches[2]; 2209 | $content = $matches[3]; 2210 | 2211 | # Remove leading pipe for each row. 2212 | $content = preg_replace('/^ *[|]/m', '', $content); 2213 | 2214 | return $this->_doTable_callback(array($matches[0], $head, $underline, $content)); 2215 | } 2216 | function _doTable_callback($matches) { 2217 | $head = $matches[1]; 2218 | $underline = $matches[2]; 2219 | $content = $matches[3]; 2220 | 2221 | # Remove any tailing pipes for each line. 2222 | $head = preg_replace('/[|] *$/m', '', $head); 2223 | $underline = preg_replace('/[|] *$/m', '', $underline); 2224 | $content = preg_replace('/[|] *$/m', '', $content); 2225 | 2226 | # Reading alignement from header underline. 2227 | $separators = preg_split('/ *[|] */', $underline); 2228 | foreach ($separators as $n => $s) { 2229 | if (preg_match('/^ *-+: *$/', $s)) $attr[$n] = ' align="right"'; 2230 | else if (preg_match('/^ *:-+: *$/', $s))$attr[$n] = ' align="center"'; 2231 | else if (preg_match('/^ *:-+ *$/', $s)) $attr[$n] = ' align="left"'; 2232 | else $attr[$n] = ''; 2233 | } 2234 | 2235 | # Parsing span elements, including code spans, character escapes, 2236 | # and inline HTML tags, so that pipes inside those gets ignored. 2237 | $head = $this->parseSpan($head); 2238 | $headers = preg_split('/ *[|] */', $head); 2239 | $col_count = count($headers); 2240 | 2241 | # Write column headers. 2242 | $text = "\n"; 2243 | $text .= "\n"; 2244 | $text .= "\n"; 2245 | foreach ($headers as $n => $header) 2246 | $text .= " ".$this->runSpanGamut(trim($header))."\n"; 2247 | $text .= "\n"; 2248 | $text .= "\n"; 2249 | 2250 | # Split content by row. 2251 | $rows = explode("\n", trim($content, "\n")); 2252 | 2253 | $text .= "\n"; 2254 | foreach ($rows as $row) { 2255 | # Parsing span elements, including code spans, character escapes, 2256 | # and inline HTML tags, so that pipes inside those gets ignored. 2257 | $row = $this->parseSpan($row); 2258 | 2259 | # Split row by cell. 2260 | $row_cells = preg_split('/ *[|] */', $row, $col_count); 2261 | $row_cells = array_pad($row_cells, $col_count, ''); 2262 | 2263 | $text .= "\n"; 2264 | foreach ($row_cells as $n => $cell) 2265 | $text .= " ".$this->runSpanGamut(trim($cell))."\n"; 2266 | $text .= "\n"; 2267 | } 2268 | $text .= "\n"; 2269 | $text .= "
    "; 2270 | 2271 | return $this->hashBlock($text) . "\n"; 2272 | } 2273 | 2274 | 2275 | function doDefLists($text) { 2276 | # 2277 | # Form HTML definition lists. 2278 | # 2279 | $less_than_tab = $this->tab_width - 1; 2280 | 2281 | # Re-usable pattern to match any entire dl list: 2282 | $whole_list_re = '(?> 2283 | ( # $1 = whole list 2284 | ( # $2 2285 | [ ]{0,'.$less_than_tab.'} 2286 | ((?>.*\S.*\n)+) # $3 = defined term 2287 | \n? 2288 | [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition 2289 | ) 2290 | (?s:.+?) 2291 | ( # $4 2292 | \z 2293 | | 2294 | \n{2,} 2295 | (?=\S) 2296 | (?! # Negative lookahead for another term 2297 | [ ]{0,'.$less_than_tab.'} 2298 | (?: \S.*\n )+? # defined term 2299 | \n? 2300 | [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition 2301 | ) 2302 | (?! # Negative lookahead for another definition 2303 | [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition 2304 | ) 2305 | ) 2306 | ) 2307 | )'; // mx 2308 | 2309 | $text = preg_replace_callback('{ 2310 | (?>\A\n?|(?<=\n\n)) 2311 | '.$whole_list_re.' 2312 | }mx', 2313 | array(&$this, '_doDefLists_callback'), $text); 2314 | 2315 | return $text; 2316 | } 2317 | function _doDefLists_callback($matches) { 2318 | # Re-usable patterns to match list item bullets and number markers: 2319 | $list = $matches[1]; 2320 | 2321 | # Turn double returns into triple returns, so that we can make a 2322 | # paragraph for the last item in a list, if necessary: 2323 | $result = trim($this->processDefListItems($list)); 2324 | $result = "
    \n" . $result . "\n
    "; 2325 | return $this->hashBlock($result) . "\n\n"; 2326 | } 2327 | 2328 | 2329 | function processDefListItems($list_str) { 2330 | # 2331 | # Process the contents of a single definition list, splitting it 2332 | # into individual term and definition list items. 2333 | # 2334 | $less_than_tab = $this->tab_width - 1; 2335 | 2336 | # trim trailing blank lines: 2337 | $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str); 2338 | 2339 | # Process definition terms. 2340 | $list_str = preg_replace_callback('{ 2341 | (?>\A\n?|\n\n+) # leading line 2342 | ( # definition terms = $1 2343 | [ ]{0,'.$less_than_tab.'} # leading whitespace 2344 | (?![:][ ]|[ ]) # negative lookahead for a definition 2345 | # mark (colon) or more whitespace. 2346 | (?> \S.* \n)+? # actual term (not whitespace). 2347 | ) 2348 | (?=\n?[ ]{0,3}:[ ]) # lookahead for following line feed 2349 | # with a definition mark. 2350 | }xm', 2351 | array(&$this, '_processDefListItems_callback_dt'), $list_str); 2352 | 2353 | # Process actual definitions. 2354 | $list_str = preg_replace_callback('{ 2355 | \n(\n+)? # leading line = $1 2356 | ( # marker space = $2 2357 | [ ]{0,'.$less_than_tab.'} # whitespace before colon 2358 | [:][ ]+ # definition mark (colon) 2359 | ) 2360 | ((?s:.+?)) # definition text = $3 2361 | (?= \n+ # stop at next definition mark, 2362 | (?: # next term or end of text 2363 | [ ]{0,'.$less_than_tab.'} [:][ ] | 2364 |
    | \z 2365 | ) 2366 | ) 2367 | }xm', 2368 | array(&$this, '_processDefListItems_callback_dd'), $list_str); 2369 | 2370 | return $list_str; 2371 | } 2372 | function _processDefListItems_callback_dt($matches) { 2373 | $terms = explode("\n", trim($matches[1])); 2374 | $text = ''; 2375 | foreach ($terms as $term) { 2376 | $term = $this->runSpanGamut(trim($term)); 2377 | $text .= "\n
    " . $term . "
    "; 2378 | } 2379 | return $text . "\n"; 2380 | } 2381 | function _processDefListItems_callback_dd($matches) { 2382 | $leading_line = $matches[1]; 2383 | $marker_space = $matches[2]; 2384 | $def = $matches[3]; 2385 | 2386 | if ($leading_line || preg_match('/\n{2,}/', $def)) { 2387 | # Replace marker with the appropriate whitespace indentation 2388 | $def = str_repeat(' ', strlen($marker_space)) . $def; 2389 | $def = $this->runBlockGamut($this->outdent($def . "\n\n")); 2390 | $def = "\n". $def ."\n"; 2391 | } 2392 | else { 2393 | $def = rtrim($def); 2394 | $def = $this->runSpanGamut($this->outdent($def)); 2395 | } 2396 | 2397 | return "\n
    " . $def . "
    \n"; 2398 | } 2399 | 2400 | 2401 | function doFencedCodeBlocks($text) { 2402 | # 2403 | # Adding the fenced code block syntax to regular Markdown: 2404 | # 2405 | # ~~~ 2406 | # Code block 2407 | # ~~~ 2408 | # 2409 | $less_than_tab = $this->tab_width; 2410 | 2411 | $text = preg_replace_callback('{ 2412 | (?:\n|\A) 2413 | # 1: Opening marker 2414 | ( 2415 | ~{3,} # Marker: three tilde or more. 2416 | ) 2417 | [ ]* \n # Whitespace and newline following marker. 2418 | 2419 | # 2: Content 2420 | ( 2421 | (?> 2422 | (?!\1 [ ]* \n) # Not a closing marker. 2423 | .*\n+ 2424 | )+ 2425 | ) 2426 | 2427 | # Closing marker. 2428 | \1 [ ]* \n 2429 | }xm', 2430 | array(&$this, '_doFencedCodeBlocks_callback'), $text); 2431 | 2432 | return $text; 2433 | } 2434 | function _doFencedCodeBlocks_callback($matches) { 2435 | $codeblock = $matches[2]; 2436 | $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES); 2437 | $codeblock = preg_replace_callback('/^\n+/', 2438 | array(&$this, '_doFencedCodeBlocks_newlines'), $codeblock); 2439 | $codeblock = "
    $codeblock
    "; 2440 | return "\n\n".$this->hashBlock($codeblock)."\n\n"; 2441 | } 2442 | function _doFencedCodeBlocks_newlines($matches) { 2443 | return str_repeat("empty_element_suffix", 2444 | strlen($matches[0])); 2445 | } 2446 | 2447 | 2448 | # 2449 | # Redefining emphasis markers so that emphasis by underscore does not 2450 | # work in the middle of a word. 2451 | # 2452 | var $em_relist = array( 2453 | '' => '(?:(? '(?<=\S|^)(? '(?<=\S|^)(? '(?:(? '(?<=\S|^)(? '(?<=\S|^)(? '(?:(? '(?<=\S|^)(? '(?<=\S|^)(? tags 2473 | # 2474 | # Strip leading and trailing lines: 2475 | $text = preg_replace('/\A\n+|\n+\z/', '', $text); 2476 | 2477 | $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY); 2478 | 2479 | # 2480 | # Wrap

    tags and unhashify HTML blocks 2481 | # 2482 | foreach ($grafs as $key => $value) { 2483 | $value = trim($this->runSpanGamut($value)); 2484 | 2485 | # Check if this should be enclosed in a paragraph. 2486 | # Clean tag hashes & block tag hashes are left alone. 2487 | $is_p = !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value); 2488 | 2489 | if ($is_p) { 2490 | $value = "

    $value

    "; 2491 | } 2492 | $grafs[$key] = $value; 2493 | } 2494 | 2495 | # Join grafs in one text, then unhash HTML tags. 2496 | $text = implode("\n\n", $grafs); 2497 | 2498 | # Finish by removing any tag hashes still present in $text. 2499 | $text = $this->unhash($text); 2500 | 2501 | return $text; 2502 | } 2503 | 2504 | 2505 | ### Footnotes 2506 | 2507 | function stripFootnotes($text) { 2508 | # 2509 | # Strips link definitions from text, stores the URLs and titles in 2510 | # hash references. 2511 | # 2512 | $less_than_tab = $this->tab_width - 1; 2513 | 2514 | # Link defs are in the form: [^id]: url "optional title" 2515 | $text = preg_replace_callback('{ 2516 | ^[ ]{0,'.$less_than_tab.'}\[\^(.+?)\][ ]?: # note_id = $1 2517 | [ ]* 2518 | \n? # maybe *one* newline 2519 | ( # text = $2 (no blank lines allowed) 2520 | (?: 2521 | .+ # actual text 2522 | | 2523 | \n # newlines but 2524 | (?!\[\^.+?\]:\s)# negative lookahead for footnote marker. 2525 | (?!\n+[ ]{0,3}\S)# ensure line is not blank and followed 2526 | # by non-indented content 2527 | )* 2528 | ) 2529 | }xm', 2530 | array(&$this, '_stripFootnotes_callback'), 2531 | $text); 2532 | return $text; 2533 | } 2534 | function _stripFootnotes_callback($matches) { 2535 | $note_id = $this->fn_id_prefix . $matches[1]; 2536 | $this->footnotes[$note_id] = $this->outdent($matches[2]); 2537 | return ''; # String that will replace the block 2538 | } 2539 | 2540 | 2541 | function doFootnotes($text) { 2542 | # 2543 | # Replace footnote references in $text [^id] with a special text-token 2544 | # which will be replaced by the actual footnote marker in appendFootnotes. 2545 | # 2546 | if (!$this->in_anchor) { 2547 | $text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text); 2548 | } 2549 | return $text; 2550 | } 2551 | 2552 | 2553 | function appendFootnotes($text) { 2554 | # 2555 | # Append footnote list to text. 2556 | # 2557 | $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}', 2558 | array(&$this, '_appendFootnotes_callback'), $text); 2559 | 2560 | if (!empty($this->footnotes_ordered)) { 2561 | $text .= "\n\n"; 2562 | $text .= "
    \n"; 2563 | $text .= "empty_element_suffix ."\n"; 2564 | $text .= "
      \n\n"; 2565 | 2566 | $attr = " rev=\"footnote\""; 2567 | if ($this->fn_backlink_class != "") { 2568 | $class = $this->fn_backlink_class; 2569 | $class = $this->encodeAttribute($class); 2570 | $attr .= " class=\"$class\""; 2571 | } 2572 | if ($this->fn_backlink_title != "") { 2573 | $title = $this->fn_backlink_title; 2574 | $title = $this->encodeAttribute($title); 2575 | $attr .= " title=\"$title\""; 2576 | } 2577 | $num = 0; 2578 | 2579 | while (!empty($this->footnotes_ordered)) { 2580 | $footnote = reset($this->footnotes_ordered); 2581 | $note_id = key($this->footnotes_ordered); 2582 | unset($this->footnotes_ordered[$note_id]); 2583 | 2584 | $footnote .= "\n"; # Need to append newline before parsing. 2585 | $footnote = $this->runBlockGamut("$footnote\n"); 2586 | $footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}', 2587 | array(&$this, '_appendFootnotes_callback'), $footnote); 2588 | 2589 | $attr = str_replace("%%", ++$num, $attr); 2590 | $note_id = $this->encodeAttribute($note_id); 2591 | 2592 | # Add backlink to last paragraph; create new paragraph if needed. 2593 | $backlink = ""; 2594 | if (preg_match('{

      $}', $footnote)) { 2595 | $footnote = substr($footnote, 0, -4) . " $backlink

      "; 2596 | } else { 2597 | $footnote .= "\n\n

      $backlink

      "; 2598 | } 2599 | 2600 | $text .= "
    1. \n"; 2601 | $text .= $footnote . "\n"; 2602 | $text .= "
    2. \n\n"; 2603 | } 2604 | 2605 | $text .= "
    \n"; 2606 | $text .= "
    "; 2607 | } 2608 | return $text; 2609 | } 2610 | function _appendFootnotes_callback($matches) { 2611 | $node_id = $this->fn_id_prefix . $matches[1]; 2612 | 2613 | # Create footnote marker only if it has a corresponding footnote *and* 2614 | # the footnote hasn't been used by another marker. 2615 | if (isset($this->footnotes[$node_id])) { 2616 | # Transfert footnote content to the ordered list. 2617 | $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id]; 2618 | unset($this->footnotes[$node_id]); 2619 | 2620 | $num = $this->footnote_counter++; 2621 | $attr = " rel=\"footnote\""; 2622 | if ($this->fn_link_class != "") { 2623 | $class = $this->fn_link_class; 2624 | $class = $this->encodeAttribute($class); 2625 | $attr .= " class=\"$class\""; 2626 | } 2627 | if ($this->fn_link_title != "") { 2628 | $title = $this->fn_link_title; 2629 | $title = $this->encodeAttribute($title); 2630 | $attr .= " title=\"$title\""; 2631 | } 2632 | 2633 | $attr = str_replace("%%", $num, $attr); 2634 | $node_id = $this->encodeAttribute($node_id); 2635 | 2636 | return 2637 | "". 2638 | "$num". 2639 | ""; 2640 | } 2641 | 2642 | return "[^".$matches[1]."]"; 2643 | } 2644 | 2645 | 2646 | ### Abbreviations ### 2647 | 2648 | function stripAbbreviations($text) { 2649 | # 2650 | # Strips abbreviations from text, stores titles in hash references. 2651 | # 2652 | $less_than_tab = $this->tab_width - 1; 2653 | 2654 | # Link defs are in the form: [id]*: url "optional title" 2655 | $text = preg_replace_callback('{ 2656 | ^[ ]{0,'.$less_than_tab.'}\*\[(.+?)\][ ]?: # abbr_id = $1 2657 | (.*) # text = $2 (no blank lines allowed) 2658 | }xm', 2659 | array(&$this, '_stripAbbreviations_callback'), 2660 | $text); 2661 | return $text; 2662 | } 2663 | function _stripAbbreviations_callback($matches) { 2664 | $abbr_word = $matches[1]; 2665 | $abbr_desc = $matches[2]; 2666 | if ($this->abbr_word_re) 2667 | $this->abbr_word_re .= '|'; 2668 | $this->abbr_word_re .= preg_quote($abbr_word); 2669 | $this->abbr_desciptions[$abbr_word] = trim($abbr_desc); 2670 | return ''; # String that will replace the block 2671 | } 2672 | 2673 | 2674 | function doAbbreviations($text) { 2675 | # 2676 | # Find defined abbreviations in text and wrap them in elements. 2677 | # 2678 | if ($this->abbr_word_re) { 2679 | // cannot use the /x modifier because abbr_word_re may 2680 | // contain significant spaces: 2681 | $text = preg_replace_callback('{'. 2682 | '(?abbr_word_re.')'. 2684 | '(?![\w\x1A])'. 2685 | '}', 2686 | array(&$this, '_doAbbreviations_callback'), $text); 2687 | } 2688 | return $text; 2689 | } 2690 | function _doAbbreviations_callback($matches) { 2691 | $abbr = $matches[0]; 2692 | if (isset($this->abbr_desciptions[$abbr])) { 2693 | $desc = $this->abbr_desciptions[$abbr]; 2694 | if (empty($desc)) { 2695 | return $this->hashPart("$abbr"); 2696 | } else { 2697 | $desc = $this->encodeAttribute($desc); 2698 | return $this->hashPart("$abbr"); 2699 | } 2700 | } else { 2701 | return $matches[0]; 2702 | } 2703 | } 2704 | 2705 | } 2706 | 2707 | 2708 | /* 2709 | 2710 | PHP Markdown Extra 2711 | ================== 2712 | 2713 | Description 2714 | ----------- 2715 | 2716 | This is a PHP port of the original Markdown formatter written in Perl 2717 | by John Gruber. This special "Extra" version of PHP Markdown features 2718 | further enhancements to the syntax for making additional constructs 2719 | such as tables and definition list. 2720 | 2721 | Markdown is a text-to-HTML filter; it translates an easy-to-read / 2722 | easy-to-write structured text format into HTML. Markdown's text format 2723 | is most similar to that of plain text email, and supports features such 2724 | as headers, *emphasis*, code blocks, blockquotes, and links. 2725 | 2726 | Markdown's syntax is designed not as a generic markup language, but 2727 | specifically to serve as a front-end to (X)HTML. You can use span-level 2728 | HTML tags anywhere in a Markdown document, and you can use block level 2729 | HTML tags (like
    and as well). 2730 | 2731 | For more information about Markdown's syntax, see: 2732 | 2733 | 2734 | 2735 | 2736 | Bugs 2737 | ---- 2738 | 2739 | To file bug reports please send email to: 2740 | 2741 | 2742 | 2743 | Please include with your report: (1) the example input; (2) the output you 2744 | expected; (3) the output Markdown actually produced. 2745 | 2746 | 2747 | Version History 2748 | --------------- 2749 | 2750 | See the readme file for detailed release notes for this version. 2751 | 2752 | 2753 | Copyright and License 2754 | --------------------- 2755 | 2756 | PHP Markdown & Extra 2757 | Copyright (c) 2004-2009 Michel Fortin 2758 | 2759 | All rights reserved. 2760 | 2761 | Based on Markdown 2762 | Copyright (c) 2003-2006 John Gruber 2763 | 2764 | All rights reserved. 2765 | 2766 | Redistribution and use in source and binary forms, with or without 2767 | modification, are permitted provided that the following conditions are 2768 | met: 2769 | 2770 | * Redistributions of source code must retain the above copyright notice, 2771 | this list of conditions and the following disclaimer. 2772 | 2773 | * Redistributions in binary form must reproduce the above copyright 2774 | notice, this list of conditions and the following disclaimer in the 2775 | documentation and/or other materials provided with the distribution. 2776 | 2777 | * Neither the name "Markdown" nor the names of its contributors may 2778 | be used to endorse or promote products derived from this software 2779 | without specific prior written permission. 2780 | 2781 | This software is provided by the copyright holders and contributors "as 2782 | is" and any express or implied warranties, including, but not limited 2783 | to, the implied warranties of merchantability and fitness for a 2784 | particular purpose are disclaimed. In no event shall the copyright owner 2785 | or contributors be liable for any direct, indirect, incidental, special, 2786 | exemplary, or consequential damages (including, but not limited to, 2787 | procurement of substitute goods or services; loss of use, data, or 2788 | profits; or business interruption) however caused and on any theory of 2789 | liability, whether in contract, strict liability, or tort (including 2790 | negligence or otherwise) arising in any way out of the use of this 2791 | software, even if advised of the possibility of such damage. 2792 | 2793 | */ 2794 | ?> --------------------------------------------------------------------------------