markdown.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  1. <?php
  2. #
  3. # Markdown - A text-to-HTML conversion tool for web writers
  4. #
  5. # PHP Markdown
  6. # Copyright (c) 2004-2012 Michel Fortin
  7. # <http://michelf.com/projects/php-markdown/>
  8. #
  9. # Original Markdown
  10. # Copyright (c) 2004-2006 John Gruber
  11. # <http://daringfireball.net/projects/markdown/>
  12. #
  13. define( 'MARKDOWN_VERSION', "1.0.1o" ); # Sun 8 Jan 2012
  14. #
  15. # Global default settings:
  16. #
  17. # Change to ">" for HTML output
  18. @define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX', " />");
  19. # Define the width of a tab for code blocks.
  20. @define( 'MARKDOWN_TAB_WIDTH', 4 );
  21. #
  22. # WordPress settings:
  23. #
  24. # Change to false to remove Markdown from posts and/or comments.
  25. @define( 'MARKDOWN_WP_POSTS', true );
  26. @define( 'MARKDOWN_WP_COMMENTS', true );
  27. ### Standard Function Interface ###
  28. @define( 'MARKDOWN_PARSER_CLASS', 'Markdown_Parser' );
  29. function Markdown($text) {
  30. #
  31. # Initialize the parser and return the result of its transform method.
  32. #
  33. # Setup static parser variable.
  34. static $parser;
  35. if (!isset($parser)) {
  36. $parser_class = MARKDOWN_PARSER_CLASS;
  37. $parser = new $parser_class;
  38. }
  39. # Transform text using parser.
  40. return $parser->transform($text);
  41. }
  42. ### WordPress Plugin Interface ###
  43. /*
  44. Plugin Name: Markdown
  45. Plugin URI: http://michelf.com/projects/php-markdown/
  46. Description: <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by <a href="http://daringfireball.net/">John Gruber</a>. <a href="http://michelf.com/projects/php-markdown/">More...</a>
  47. Version: 1.0.1o
  48. Author: Michel Fortin
  49. Author URI: http://michelf.com/
  50. */
  51. if (isset($wp_version)) {
  52. # More details about how it works here:
  53. # <http://michelf.com/weblog/2005/wordpress-text-flow-vs-markdown/>
  54. # Post content and excerpts
  55. # - Remove WordPress paragraph generator.
  56. # - Run Markdown on excerpt, then remove all tags.
  57. # - Add paragraph tag around the excerpt, but remove it for the excerpt rss.
  58. if (MARKDOWN_WP_POSTS) {
  59. remove_filter('the_content', 'wpautop');
  60. remove_filter('the_content_rss', 'wpautop');
  61. remove_filter('the_excerpt', 'wpautop');
  62. add_filter('the_content', 'Markdown', 6);
  63. add_filter('the_content_rss', 'Markdown', 6);
  64. add_filter('get_the_excerpt', 'Markdown', 6);
  65. add_filter('get_the_excerpt', 'trim', 7);
  66. add_filter('the_excerpt', 'mdwp_add_p');
  67. add_filter('the_excerpt_rss', 'mdwp_strip_p');
  68. remove_filter('content_save_pre', 'balanceTags', 50);
  69. remove_filter('excerpt_save_pre', 'balanceTags', 50);
  70. add_filter('the_content', 'balanceTags', 50);
  71. add_filter('get_the_excerpt', 'balanceTags', 9);
  72. }
  73. # Comments
  74. # - Remove WordPress paragraph generator.
  75. # - Remove WordPress auto-link generator.
  76. # - Scramble important tags before passing them to the kses filter.
  77. # - Run Markdown on excerpt then remove paragraph tags.
  78. if (MARKDOWN_WP_COMMENTS) {
  79. remove_filter('comment_text', 'wpautop', 30);
  80. remove_filter('comment_text', 'make_clickable');
  81. add_filter('pre_comment_content', 'Markdown', 6);
  82. add_filter('pre_comment_content', 'mdwp_hide_tags', 8);
  83. add_filter('pre_comment_content', 'mdwp_show_tags', 12);
  84. add_filter('get_comment_text', 'Markdown', 6);
  85. add_filter('get_comment_excerpt', 'Markdown', 6);
  86. add_filter('get_comment_excerpt', 'mdwp_strip_p', 7);
  87. global $mdwp_hidden_tags, $mdwp_placeholders;
  88. $mdwp_hidden_tags = explode(' ',
  89. '<p> </p> <pre> </pre> <ol> </ol> <ul> </ul> <li> </li>');
  90. $mdwp_placeholders = explode(' ', str_rot13(
  91. 'pEj07ZbbBZ U1kqgh4w4p pre2zmeN6K QTi31t9pre ol0MP1jzJR '.
  92. 'ML5IjmbRol ulANi1NsGY J7zRLJqPul liA8ctl16T K9nhooUHli'));
  93. }
  94. function mdwp_add_p($text) {
  95. if (!preg_match('{^$|^<(p|ul|ol|dl|pre|blockquote)>}i', $text)) {
  96. $text = '<p>'.$text.'</p>';
  97. $text = preg_replace('{\n{2,}}', "</p>\n\n<p>", $text);
  98. }
  99. return $text;
  100. }
  101. function mdwp_strip_p($t) { return preg_replace('{</?p>}i', '', $t); }
  102. function mdwp_hide_tags($text) {
  103. global $mdwp_hidden_tags, $mdwp_placeholders;
  104. return str_replace($mdwp_hidden_tags, $mdwp_placeholders, $text);
  105. }
  106. function mdwp_show_tags($text) {
  107. global $mdwp_hidden_tags, $mdwp_placeholders;
  108. return str_replace($mdwp_placeholders, $mdwp_hidden_tags, $text);
  109. }
  110. }
  111. ### bBlog Plugin Info ###
  112. function identify_modifier_markdown() {
  113. return array(
  114. 'name' => 'markdown',
  115. 'type' => 'modifier',
  116. 'nicename' => 'Markdown',
  117. 'description' => 'A text-to-HTML conversion tool for web writers',
  118. 'authors' => 'Michel Fortin and John Gruber',
  119. 'licence' => 'BSD-like',
  120. 'version' => MARKDOWN_VERSION,
  121. 'help' => '<a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by <a href="http://daringfireball.net/">John Gruber</a>. <a href="http://michelf.com/projects/php-markdown/">More...</a>'
  122. );
  123. }
  124. ### Smarty Modifier Interface ###
  125. function smarty_modifier_markdown($text) {
  126. return Markdown($text);
  127. }
  128. ### Textile Compatibility Mode ###
  129. # Rename this file to "classTextile.php" and it can replace Textile everywhere.
  130. if (strcasecmp(substr(__FILE__, -16), "classTextile.php") == 0) {
  131. # Try to include PHP SmartyPants. Should be in the same directory.
  132. @include_once 'smartypants.php';
  133. # Fake Textile class. It calls Markdown instead.
  134. class Textile {
  135. function TextileThis($text, $lite='', $encode='') {
  136. if ($lite == '' && $encode == '') $text = Markdown($text);
  137. if (function_exists('SmartyPants')) $text = SmartyPants($text);
  138. return $text;
  139. }
  140. # Fake restricted version: restrictions are not supported for now.
  141. function TextileRestricted($text, $lite='', $noimage='') {
  142. return $this->TextileThis($text, $lite);
  143. }
  144. # Workaround to ensure compatibility with TextPattern 4.0.3.
  145. function blockLite($text) { return $text; }
  146. }
  147. }
  148. #
  149. # Markdown Parser Class
  150. #
  151. class Markdown_Parser {
  152. # Regex to match balanced [brackets].
  153. # Needed to insert a maximum bracked depth while converting to PHP.
  154. var $nested_brackets_depth = 6;
  155. var $nested_brackets_re;
  156. var $nested_url_parenthesis_depth = 4;
  157. var $nested_url_parenthesis_re;
  158. # Table of hash values for escaped characters:
  159. var $escape_chars = '\`*_{}[]()>#+-.!';
  160. var $escape_chars_re;
  161. # Change to ">" for HTML output.
  162. var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX;
  163. var $tab_width = MARKDOWN_TAB_WIDTH;
  164. # Change to `true` to disallow markup or entities.
  165. var $no_markup = false;
  166. var $no_entities = false;
  167. # Predefined urls and titles for reference links and images.
  168. var $predef_urls = array();
  169. var $predef_titles = array();
  170. function Markdown_Parser() {
  171. #
  172. # Constructor function. Initialize appropriate member variables.
  173. #
  174. $this->_initDetab();
  175. $this->prepareItalicsAndBold();
  176. $this->nested_brackets_re =
  177. str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth).
  178. str_repeat('\])*', $this->nested_brackets_depth);
  179. $this->nested_url_parenthesis_re =
  180. str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth).
  181. str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth);
  182. $this->escape_chars_re = '['.preg_quote($this->escape_chars).']';
  183. # Sort document, block, and span gamut in ascendent priority order.
  184. asort($this->document_gamut);
  185. asort($this->block_gamut);
  186. asort($this->span_gamut);
  187. }
  188. # Internal hashes used during transformation.
  189. var $urls = array();
  190. var $titles = array();
  191. var $html_hashes = array();
  192. # Status flag to avoid invalid nesting.
  193. var $in_anchor = false;
  194. function setup() {
  195. #
  196. # Called before the transformation process starts to setup parser
  197. # states.
  198. #
  199. # Clear global hashes.
  200. $this->urls = $this->predef_urls;
  201. $this->titles = $this->predef_titles;
  202. $this->html_hashes = array();
  203. $in_anchor = false;
  204. }
  205. function teardown() {
  206. #
  207. # Called after the transformation process to clear any variable
  208. # which may be taking up memory unnecessarly.
  209. #
  210. $this->urls = array();
  211. $this->titles = array();
  212. $this->html_hashes = array();
  213. }
  214. function transform($text) {
  215. #
  216. # Main function. Performs some preprocessing on the input text
  217. # and pass it through the document gamut.
  218. #
  219. $this->setup();
  220. # Remove UTF-8 BOM and marker character in input, if present.
  221. $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text);
  222. # Standardize line endings:
  223. # DOS to Unix and Mac to Unix
  224. $text = preg_replace('{\r\n?}', "\n", $text);
  225. # Make sure $text ends with a couple of newlines:
  226. $text .= "\n\n";
  227. # Convert all tabs to spaces.
  228. $text = $this->detab($text);
  229. # Turn block-level HTML blocks into hash entries
  230. $text = $this->hashHTMLBlocks($text);
  231. # Strip any lines consisting only of spaces and tabs.
  232. # This makes subsequent regexen easier to write, because we can
  233. # match consecutive blank lines with /\n+/ instead of something
  234. # contorted like /[ ]*\n+/ .
  235. $text = preg_replace('/^[ ]+$/m', '', $text);
  236. # Run document gamut methods.
  237. foreach ($this->document_gamut as $method => $priority) {
  238. $text = $this->$method($text);
  239. }
  240. $this->teardown();
  241. return $text . "\n";
  242. }
  243. var $document_gamut = array(
  244. # Strip link definitions, store in hashes.
  245. "stripLinkDefinitions" => 20,
  246. "runBasicBlockGamut" => 30,
  247. );
  248. function stripLinkDefinitions($text) {
  249. #
  250. # Strips link definitions from text, stores the URLs and titles in
  251. # hash references.
  252. #
  253. $less_than_tab = $this->tab_width - 1;
  254. # Link defs are in the form: ^[id]: url "optional title"
  255. $text = preg_replace_callback('{
  256. ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1
  257. [ ]*
  258. \n? # maybe *one* newline
  259. [ ]*
  260. (?:
  261. <(.+?)> # url = $2
  262. |
  263. (\S+?) # url = $3
  264. )
  265. [ ]*
  266. \n? # maybe one newline
  267. [ ]*
  268. (?:
  269. (?<=\s) # lookbehind for whitespace
  270. ["(]
  271. (.*?) # title = $4
  272. [")]
  273. [ ]*
  274. )? # title is optional
  275. (?:\n+|\Z)
  276. }xm',
  277. array(&$this, '_stripLinkDefinitions_callback'),
  278. $text);
  279. return $text;
  280. }
  281. function _stripLinkDefinitions_callback($matches) {
  282. $link_id = strtolower($matches[1]);
  283. $url = $matches[2] == '' ? $matches[3] : $matches[2];
  284. $this->urls[$link_id] = $url;
  285. $this->titles[$link_id] =& $matches[4];
  286. return ''; # String that will replace the block
  287. }
  288. function hashHTMLBlocks($text) {
  289. if ($this->no_markup) return $text;
  290. $less_than_tab = $this->tab_width - 1;
  291. # Hashify HTML blocks:
  292. # We only want to do this for block-level HTML tags, such as headers,
  293. # lists, and tables. That's because we still want to wrap <p>s around
  294. # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  295. # phrase emphasis, and spans. The list of tags we're looking for is
  296. # hard-coded:
  297. #
  298. # * List "a" is made of tags which can be both inline or block-level.
  299. # These will be treated block-level when the start tag is alone on
  300. # its line, otherwise they're not matched here and will be taken as
  301. # inline later.
  302. # * List "b" is made of tags which are always block-level;
  303. #
  304. $block_tags_a_re = 'ins|del';
  305. $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'.
  306. 'script|noscript|form|fieldset|iframe|math';
  307. # Regular expression for the content of a block tag.
  308. $nested_tags_level = 4;
  309. $attr = '
  310. (?> # optional tag attributes
  311. \s # starts with whitespace
  312. (?>
  313. [^>"/]+ # text outside quotes
  314. |
  315. /+(?!>) # slash not followed by ">"
  316. |
  317. "[^"]*" # text inside double quotes (tolerate ">")
  318. |
  319. \'[^\']*\' # text inside single quotes (tolerate ">")
  320. )*
  321. )?
  322. ';
  323. $content =
  324. str_repeat('
  325. (?>
  326. [^<]+ # content without tag
  327. |
  328. <\2 # nested opening tag
  329. '.$attr.' # attributes
  330. (?>
  331. />
  332. |
  333. >', $nested_tags_level). # end of opening tag
  334. '.*?'. # last level nested tag content
  335. str_repeat('
  336. </\2\s*> # closing nested tag
  337. )
  338. |
  339. <(?!/\2\s*> # other tags with a different name
  340. )
  341. )*',
  342. $nested_tags_level);
  343. $content2 = str_replace('\2', '\3', $content);
  344. # First, look for nested blocks, e.g.:
  345. # <div>
  346. # <div>
  347. # tags for inner block must be indented.
  348. # </div>
  349. # </div>
  350. #
  351. # The outermost tags must start at the left margin for this to match, and
  352. # the inner nested divs must be indented.
  353. # We need to do this before the next, more liberal match, because the next
  354. # match will start at the first `<div>` and stop at the first `</div>`.
  355. $text = preg_replace_callback('{(?>
  356. (?>
  357. (?<=\n\n) # Starting after a blank line
  358. | # or
  359. \A\n? # the beginning of the doc
  360. )
  361. ( # save in $1
  362. # Match from `\n<tag>` to `</tag>\n`, handling nested tags
  363. # in between.
  364. [ ]{0,'.$less_than_tab.'}
  365. <('.$block_tags_b_re.')# start tag = $2
  366. '.$attr.'> # attributes followed by > and \n
  367. '.$content.' # content, support nesting
  368. </\2> # the matching end tag
  369. [ ]* # trailing spaces/tabs
  370. (?=\n+|\Z) # followed by a newline or end of document
  371. | # Special version for tags of group a.
  372. [ ]{0,'.$less_than_tab.'}
  373. <('.$block_tags_a_re.')# start tag = $3
  374. '.$attr.'>[ ]*\n # attributes followed by >
  375. '.$content2.' # content, support nesting
  376. </\3> # the matching end tag
  377. [ ]* # trailing spaces/tabs
  378. (?=\n+|\Z) # followed by a newline or end of document
  379. | # Special case just for <hr />. It was easier to make a special
  380. # case than to make the other regex more complicated.
  381. [ ]{0,'.$less_than_tab.'}
  382. <(hr) # start tag = $2
  383. '.$attr.' # attributes
  384. /?> # the matching end tag
  385. [ ]*
  386. (?=\n{2,}|\Z) # followed by a blank line or end of document
  387. | # Special case for standalone HTML comments:
  388. [ ]{0,'.$less_than_tab.'}
  389. (?s:
  390. <!-- .*? -->
  391. )
  392. [ ]*
  393. (?=\n{2,}|\Z) # followed by a blank line or end of document
  394. | # PHP and ASP-style processor instructions (<? and <%)
  395. [ ]{0,'.$less_than_tab.'}
  396. (?s:
  397. <([?%]) # $2
  398. .*?
  399. \2>
  400. )
  401. [ ]*
  402. (?=\n{2,}|\Z) # followed by a blank line or end of document
  403. )
  404. )}Sxmi',
  405. array(&$this, '_hashHTMLBlocks_callback'),
  406. $text);
  407. return $text;
  408. }
  409. function _hashHTMLBlocks_callback($matches) {
  410. $text = $matches[1];
  411. $key = $this->hashBlock($text);
  412. return "\n\n$key\n\n";
  413. }
  414. function hashPart($text, $boundary = 'X') {
  415. #
  416. # Called whenever a tag must be hashed when a function insert an atomic
  417. # element in the text stream. Passing $text to through this function gives
  418. # a unique text-token which will be reverted back when calling unhash.
  419. #
  420. # The $boundary argument specify what character should be used to surround
  421. # the token. By convension, "B" is used for block elements that needs not
  422. # to be wrapped into paragraph tags at the end, ":" is used for elements
  423. # that are word separators and "X" is used in the general case.
  424. #
  425. # Swap back any tag hash found in $text so we do not have to `unhash`
  426. # multiple times at the end.
  427. $text = $this->unhash($text);
  428. # Then hash the block.
  429. static $i = 0;
  430. $key = "$boundary\x1A" . ++$i . $boundary;
  431. $this->html_hashes[$key] = $text;
  432. return $key; # String that will replace the tag.
  433. }
  434. function hashBlock($text) {
  435. #
  436. # Shortcut function for hashPart with block-level boundaries.
  437. #
  438. return $this->hashPart($text, 'B');
  439. }
  440. var $block_gamut = array(
  441. #
  442. # These are all the transformations that form block-level
  443. # tags like paragraphs, headers, and list items.
  444. #
  445. "doHeaders" => 10,
  446. "doHorizontalRules" => 20,
  447. "doLists" => 40,
  448. "doCodeBlocks" => 50,
  449. "doBlockQuotes" => 60,
  450. );
  451. function runBlockGamut($text) {
  452. #
  453. # Run block gamut tranformations.
  454. #
  455. # We need to escape raw HTML in Markdown source before doing anything
  456. # else. This need to be done for each block, and not only at the
  457. # begining in the Markdown function since hashed blocks can be part of
  458. # list items and could have been indented. Indented blocks would have
  459. # been seen as a code block in a previous pass of hashHTMLBlocks.
  460. $text = $this->hashHTMLBlocks($text);
  461. return $this->runBasicBlockGamut($text);
  462. }
  463. function runBasicBlockGamut($text) {
  464. #
  465. # Run block gamut tranformations, without hashing HTML blocks. This is
  466. # useful when HTML blocks are known to be already hashed, like in the first
  467. # whole-document pass.
  468. #
  469. foreach ($this->block_gamut as $method => $priority) {
  470. $text = $this->$method($text);
  471. }
  472. # Finally form paragraph and restore hashed blocks.
  473. $text = $this->formParagraphs($text);
  474. return $text;
  475. }
  476. function doHorizontalRules($text) {
  477. # Do Horizontal Rules:
  478. return preg_replace(
  479. '{
  480. ^[ ]{0,3} # Leading space
  481. ([-*_]) # $1: First marker
  482. (?> # Repeated marker group
  483. [ ]{0,2} # Zero, one, or two spaces.
  484. \1 # Marker character
  485. ){2,} # Group repeated at least twice
  486. [ ]* # Tailing spaces
  487. $ # End of line.
  488. }mx',
  489. "\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n",
  490. $text);
  491. }
  492. var $span_gamut = array(
  493. #
  494. # These are all the transformations that occur *within* block-level
  495. # tags like paragraphs, headers, and list items.
  496. #
  497. # Process character escapes, code spans, and inline HTML
  498. # in one shot.
  499. "parseSpan" => -30,
  500. # Process anchor and image tags. Images must come first,
  501. # because ![foo][f] looks like an anchor.
  502. "doImages" => 10,
  503. "doAnchors" => 20,
  504. # Make links out of things like `<http://example.com/>`
  505. # Must come after doAnchors, because you can use < and >
  506. # delimiters in inline links like [this](<url>).
  507. "doAutoLinks" => 30,
  508. "encodeAmpsAndAngles" => 40,
  509. "doItalicsAndBold" => 50,
  510. "doHardBreaks" => 60,
  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. return $text;
  520. }
  521. function doHardBreaks($text) {
  522. # Do hard breaks:
  523. return preg_replace_callback('/ {2,}\n/',
  524. array(&$this, '_doHardBreaks_callback'), $text);
  525. }
  526. function _doHardBreaks_callback($matches) {
  527. return $this->hashPart("<br$this->empty_element_suffix\n");
  528. }
  529. function doAnchors($text) {
  530. #
  531. # Turn Markdown link shortcuts into XHTML <a> tags.
  532. #
  533. if ($this->in_anchor) return $text;
  534. $this->in_anchor = true;
  535. #
  536. # First, handle reference-style links: [link text] [id]
  537. #
  538. $text = preg_replace_callback('{
  539. ( # wrap whole match in $1
  540. \[
  541. ('.$this->nested_brackets_re.') # link text = $2
  542. \]
  543. [ ]? # one optional space
  544. (?:\n[ ]*)? # one optional newline followed by spaces
  545. \[
  546. (.*?) # id = $3
  547. \]
  548. )
  549. }xs',
  550. array(&$this, '_doAnchors_reference_callback'), $text);
  551. #
  552. # Next, inline-style links: [link text](url "optional title")
  553. #
  554. $text = preg_replace_callback('{
  555. ( # wrap whole match in $1
  556. \[
  557. ('.$this->nested_brackets_re.') # link text = $2
  558. \]
  559. \( # literal paren
  560. [ \n]*
  561. (?:
  562. <(.+?)> # href = $3
  563. |
  564. ('.$this->nested_url_parenthesis_re.') # href = $4
  565. )
  566. [ \n]*
  567. ( # $5
  568. ([\'"]) # quote char = $6
  569. (.*?) # Title = $7
  570. \6 # matching quote
  571. [ \n]* # ignore any spaces/tabs between closing quote and )
  572. )? # title is optional
  573. \)
  574. )
  575. }xs',
  576. array(&$this, '_doAnchors_inline_callback'), $text);
  577. #
  578. # Last, handle reference-style shortcuts: [link text]
  579. # These must come last in case you've also got [link text][1]
  580. # or [link text](/foo)
  581. #
  582. $text = preg_replace_callback('{
  583. ( # wrap whole match in $1
  584. \[
  585. ([^\[\]]+) # link text = $2; can\'t contain [ or ]
  586. \]
  587. )
  588. }xs',
  589. array(&$this, '_doAnchors_reference_callback'), $text);
  590. $this->in_anchor = false;
  591. return $text;
  592. }
  593. function _doAnchors_reference_callback($matches) {
  594. $whole_match = $matches[1];
  595. $link_text = $matches[2];
  596. $link_id =& $matches[3];
  597. if ($link_id == "") {
  598. # for shortcut links like [this][] or [this].
  599. $link_id = $link_text;
  600. }
  601. # lower-case and turn embedded newlines into spaces
  602. $link_id = strtolower($link_id);
  603. $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
  604. if (isset($this->urls[$link_id])) {
  605. $url = $this->urls[$link_id];
  606. // dayle convert
  607. $url = URL::to($url);
  608. $url = $this->encodeAttribute($url);
  609. $result = "<a href=\"$url\"";
  610. if ( isset( $this->titles[$link_id] ) ) {
  611. $title = $this->titles[$link_id];
  612. $title = $this->encodeAttribute($title);
  613. $result .= " title=\"$title\"";
  614. }
  615. $link_text = $this->runSpanGamut($link_text);
  616. $result .= ">$link_text</a>";
  617. $result = $this->hashPart($result);
  618. }
  619. else {
  620. $result = $whole_match;
  621. }
  622. return $result;
  623. }
  624. function _doAnchors_inline_callback($matches) {
  625. $whole_match = $matches[1];
  626. $link_text = $this->runSpanGamut($matches[2]);
  627. $url = $matches[3] == '' ? $matches[4] : $matches[3];
  628. $title =& $matches[7];
  629. // dayle convert
  630. $url = URL::to($url);
  631. $url = $this->encodeAttribute($url);
  632. $result = "<a href=\"$url\"";
  633. if (isset($title)) {
  634. $title = $this->encodeAttribute($title);
  635. $result .= " title=\"$title\"";
  636. }
  637. $link_text = $this->runSpanGamut($link_text);
  638. $result .= ">$link_text</a>";
  639. return $this->hashPart($result);
  640. }
  641. function doImages($text) {
  642. #
  643. # Turn Markdown image shortcuts into <img> tags.
  644. #
  645. #
  646. # First, handle reference-style labeled images: ![alt text][id]
  647. #
  648. $text = preg_replace_callback('{
  649. ( # wrap whole match in $1
  650. !\[
  651. ('.$this->nested_brackets_re.') # alt text = $2
  652. \]
  653. [ ]? # one optional space
  654. (?:\n[ ]*)? # one optional newline followed by spaces
  655. \[
  656. (.*?) # id = $3
  657. \]
  658. )
  659. }xs',
  660. array(&$this, '_doImages_reference_callback'), $text);
  661. #
  662. # Next, handle inline images: ![alt text](url "optional title")
  663. # Don't forget: encode * and _
  664. #
  665. $text = preg_replace_callback('{
  666. ( # wrap whole match in $1
  667. !\[
  668. ('.$this->nested_brackets_re.') # alt text = $2
  669. \]
  670. \s? # One optional whitespace character
  671. \( # literal paren
  672. [ \n]*
  673. (?:
  674. <(\S*)> # src url = $3
  675. |
  676. ('.$this->nested_url_parenthesis_re.') # src url = $4
  677. )
  678. [ \n]*
  679. ( # $5
  680. ([\'"]) # quote char = $6
  681. (.*?) # title = $7
  682. \6 # matching quote
  683. [ \n]*
  684. )? # title is optional
  685. \)
  686. )
  687. }xs',
  688. array(&$this, '_doImages_inline_callback'), $text);
  689. return $text;
  690. }
  691. function _doImages_reference_callback($matches) {
  692. $whole_match = $matches[1];
  693. $alt_text = $matches[2];
  694. $link_id = strtolower($matches[3]);
  695. if ($link_id == "") {
  696. $link_id = strtolower($alt_text); # for shortcut links like ![this][].
  697. }
  698. $alt_text = $this->encodeAttribute($alt_text);
  699. if (isset($this->urls[$link_id])) {
  700. $url = $this->encodeAttribute($this->urls[$link_id]);
  701. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  702. if (isset($this->titles[$link_id])) {
  703. $title = $this->titles[$link_id];
  704. $title = $this->encodeAttribute($title);
  705. $result .= " title=\"$title\"";
  706. }
  707. $result .= $this->empty_element_suffix;
  708. $result = $this->hashPart($result);
  709. }
  710. else {
  711. # If there's no such link ID, leave intact:
  712. $result = $whole_match;
  713. }
  714. return $result;
  715. }
  716. function _doImages_inline_callback($matches) {
  717. $whole_match = $matches[1];
  718. $alt_text = $matches[2];
  719. $url = $matches[3] == '' ? $matches[4] : $matches[3];
  720. $title =& $matches[7];
  721. $alt_text = $this->encodeAttribute($alt_text);
  722. $url = $this->encodeAttribute($url);
  723. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  724. if (isset($title)) {
  725. $title = $this->encodeAttribute($title);
  726. $result .= " title=\"$title\""; # $title already quoted
  727. }
  728. $result .= $this->empty_element_suffix;
  729. return $this->hashPart($result);
  730. }
  731. function doHeaders($text) {
  732. # Setext-style headers:
  733. # Header 1
  734. # ========
  735. #
  736. # Header 2
  737. # --------
  738. #
  739. $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx',
  740. array(&$this, '_doHeaders_callback_setext'), $text);
  741. # atx-style headers:
  742. # # Header 1
  743. # ## Header 2
  744. # ## Header 2 with closing hashes ##
  745. # ...
  746. # ###### Header 6
  747. #
  748. $text = preg_replace_callback('{
  749. ^(\#{1,6}) # $1 = string of #\'s
  750. [ ]*
  751. (.+?) # $2 = Header text
  752. [ ]*
  753. \#* # optional closing #\'s (not counted)
  754. \n+
  755. }xm',
  756. array(&$this, '_doHeaders_callback_atx'), $text);
  757. return $text;
  758. }
  759. function _doHeaders_callback_setext($matches) {
  760. # Terrible hack to check we haven't found an empty list item.
  761. if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1]))
  762. return $matches[0];
  763. $level = $matches[2]{0} == '=' ? 1 : 2;
  764. $block = "<h$level>".$this->runSpanGamut($matches[1])."</h$level>";
  765. return "\n" . $this->hashBlock($block) . "\n\n";
  766. }
  767. function _doHeaders_callback_atx($matches) {
  768. $level = strlen($matches[1]);
  769. $block = "<h$level>".$this->runSpanGamut($matches[2])."</h$level>";
  770. return "\n" . $this->hashBlock($block) . "\n\n";
  771. }
  772. function doLists($text) {
  773. #
  774. # Form HTML ordered (numbered) and unordered (bulleted) lists.
  775. #
  776. $less_than_tab = $this->tab_width - 1;
  777. # Re-usable patterns to match list item bullets and number markers:
  778. $marker_ul_re = '[*+-]';
  779. $marker_ol_re = '\d+[\.]';
  780. $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  781. $markers_relist = array(
  782. $marker_ul_re => $marker_ol_re,
  783. $marker_ol_re => $marker_ul_re,
  784. );
  785. foreach ($markers_relist as $marker_re => $other_marker_re) {
  786. # Re-usable pattern to match any entirel ul or ol list:
  787. $whole_list_re = '
  788. ( # $1 = whole list
  789. ( # $2
  790. ([ ]{0,'.$less_than_tab.'}) # $3 = number of spaces
  791. ('.$marker_re.') # $4 = first list item marker
  792. [ ]+
  793. )
  794. (?s:.+?)
  795. ( # $5
  796. \z
  797. |
  798. \n{2,}
  799. (?=\S)
  800. (?! # Negative lookahead for another list item marker
  801. [ ]*
  802. '.$marker_re.'[ ]+
  803. )
  804. |
  805. (?= # Lookahead for another kind of list
  806. \n
  807. \3 # Must have the same indentation
  808. '.$other_marker_re.'[ ]+
  809. )
  810. )
  811. )
  812. '; // mx
  813. # We use a different prefix before nested lists than top-level lists.
  814. # See extended comment in _ProcessListItems().
  815. if ($this->list_level) {
  816. $text = preg_replace_callback('{
  817. ^
  818. '.$whole_list_re.'
  819. }mx',
  820. array(&$this, '_doLists_callback'), $text);
  821. }
  822. else {
  823. $text = preg_replace_callback('{
  824. (?:(?<=\n)\n|\A\n?) # Must eat the newline
  825. '.$whole_list_re.'
  826. }mx',
  827. array(&$this, '_doLists_callback'), $text);
  828. }
  829. }
  830. return $text;
  831. }
  832. function _doLists_callback($matches) {
  833. # Re-usable patterns to match list item bullets and number markers:
  834. $marker_ul_re = '[*+-]';
  835. $marker_ol_re = '\d+[\.]';
  836. $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  837. $list = $matches[1];
  838. $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol";
  839. $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re );
  840. $list .= "\n";
  841. $result = $this->processListItems($list, $marker_any_re);
  842. $result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>");
  843. return "\n". $result ."\n\n";
  844. }
  845. var $list_level = 0;
  846. function processListItems($list_str, $marker_any_re) {
  847. #
  848. # Process the contents of a single ordered or unordered list, splitting it
  849. # into individual list items.
  850. #
  851. # The $this->list_level global keeps track of when we're inside a list.
  852. # Each time we enter a list, we increment it; when we leave a list,
  853. # we decrement. If it's zero, we're not in a list anymore.
  854. #
  855. # We do this because when we're not inside a list, we want to treat
  856. # something like this:
  857. #
  858. # I recommend upgrading to version
  859. # 8. Oops, now this line is treated
  860. # as a sub-list.
  861. #
  862. # As a single paragraph, despite the fact that the second line starts
  863. # with a digit-period-space sequence.
  864. #
  865. # Whereas when we're inside a list (or sub-list), that line will be
  866. # treated as the start of a sub-list. What a kludge, huh? This is
  867. # an aspect of Markdown's syntax that's hard to parse perfectly
  868. # without resorting to mind-reading. Perhaps the solution is to
  869. # change the syntax rules such that sub-lists must start with a
  870. # starting cardinal number; e.g. "1." or "a.".
  871. $this->list_level++;
  872. # trim trailing blank lines:
  873. $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  874. $list_str = preg_replace_callback('{
  875. (\n)? # leading line = $1
  876. (^[ ]*) # leading whitespace = $2
  877. ('.$marker_any_re.' # list marker and space = $3
  878. (?:[ ]+|(?=\n)) # space only required if item is not empty
  879. )
  880. ((?s:.*?)) # list item text = $4
  881. (?:(\n+(?=\n))|\n) # tailing blank line = $5
  882. (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n))))
  883. }xm',
  884. array(&$this, '_processListItems_callback'), $list_str);
  885. $this->list_level--;
  886. return $list_str;
  887. }
  888. function _processListItems_callback($matches) {
  889. $item = $matches[4];
  890. $leading_line =& $matches[1];
  891. $leading_space =& $matches[2];
  892. $marker_space = $matches[3];
  893. $tailing_blank_line =& $matches[5];
  894. if ($leading_line || $tailing_blank_line ||
  895. preg_match('/\n{2,}/', $item))
  896. {
  897. # Replace marker with the appropriate whitespace indentation
  898. $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;
  899. $item = $this->runBlockGamut($this->outdent($item)."\n");
  900. }
  901. else {
  902. # Recursion for sub-lists:
  903. $item = $this->doLists($this->outdent($item));
  904. $item = preg_replace('/\n+$/', '', $item);
  905. $item = $this->runSpanGamut($item);
  906. }
  907. return "<li>" . $item . "</li>\n";
  908. }
  909. function doCodeBlocks($text) {
  910. #
  911. # Process Markdown `<pre><code>` blocks.
  912. #
  913. $text = preg_replace_callback('{
  914. (?:\n\n|\A\n?)
  915. ( # $1 = the code block -- one or more lines, starting with a space/tab
  916. (?>
  917. [ ]{'.$this->tab_width.'} # Lines must start with a tab or a tab-width of spaces
  918. .*\n+
  919. )+
  920. )
  921. ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
  922. }xm',
  923. array(&$this, '_doCodeBlocks_callback'), $text);
  924. return $text;
  925. }
  926. function _doCodeBlocks_callback($matches) {
  927. $codeblock = $matches[1];
  928. $codeblock = $this->outdent($codeblock);
  929. $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
  930. # trim leading newlines and trailing newlines
  931. $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
  932. $codeblock = "<pre class=\"prettyprint lang-php linenums\">$codeblock\n</pre>";
  933. return "\n\n".$this->hashBlock($codeblock)."\n\n";
  934. }
  935. function makeCodeSpan($code) {
  936. #
  937. # Create a code span markup for $code. Called from handleSpanToken.
  938. #
  939. $code = htmlspecialchars(trim($code), ENT_NOQUOTES);
  940. return $this->hashPart("<code>$code</code>");
  941. }
  942. var $em_relist = array(
  943. '' => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S|$)(?![\.,:;]\s)',
  944. '*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
  945. '_' => '(?<=\S|^)(?<!_)_(?!_)',
  946. );
  947. var $strong_relist = array(
  948. '' => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S|$)(?![\.,:;]\s)',
  949. '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
  950. '__' => '(?<=\S|^)(?<!_)__(?!_)',
  951. );
  952. var $em_strong_relist = array(
  953. '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S|$)(?![\.,:;]\s)',
  954. '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
  955. '___' => '(?<=\S|^)(?<!_)___(?!_)',
  956. );
  957. var $em_strong_prepared_relist;
  958. function prepareItalicsAndBold() {
  959. #
  960. # Prepare regular expressions for searching emphasis tokens in any
  961. # context.
  962. #
  963. foreach ($this->em_relist as $em => $em_re) {
  964. foreach ($this->strong_relist as $strong => $strong_re) {
  965. # Construct list of allowed token expressions.
  966. $token_relist = array();
  967. if (isset($this->em_strong_relist["$em$strong"])) {
  968. $token_relist[] = $this->em_strong_relist["$em$strong"];
  969. }
  970. $token_relist[] = $em_re;
  971. $token_relist[] = $strong_re;
  972. # Construct master expression from list.
  973. $token_re = '{('. implode('|', $token_relist) .')}';
  974. $this->em_strong_prepared_relist["$em$strong"] = $token_re;
  975. }
  976. }
  977. }
  978. function doItalicsAndBold($text) {
  979. $token_stack = array('');
  980. $text_stack = array('');
  981. $em = '';
  982. $strong = '';
  983. $tree_char_em = false;
  984. while (1) {
  985. #
  986. # Get prepared regular expression for seraching emphasis tokens
  987. # in current context.
  988. #
  989. $token_re = $this->em_strong_prepared_relist["$em$strong"];
  990. #
  991. # Each loop iteration search for the next emphasis token.
  992. # Each token is then passed to handleSpanToken.
  993. #
  994. $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
  995. $text_stack[0] .= $parts[0];
  996. $token =& $parts[1];
  997. $text =& $parts[2];
  998. if (empty($token)) {
  999. # Reached end of text span: empty stack without emitting.
  1000. # any more emphasis.
  1001. while ($token_stack[0]) {
  1002. $text_stack[1] .= array_shift($token_stack);
  1003. $text_stack[0] .= array_shift($text_stack);
  1004. }
  1005. break;
  1006. }
  1007. $token_len = strlen($token);
  1008. if ($tree_char_em) {
  1009. # Reached closing marker while inside a three-char emphasis.
  1010. if ($token_len == 3) {
  1011. # Three-char closing marker, close em and strong.
  1012. array_shift($token_stack);
  1013. $span = array_shift($text_stack);
  1014. $span = $this->runSpanGamut($span);
  1015. $span = "<strong><em>$span</em></strong>";
  1016. $text_stack[0] .= $this->hashPart($span);
  1017. $em = '';
  1018. $strong = '';
  1019. } else {
  1020. # Other closing marker: close one em or strong and
  1021. # change current token state to match the other
  1022. $token_stack[0] = str_repeat($token{0}, 3-$token_len);
  1023. $tag = $token_len == 2 ? "strong" : "em";
  1024. $span = $text_stack[0];
  1025. $span = $this->runSpanGamut($span);
  1026. $span = "<$tag>$span</$tag>";
  1027. $text_stack[0] = $this->hashPart($span);
  1028. $$tag = ''; # $$tag stands for $em or $strong
  1029. }
  1030. $tree_char_em = false;
  1031. } else if ($token_len == 3) {
  1032. if ($em) {
  1033. # Reached closing marker for both em and strong.
  1034. # Closing strong marker:
  1035. for ($i = 0; $i < 2; ++$i) {
  1036. $shifted_token = array_shift($token_stack);
  1037. $tag = strlen($shifted_token) == 2 ? "strong" : "em";
  1038. $span = array_shift($text_stack);
  1039. $span = $this->runSpanGamut($span);
  1040. $span = "<$tag>$span</$tag>";
  1041. $text_stack[0] .= $this->hashPart($span);
  1042. $$tag = ''; # $$tag stands for $em or $strong
  1043. }
  1044. } else {
  1045. # Reached opening three-char emphasis marker. Push on token
  1046. # stack; will be handled by the special condition above.
  1047. $em = $token{0};
  1048. $strong = "$em$em";
  1049. array_unshift($token_stack, $token);
  1050. array_unshift($text_stack, '');
  1051. $tree_char_em = true;
  1052. }
  1053. } else if ($token_len == 2) {
  1054. if ($strong) {
  1055. # Unwind any dangling emphasis marker:
  1056. if (strlen($token_stack[0]) == 1) {
  1057. $text_stack[1] .= array_shift($token_stack);
  1058. $text_stack[0] .= array_shift($text_stack);
  1059. }
  1060. # Closing strong marker:
  1061. array_shift($token_stack);
  1062. $span = array_shift($text_stack);
  1063. $span = $this->runSpanGamut($span);
  1064. $span = "<strong>$span</strong>";
  1065. $text_stack[0] .= $this->hashPart($span);
  1066. $strong = '';
  1067. } else {
  1068. array_unshift($token_stack, $token);
  1069. array_unshift($text_stack, '');
  1070. $strong = $token;
  1071. }
  1072. } else {
  1073. # Here $token_len == 1
  1074. if ($em) {
  1075. if (strlen($token_stack[0]) == 1) {
  1076. # Closing emphasis marker:
  1077. array_shift($token_stack);
  1078. $span = array_shift($text_stack);
  1079. $span = $this->runSpanGamut($span);
  1080. $span = "<em>$span</em>";
  1081. $text_stack[0] .= $this->hashPart($span);
  1082. $em = '';
  1083. } else {
  1084. $text_stack[0] .= $token;
  1085. }
  1086. } else {
  1087. array_unshift($token_stack, $token);
  1088. array_unshift($text_stack, '');
  1089. $em = $token;
  1090. }
  1091. }
  1092. }
  1093. return $text_stack[0];
  1094. }
  1095. function doBlockQuotes($text) {
  1096. $text = preg_replace_callback('/
  1097. ( # Wrap whole match in $1
  1098. (?>
  1099. ^[ ]*>[ ]? # ">" at the start of a line
  1100. .+\n # rest of the first line
  1101. (.+\n)* # subsequent consecutive lines
  1102. \n* # blanks
  1103. )+
  1104. )
  1105. /xm',
  1106. array(&$this, '_doBlockQuotes_callback'), $text);
  1107. return $text;
  1108. }
  1109. function _doBlockQuotes_callback($matches) {
  1110. $bq = $matches[1];
  1111. # trim one level of quoting - trim whitespace-only lines
  1112. $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
  1113. $bq = $this->runBlockGamut($bq); # recurse
  1114. $bq = preg_replace('/^/m', " ", $bq);
  1115. # These leading spaces cause problem with <pre> content,
  1116. # so we need to fix that:
  1117. $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx',
  1118. array(&$this, '_doBlockQuotes_callback2'), $bq);
  1119. return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n";
  1120. }
  1121. function _doBlockQuotes_callback2($matches) {
  1122. $pre = $matches[1];
  1123. $pre = preg_replace('/^ /m', '', $pre);
  1124. return $pre;
  1125. }
  1126. function formParagraphs($text) {
  1127. #
  1128. # Params:
  1129. # $text - string to process with html <p> tags
  1130. #
  1131. # Strip leading and trailing lines:
  1132. $text = preg_replace('/\A\n+|\n+\z/', '', $text);
  1133. $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
  1134. #
  1135. # Wrap <p> tags and unhashify HTML blocks
  1136. #
  1137. foreach ($grafs as $key => $value) {
  1138. if (!preg_match('/^B\x1A[0-9]+B$/', $value)) {
  1139. # Is a paragraph.
  1140. $value = $this->runSpanGamut($value);
  1141. $value = preg_replace('/^([ ]*)/', "<p>", $value);
  1142. $value .= "</p>";
  1143. $grafs[$key] = $this->unhash($value);
  1144. }
  1145. else {
  1146. # Is a block.
  1147. # Modify elements of @grafs in-place...
  1148. $graf = $value;
  1149. $block = $this->html_hashes[$graf];
  1150. $graf = $block;
  1151. // if (preg_match('{
  1152. // \A
  1153. // ( # $1 = <div> tag
  1154. // <div \s+
  1155. // [^>]*
  1156. // \b
  1157. // markdown\s*=\s* ([\'"]) # $2 = attr quote char
  1158. // 1
  1159. // \2
  1160. // [^>]*
  1161. // >
  1162. // )
  1163. // ( # $3 = contents
  1164. // .*
  1165. // )
  1166. // (</div>) # $4 = closing tag
  1167. // \z
  1168. // }xs', $block, $matches))
  1169. // {
  1170. // list(, $div_open, , $div_content, $div_close) = $matches;
  1171. //
  1172. // # We can't call Markdown(), because that resets the hash;
  1173. // # that initialization code should be pulled into its own sub, though.
  1174. // $div_content = $this->hashHTMLBlocks($div_content);
  1175. //
  1176. // # Run document gamut methods on the content.
  1177. // foreach ($this->document_gamut as $method => $priority) {
  1178. // $div_content = $this->$method($div_content);
  1179. // }
  1180. //
  1181. // $div_open = preg_replace(
  1182. // '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open);
  1183. //
  1184. // $graf = $div_open . "\n" . $div_content . "\n" . $div_close;
  1185. // }
  1186. $grafs[$key] = $graf;
  1187. }
  1188. }
  1189. return implode("\n\n", $grafs);
  1190. }
  1191. function encodeAttribute($text) {
  1192. #
  1193. # Encode text for a double-quoted HTML attribute. This function
  1194. # is *not* suitable for attributes enclosed in single quotes.
  1195. #
  1196. $text = $this->encodeAmpsAndAngles($text);
  1197. $text = str_replace('"', '&quot;', $text);
  1198. return $text;
  1199. }
  1200. function encodeAmpsAndAngles($text) {
  1201. #
  1202. # Smart processing for ampersands and angle brackets that need to
  1203. # be encoded. Valid character entities are left alone unless the
  1204. # no-entities mode is set.
  1205. #
  1206. if ($this->no_entities) {
  1207. $text = str_replace('&', '&amp;', $text);
  1208. } else {
  1209. # Ampersand-encoding based entirely on Nat Irons's Amputator
  1210. # MT plugin: <http://bumppo.net/projects/amputator/>
  1211. $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
  1212. '&amp;', $text);;
  1213. }
  1214. # Encode remaining <'s
  1215. $text = str_replace('<', '&lt;', $text);
  1216. return $text;
  1217. }
  1218. function doAutoLinks($text) {
  1219. $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i',
  1220. array(&$this, '_doAutoLinks_url_callback'), $text);
  1221. # Email addresses: <address@domain.foo>
  1222. $text = preg_replace_callback('{
  1223. <
  1224. (?:mailto:)?
  1225. (
  1226. (?:
  1227. [-!#$%&\'*+/=?^_`.{|}~\w\x80-\xFF]+
  1228. |
  1229. ".*?"
  1230. )
  1231. \@
  1232. (?:
  1233. [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+
  1234. |
  1235. \[[\d.a-fA-F:]+\] # IPv4 & IPv6
  1236. )
  1237. )
  1238. >
  1239. }xi',
  1240. array(&$this, '_doAutoLinks_email_callback'), $text);
  1241. return $text;
  1242. }
  1243. function _doAutoLinks_url_callback($matches) {
  1244. $url = $this->encodeAttribute($matches[1]);
  1245. $url = Laravel\URL::to($url);
  1246. $link = "<a href=\"$url\">$url</a>";
  1247. return $this->hashPart($link);
  1248. }
  1249. function _doAutoLinks_email_callback($matches) {
  1250. $address = $matches[1];
  1251. $link = $this->encodeEmailAddress($address);
  1252. return $this->hashPart($link);
  1253. }
  1254. function encodeEmailAddress($addr) {
  1255. #
  1256. # Input: an email address, e.g. "foo@example.com"
  1257. #
  1258. # Output: the email address as a mailto link, with each character
  1259. # of the address encoded as either a decimal or hex entity, in
  1260. # the hopes of foiling most address harvesting spam bots. E.g.:
  1261. #
  1262. # <p><a href="&#109;&#x61;&#105;&#x6c;&#116;&#x6f;&#58;&#x66;o&#111;
  1263. # &#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;&#101;&#46;&#x63;&#111;
  1264. # &#x6d;">&#x66;o&#111;&#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;
  1265. # &#101;&#46;&#x63;&#111;&#x6d;</a></p>
  1266. #
  1267. # Based by a filter by Matthew Wickline, posted to BBEdit-Talk.
  1268. # With some optimizations by Milian Wolff.
  1269. #
  1270. $addr = "mailto:" . $addr;
  1271. $chars = preg_split('/(?<!^)(?!$)/', $addr);
  1272. $seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed.
  1273. foreach ($chars as $key => $char) {
  1274. $ord = ord($char);
  1275. # Ignore non-ascii chars.
  1276. if ($ord < 128) {
  1277. $r = ($seed * (1 + $key)) % 100; # Pseudo-random function.
  1278. # roughly 10% raw, 45% hex, 45% dec
  1279. # '@' *must* be encoded. I insist.
  1280. if ($r > 90 && $char != '@') /* do nothing */;
  1281. else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';';
  1282. else $chars[$key] = '&#'.$ord.';';
  1283. }
  1284. }
  1285. $addr = implode('', $chars);
  1286. $text = implode('', array_slice($chars, 7)); # text without `mailto:`
  1287. $addr = "<a href=\"$addr\">$text</a>";
  1288. return $addr;
  1289. }
  1290. function parseSpan($str) {
  1291. #
  1292. # Take the string $str and parse it into tokens, hashing embeded HTML,
  1293. # escaped characters and handling code spans.
  1294. #
  1295. $output = '';
  1296. $span_re = '{
  1297. (
  1298. \\\\'.$this->escape_chars_re.'
  1299. |
  1300. (?<![`\\\\])
  1301. `+ # code span marker
  1302. '.( $this->no_markup ? '' : '
  1303. |
  1304. <!-- .*? --> # comment
  1305. |
  1306. <\?.*?\?> | <%.*?%> # processing instruction
  1307. |
  1308. <[/!$]?[-a-zA-Z0-9:_]+ # regular tags
  1309. (?>
  1310. \s
  1311. (?>[^"\'>]+|"[^"]*"|\'[^\']*\')*
  1312. )?
  1313. >
  1314. ').'
  1315. )
  1316. }xs';
  1317. while (1) {
  1318. #
  1319. # Each loop iteration seach for either the next tag, the next
  1320. # openning code span marker, or the next escaped character.
  1321. # Each token is then passed to handleSpanToken.
  1322. #
  1323. $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE);
  1324. # Create token from text preceding tag.
  1325. if ($parts[0] != "") {
  1326. $output .= $parts[0];
  1327. }
  1328. # Check if we reach the end.
  1329. if (isset($parts[1])) {
  1330. $output .= $this->handleSpanToken($parts[1], $parts[2]);
  1331. $str = $parts[2];
  1332. }
  1333. else {
  1334. break;
  1335. }
  1336. }
  1337. return $output;
  1338. }
  1339. function handleSpanToken($token, &$str) {
  1340. #
  1341. # Handle $token provided by parseSpan by determining its nature and
  1342. # returning the corresponding value that should replace it.
  1343. #
  1344. switch ($token{0}) {
  1345. case "\\":
  1346. return $this->hashPart("&#". ord($token{1}). ";");
  1347. case "`":
  1348. # Search for end marker in remaining text.
  1349. if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm',
  1350. $str, $matches))
  1351. {
  1352. $str = $matches[2];
  1353. $codespan = $this->makeCodeSpan($matches[1]);
  1354. return $this->hashPart($codespan);
  1355. }
  1356. return $token; // return as text since no ending marker found.
  1357. default:
  1358. return $this->hashPart($token);
  1359. }
  1360. }
  1361. function outdent($text) {
  1362. #
  1363. # Remove one level of line-leading tabs or spaces
  1364. #
  1365. return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text);
  1366. }
  1367. # String length function for detab. `_initDetab` will create a function to
  1368. # hanlde UTF-8 if the default function does not exist.
  1369. var $utf8_strlen = 'mb_strlen';
  1370. function detab($text) {
  1371. #
  1372. # Replace tabs with the appropriate amount of space.
  1373. #
  1374. # For each line we separate the line in blocks delemited by
  1375. # tab characters. Then we reconstruct every line by adding the
  1376. # appropriate number of space between each blocks.
  1377. $text = preg_replace_callback('/^.*\t.*$/m',
  1378. array(&$this, '_detab_callback'), $text);
  1379. return $text;
  1380. }
  1381. function _detab_callback($matches) {
  1382. $line = $matches[0];
  1383. $strlen = $this->utf8_strlen; # strlen function for UTF-8.
  1384. # Split in blocks.
  1385. $blocks = explode("\t", $line);
  1386. # Add each blocks to the line.
  1387. $line = $blocks[0];
  1388. unset($blocks[0]); # Do not add first block twice.
  1389. foreach ($blocks as $block) {
  1390. # Calculate amount of space, insert spaces, insert block.
  1391. $amount = $this->tab_width -
  1392. $strlen($line, 'UTF-8') % $this->tab_width;
  1393. $line .= str_repeat(" ", $amount) . $block;
  1394. }
  1395. return $line;
  1396. }
  1397. function _initDetab() {
  1398. #
  1399. # Check for the availability of the function in the `utf8_strlen` property
  1400. # (initially `mb_strlen`). If the function is not available, create a
  1401. # function that will loosely count the number of UTF-8 characters with a
  1402. # regular expression.
  1403. #
  1404. if (function_exists($this->utf8_strlen)) return;
  1405. $this->utf8_strlen = create_function('$text', 'return preg_match_all(
  1406. "/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/",
  1407. $text, $m);');
  1408. }
  1409. function unhash($text) {
  1410. #
  1411. # Swap back in all the tags hashed by _HashHTMLBlocks.
  1412. #
  1413. return preg_replace_callback('/(.)\x1A[0-9]+\1/',
  1414. array(&$this, '_unhash_callback'), $text);
  1415. }
  1416. function _unhash_callback($matches) {
  1417. return $this->html_hashes[$matches[0]];
  1418. }
  1419. }
  1420. /*
  1421. PHP Markdown
  1422. ============
  1423. Description
  1424. -----------
  1425. This is a PHP translation of the original Markdown formatter written in
  1426. Perl by John Gruber.
  1427. Markdown is a text-to-HTML filter; it translates an easy-to-read /
  1428. easy-to-write structured text format into HTML. Markdown's text format
  1429. is most similar to that of plain text email, and supports features such
  1430. as headers, *emphasis*, code blocks, blockquotes, and links.
  1431. Markdown's syntax is designed not as a generic markup language, but
  1432. specifically to serve as a front-end to (X)HTML. You can use span-level
  1433. HTML tags anywhere in a Markdown document, and you can use block level
  1434. HTML tags (like <div> and <table> as well).
  1435. For more information about Markdown's syntax, see:
  1436. <http://daringfireball.net/projects/markdown/>
  1437. Bugs
  1438. ----
  1439. To file bug reports please send email to:
  1440. <michel.fortin@michelf.com>
  1441. Please include with your report: (1) the example input; (2) the output you
  1442. expected; (3) the output Markdown actually produced.
  1443. Version History
  1444. ---------------
  1445. See the readme file for detailed release notes for this version.
  1446. Copyright and License
  1447. ---------------------
  1448. PHP Markdown
  1449. Copyright (c) 2004-2009 Michel Fortin
  1450. <http://michelf.com/>
  1451. All rights reserved.
  1452. Based on Markdown
  1453. Copyright (c) 2003-2006 John Gruber
  1454. <http://daringfireball.net/>
  1455. All rights reserved.
  1456. Redistribution and use in source and binary forms, with or without
  1457. modification, are permitted provided that the following conditions are
  1458. met:
  1459. * Redistributions of source code must retain the above copyright notice,
  1460. this list of conditions and the following disclaimer.
  1461. * Redistributions in binary form must reproduce the above copyright
  1462. notice, this list of conditions and the following disclaimer in the
  1463. documentation and/or other materials provided with the distribution.
  1464. * Neither the name "Markdown" nor the names of its contributors may
  1465. be used to endorse or promote products derived from this software
  1466. without specific prior written permission.
  1467. This software is provided by the copyright holders and contributors "as
  1468. is" and any express or implied warranties, including, but not limited
  1469. to, the implied warranties of merchantability and fitness for a
  1470. particular purpose are disclaimed. In no event shall the copyright owner
  1471. or contributors be liable for any direct, indirect, incidental, special,
  1472. exemplary, or consequential damages (including, but not limited to,
  1473. procurement of substitute goods or services; loss of use, data, or
  1474. profits; or business interruption) however caused and on any theory of
  1475. liability, whether in contract, strict liability, or tort (including
  1476. negligence or otherwise) arising in any way out of the use of this
  1477. software, even if advised of the possibility of such damage.
  1478. */
  1479. ?>