markdown.php 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910
  1. <?php
  2. #
  3. # Markdown Extra - A text-to-HTML conversion tool for web writers
  4. #
  5. # PHP Markdown & Extra
  6. # Copyright (c) 2017-2018 Koseven Team
  7. #
  8. # PHP Markdown & Extra
  9. # Copyright (c) 2004-2008 Michel Fortin
  10. # <http://www.michelf.com/projects/php-markdown/>
  11. #
  12. # Original Markdown
  13. # Copyright (c) 2004-2006 John Gruber
  14. # <http://daringfireball.net/projects/markdown/>
  15. #
  16. define( 'MARKDOWN_VERSION', "1.0.1m" ); # Sat 21 Jun 2008
  17. define( 'MARKDOWNEXTRA_VERSION', "1.2.3" ); # Wed 31 Dec 2008
  18. #
  19. # Global default settings:
  20. #
  21. # Change to ">" for HTML output
  22. @define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX', " />");
  23. # Define the width of a tab for code blocks.
  24. @define( 'MARKDOWN_TAB_WIDTH', 4 );
  25. # Optional title attribute for footnote links and backlinks.
  26. @define( 'MARKDOWN_FN_LINK_TITLE', "" );
  27. @define( 'MARKDOWN_FN_BACKLINK_TITLE', "" );
  28. # Optional class attribute for footnote links and backlinks.
  29. @define( 'MARKDOWN_FN_LINK_CLASS', "" );
  30. @define( 'MARKDOWN_FN_BACKLINK_CLASS', "" );
  31. #
  32. # WordPress settings:
  33. #
  34. # Change to false to remove Markdown from posts and/or comments.
  35. @define( 'MARKDOWN_WP_POSTS', true );
  36. @define( 'MARKDOWN_WP_COMMENTS', true );
  37. ### Standard Function Interface ###
  38. @define( 'MARKDOWN_PARSER_CLASS', 'MarkdownExtra_Parser' );
  39. function Markdown($text) {
  40. #
  41. # Initialize the parser and return the result of its transform method.
  42. #
  43. # Setup static parser variable.
  44. static $parser;
  45. if (!isset($parser)) {
  46. $parser_class = MARKDOWN_PARSER_CLASS;
  47. $parser = new $parser_class;
  48. }
  49. # Transform text using parser.
  50. return $parser->transform($text);
  51. }
  52. ### WordPress Plugin Interface ###
  53. /*
  54. Plugin Name: Markdown Extra
  55. Plugin URI: http://www.michelf.com/projects/php-markdown/
  56. 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://www.michelf.com/projects/php-markdown/">More...</a>
  57. Version: 1.2.2
  58. Author: Michel Fortin
  59. Author URI: http://www.michelf.com/
  60. */
  61. if (isset($wp_version)) {
  62. # More details about how it works here:
  63. # <http://www.michelf.com/weblog/2005/wordpress-text-flow-vs-markdown/>
  64. # Post content and excerpts
  65. # - Remove WordPress paragraph generator.
  66. # - Run Markdown on excerpt, then remove all tags.
  67. # - Add paragraph tag around the excerpt, but remove it for the excerpt rss.
  68. if (MARKDOWN_WP_POSTS) {
  69. remove_filter('the_content', 'wpautop');
  70. remove_filter('the_content_rss', 'wpautop');
  71. remove_filter('the_excerpt', 'wpautop');
  72. add_filter('the_content', 'mdwp_MarkdownPost', 6);
  73. add_filter('the_content_rss', 'mdwp_MarkdownPost', 6);
  74. add_filter('get_the_excerpt', 'mdwp_MarkdownPost', 6);
  75. add_filter('get_the_excerpt', 'trim', 7);
  76. add_filter('the_excerpt', 'mdwp_add_p');
  77. add_filter('the_excerpt_rss', 'mdwp_strip_p');
  78. remove_filter('content_save_pre', 'balanceTags', 50);
  79. remove_filter('excerpt_save_pre', 'balanceTags', 50);
  80. add_filter('the_content', 'balanceTags', 50);
  81. add_filter('get_the_excerpt', 'balanceTags', 9);
  82. }
  83. # Add a footnote id prefix to posts when inside a loop.
  84. function mdwp_MarkdownPost($text) {
  85. static $parser;
  86. if (!$parser) {
  87. $parser_class = MARKDOWN_PARSER_CLASS;
  88. $parser = new $parser_class;
  89. }
  90. if (is_single() || is_page() || is_feed()) {
  91. $parser->fn_id_prefix = "";
  92. } else {
  93. $parser->fn_id_prefix = get_the_ID() . ".";
  94. }
  95. return $parser->transform($text);
  96. }
  97. # Comments
  98. # - Remove WordPress paragraph generator.
  99. # - Remove WordPress auto-link generator.
  100. # - Scramble important tags before passing them to the kses filter.
  101. # - Run Markdown on excerpt then remove paragraph tags.
  102. if (MARKDOWN_WP_COMMENTS) {
  103. remove_filter('comment_text', 'wpautop', 30);
  104. remove_filter('comment_text', 'make_clickable');
  105. add_filter('pre_comment_content', 'Markdown', 6);
  106. add_filter('pre_comment_content', 'mdwp_hide_tags', 8);
  107. add_filter('pre_comment_content', 'mdwp_show_tags', 12);
  108. add_filter('get_comment_text', 'Markdown', 6);
  109. add_filter('get_comment_excerpt', 'Markdown', 6);
  110. add_filter('get_comment_excerpt', 'mdwp_strip_p', 7);
  111. global $mdwp_hidden_tags, $mdwp_placeholders;
  112. $mdwp_hidden_tags = explode(' ',
  113. '<p> </p> <pre> </pre> <ol> </ol> <ul> </ul> <li> </li>');
  114. $mdwp_placeholders = explode(' ', str_rot13(
  115. 'pEj07ZbbBZ U1kqgh4w4p pre2zmeN6K QTi31t9pre ol0MP1jzJR '.
  116. 'ML5IjmbRol ulANi1NsGY J7zRLJqPul liA8ctl16T K9nhooUHli'));
  117. }
  118. function mdwp_add_p($text) {
  119. if (!preg_match('{^$|^<(p|ul|ol|dl|pre|blockquote)>}i', $text)) {
  120. $text = '<p>'.$text.'</p>';
  121. $text = preg_replace('{\n{2,}}', "</p>\n\n<p>", $text);
  122. }
  123. return $text;
  124. }
  125. function mdwp_strip_p($t) { return preg_replace('{</?p>}i', '', $t); }
  126. function mdwp_hide_tags($text) {
  127. global $mdwp_hidden_tags, $mdwp_placeholders;
  128. return str_replace($mdwp_hidden_tags, $mdwp_placeholders, $text);
  129. }
  130. function mdwp_show_tags($text) {
  131. global $mdwp_hidden_tags, $mdwp_placeholders;
  132. return str_replace($mdwp_placeholders, $mdwp_hidden_tags, $text);
  133. }
  134. }
  135. ### bBlog Plugin Info ###
  136. function identify_modifier_markdown() {
  137. return [
  138. 'name' => 'markdown',
  139. 'type' => 'modifier',
  140. 'nicename' => 'PHP Markdown Extra',
  141. 'description' => 'A text-to-HTML conversion tool for web writers',
  142. 'authors' => 'Michel Fortin and John Gruber',
  143. 'licence' => 'GPL',
  144. 'version' => MARKDOWNEXTRA_VERSION,
  145. '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://www.michelf.com/projects/php-markdown/">More...</a>',
  146. ];
  147. }
  148. ### Smarty Modifier Interface ###
  149. function smarty_modifier_markdown($text) {
  150. return Markdown($text);
  151. }
  152. ### Textile Compatibility Mode ###
  153. # Rename this file to "classTextile.php" and it can replace Textile everywhere.
  154. if (strcasecmp(substr(__FILE__, -16), "classTextile.php") == 0) {
  155. # Try to include PHP SmartyPants. Should be in the same directory.
  156. @include_once 'smartypants.php';
  157. # Fake Textile class. It calls Markdown instead.
  158. class Textile {
  159. function TextileThis($text, $lite='', $encode='') {
  160. if ($lite == '' && $encode == '') $text = Markdown($text);
  161. if (function_exists('SmartyPants')) $text = SmartyPants($text);
  162. return $text;
  163. }
  164. # Fake restricted version: restrictions are not supported for now.
  165. function TextileRestricted($text, $lite='', $noimage='') {
  166. return $this->TextileThis($text, $lite);
  167. }
  168. # Workaround to ensure compatibility with TextPattern 4.0.3.
  169. function blockLite($text) { return $text; }
  170. }
  171. }
  172. #
  173. # Markdown Parser Class
  174. #
  175. class Markdown_Parser {
  176. # Regex to match balanced [brackets].
  177. # Needed to insert a maximum bracked depth while converting to PHP.
  178. var $nested_brackets_depth = 6;
  179. var $nested_brackets_re;
  180. var $nested_url_parenthesis_depth = 4;
  181. var $nested_url_parenthesis_re;
  182. # Table of hash values for escaped characters:
  183. var $escape_chars = '\`*_{}[]()>#+-.!';
  184. var $escape_chars_re;
  185. # Change to ">" for HTML output.
  186. var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX;
  187. var $tab_width = MARKDOWN_TAB_WIDTH;
  188. # Change to `true` to disallow markup or entities.
  189. var $no_markup = false;
  190. var $no_entities = false;
  191. # Predefined urls and titles for reference links and images.
  192. var $predef_urls = [];
  193. var $predef_titles = [];
  194. function __construct() {
  195. #
  196. # Constructor function. Initialize appropriate member variables.
  197. #
  198. $this->_initDetab();
  199. $this->prepareItalicsAndBold();
  200. $this->nested_brackets_re =
  201. str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth).
  202. str_repeat('\])*', $this->nested_brackets_depth);
  203. $this->nested_url_parenthesis_re =
  204. str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth).
  205. str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth);
  206. $this->escape_chars_re = '['.preg_quote($this->escape_chars).']';
  207. # Sort document, block, and span gamut in ascendent priority order.
  208. asort($this->document_gamut);
  209. asort($this->block_gamut);
  210. asort($this->span_gamut);
  211. }
  212. # Internal hashes used during transformation.
  213. var $urls = [];
  214. var $titles = [];
  215. var $html_hashes = [];
  216. # Status flag to avoid invalid nesting.
  217. var $in_anchor = false;
  218. function setup() {
  219. #
  220. # Called before the transformation process starts to setup parser
  221. # states.
  222. #
  223. # Clear global hashes.
  224. $this->urls = $this->predef_urls;
  225. $this->titles = $this->predef_titles;
  226. $this->html_hashes = [];
  227. $in_anchor = false;
  228. }
  229. function teardown() {
  230. #
  231. # Called after the transformation process to clear any variable
  232. # which may be taking up memory unnecessarly.
  233. #
  234. $this->urls = [];
  235. $this->titles = [];
  236. $this->html_hashes = [];
  237. }
  238. function transform($text) {
  239. #
  240. # Main function. Performs some preprocessing on the input text
  241. # and pass it through the document gamut.
  242. #
  243. $this->setup();
  244. # Remove UTF-8 BOM and marker character in input, if present.
  245. $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text);
  246. # Standardize line endings:
  247. # DOS to Unix and Mac to Unix
  248. $text = preg_replace('{\r\n?}', "\n", $text);
  249. # Make sure $text ends with a couple of newlines:
  250. $text .= "\n\n";
  251. # Convert all tabs to spaces.
  252. $text = $this->detab($text);
  253. # Turn block-level HTML blocks into hash entries
  254. $text = $this->hashHTMLBlocks($text);
  255. # Strip any lines consisting only of spaces and tabs.
  256. # This makes subsequent regexen easier to write, because we can
  257. # match consecutive blank lines with /\n+/ instead of something
  258. # contorted like /[ ]*\n+/ .
  259. $text = preg_replace('/^[ ]+$/m', '', $text);
  260. # Run document gamut methods.
  261. foreach ($this->document_gamut as $method => $priority) {
  262. $text = $this->$method($text);
  263. }
  264. $this->teardown();
  265. return $text . "\n";
  266. }
  267. var $document_gamut = [
  268. # Strip link definitions, store in hashes.
  269. "stripLinkDefinitions" => 20,
  270. "runBasicBlockGamut" => 30,
  271. ];
  272. function stripLinkDefinitions($text) {
  273. #
  274. # Strips link definitions from text, stores the URLs and titles in
  275. # hash references.
  276. #
  277. $less_than_tab = $this->tab_width - 1;
  278. # Link defs are in the form: ^[id]: url "optional title"
  279. $text = preg_replace_callback('{
  280. ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1
  281. [ ]*
  282. \n? # maybe *one* newline
  283. [ ]*
  284. <?(\S+?)>? # url = $2
  285. [ ]*
  286. \n? # maybe one newline
  287. [ ]*
  288. (?:
  289. (?<=\s) # lookbehind for whitespace
  290. ["(]
  291. (.*?) # title = $3
  292. [")]
  293. [ ]*
  294. )? # title is optional
  295. (?:\n+|\Z)
  296. }xm',
  297. [&$this, '_stripLinkDefinitions_callback'],
  298. $text);
  299. return $text;
  300. }
  301. function _stripLinkDefinitions_callback($matches) {
  302. $link_id = strtolower($matches[1]);
  303. $this->urls[$link_id] = $matches[2];
  304. $this->titles[$link_id] =& $matches[3];
  305. return ''; # String that will replace the block
  306. }
  307. function hashHTMLBlocks($text) {
  308. if ($this->no_markup) return $text;
  309. $less_than_tab = $this->tab_width - 1;
  310. # Hashify HTML blocks:
  311. # We only want to do this for block-level HTML tags, such as headers,
  312. # lists, and tables. That's because we still want to wrap <p>s around
  313. # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  314. # phrase emphasis, and spans. The list of tags we're looking for is
  315. # hard-coded:
  316. #
  317. # * List "a" is made of tags which can be both inline or block-level.
  318. # These will be treated block-level when the start tag is alone on
  319. # its line, otherwise they're not matched here and will be taken as
  320. # inline later.
  321. # * List "b" is made of tags which are always block-level;
  322. #
  323. $block_tags_a_re = 'ins|del';
  324. $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'.
  325. 'script|noscript|form|fieldset|iframe|math';
  326. # Regular expression for the content of a block tag.
  327. $nested_tags_level = 4;
  328. $attr = '
  329. (?> # optional tag attributes
  330. \s # starts with whitespace
  331. (?>
  332. [^>"/]+ # text outside quotes
  333. |
  334. /+(?!>) # slash not followed by ">"
  335. |
  336. "[^"]*" # text inside double quotes (tolerate ">")
  337. |
  338. \'[^\']*\' # text inside single quotes (tolerate ">")
  339. )*
  340. )?
  341. ';
  342. $content =
  343. str_repeat('
  344. (?>
  345. [^<]+ # content without tag
  346. |
  347. <\2 # nested opening tag
  348. '.$attr.' # attributes
  349. (?>
  350. />
  351. |
  352. >', $nested_tags_level). # end of opening tag
  353. '.*?'. # last level nested tag content
  354. str_repeat('
  355. </\2\s*> # closing nested tag
  356. )
  357. |
  358. <(?!/\2\s*> # other tags with a different name
  359. )
  360. )*',
  361. $nested_tags_level);
  362. $content2 = str_replace('\2', '\3', $content);
  363. # First, look for nested blocks, e.g.:
  364. # <div>
  365. # <div>
  366. # tags for inner block must be indented.
  367. # </div>
  368. # </div>
  369. #
  370. # The outermost tags must start at the left margin for this to match, and
  371. # the inner nested divs must be indented.
  372. # We need to do this before the next, more liberal match, because the next
  373. # match will start at the first `<div>` and stop at the first `</div>`.
  374. $text = preg_replace_callback('{(?>
  375. (?>
  376. (?<=\n\n) # Starting after a blank line
  377. | # or
  378. \A\n? # the beginning of the doc
  379. )
  380. ( # save in $1
  381. # Match from `\n<tag>` to `</tag>\n`, handling nested tags
  382. # in between.
  383. [ ]{0,'.$less_than_tab.'}
  384. <('.$block_tags_b_re.')# start tag = $2
  385. '.$attr.'> # attributes followed by > and \n
  386. '.$content.' # content, support nesting
  387. </\2> # the matching end tag
  388. [ ]* # trailing spaces/tabs
  389. (?=\n+|\Z) # followed by a newline or end of document
  390. | # Special version for tags of group a.
  391. [ ]{0,'.$less_than_tab.'}
  392. <('.$block_tags_a_re.')# start tag = $3
  393. '.$attr.'>[ ]*\n # attributes followed by >
  394. '.$content2.' # content, support nesting
  395. </\3> # the matching end tag
  396. [ ]* # trailing spaces/tabs
  397. (?=\n+|\Z) # followed by a newline or end of document
  398. | # Special case just for <hr />. It was easier to make a special
  399. # case than to make the other regex more complicated.
  400. [ ]{0,'.$less_than_tab.'}
  401. <(hr) # start tag = $2
  402. '.$attr.' # attributes
  403. /?> # the matching end tag
  404. [ ]*
  405. (?=\n{2,}|\Z) # followed by a blank line or end of document
  406. | # Special case for standalone HTML comments:
  407. [ ]{0,'.$less_than_tab.'}
  408. (?s:
  409. <!-- .*? -->
  410. )
  411. [ ]*
  412. (?=\n{2,}|\Z) # followed by a blank line or end of document
  413. | # PHP and ASP-style processor instructions (<? and <%)
  414. [ ]{0,'.$less_than_tab.'}
  415. (?s:
  416. <([?%]) # $2
  417. .*?
  418. \2>
  419. )
  420. [ ]*
  421. (?=\n{2,}|\Z) # followed by a blank line or end of document
  422. )
  423. )}Sxmi',
  424. [&$this, '_hashHTMLBlocks_callback'],
  425. $text);
  426. return $text;
  427. }
  428. function _hashHTMLBlocks_callback($matches) {
  429. $text = $matches[1];
  430. $key = $this->hashBlock($text);
  431. return "\n\n$key\n\n";
  432. }
  433. function hashPart($text, $boundary = 'X') {
  434. #
  435. # Called whenever a tag must be hashed when a function insert an atomic
  436. # element in the text stream. Passing $text to through this function gives
  437. # a unique text-token which will be reverted back when calling unhash.
  438. #
  439. # The $boundary argument specify what character should be used to surround
  440. # the token. By convension, "B" is used for block elements that needs not
  441. # to be wrapped into paragraph tags at the end, ":" is used for elements
  442. # that are word separators and "X" is used in the general case.
  443. #
  444. # Swap back any tag hash found in $text so we do not have to `unhash`
  445. # multiple times at the end.
  446. $text = $this->unhash($text);
  447. # Then hash the block.
  448. static $i = 0;
  449. $key = "$boundary\x1A" . ++$i . $boundary;
  450. $this->html_hashes[$key] = $text;
  451. return $key; # String that will replace the tag.
  452. }
  453. function hashBlock($text) {
  454. #
  455. # Shortcut function for hashPart with block-level boundaries.
  456. #
  457. return $this->hashPart($text, 'B');
  458. }
  459. var $block_gamut = [
  460. #
  461. # These are all the transformations that form block-level
  462. # tags like paragraphs, headers, and list items.
  463. #
  464. "doHeaders" => 10,
  465. "doHorizontalRules" => 20,
  466. "doLists" => 40,
  467. "doCodeBlocks" => 50,
  468. "doBlockQuotes" => 60,
  469. ];
  470. function runBlockGamut($text) {
  471. #
  472. # Run block gamut tranformations.
  473. #
  474. # We need to escape raw HTML in Markdown source before doing anything
  475. # else. This need to be done for each block, and not only at the
  476. # begining in the Markdown function since hashed blocks can be part of
  477. # list items and could have been indented. Indented blocks would have
  478. # been seen as a code block in a previous pass of hashHTMLBlocks.
  479. $text = $this->hashHTMLBlocks($text);
  480. return $this->runBasicBlockGamut($text);
  481. }
  482. function runBasicBlockGamut($text) {
  483. #
  484. # Run block gamut tranformations, without hashing HTML blocks. This is
  485. # useful when HTML blocks are known to be already hashed, like in the first
  486. # whole-document pass.
  487. #
  488. foreach ($this->block_gamut as $method => $priority) {
  489. $text = $this->$method($text);
  490. }
  491. # Finally form paragraph and restore hashed blocks.
  492. $text = $this->formParagraphs($text);
  493. return $text;
  494. }
  495. function doHorizontalRules($text) {
  496. # Do Horizontal Rules:
  497. return preg_replace(
  498. '{
  499. ^[ ]{0,3} # Leading space
  500. ([-*_]) # $1: First marker
  501. (?> # Repeated marker group
  502. [ ]{0,2} # Zero, one, or two spaces.
  503. \1 # Marker character
  504. ){2,} # Group repeated at least twice
  505. [ ]* # Tailing spaces
  506. $ # End of line.
  507. }mx',
  508. "\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n",
  509. $text);
  510. }
  511. var $span_gamut = [
  512. #
  513. # These are all the transformations that occur *within* block-level
  514. # tags like paragraphs, headers, and list items.
  515. #
  516. # Process character escapes, code spans, and inline HTML
  517. # in one shot.
  518. "parseSpan" => -30,
  519. # Process anchor and image tags. Images must come first,
  520. # because ![foo][f] looks like an anchor.
  521. "doImages" => 10,
  522. "doAnchors" => 20,
  523. # Make links out of things like `<http://example.com/>`
  524. # Must come after doAnchors, because you can use < and >
  525. # delimiters in inline links like [this](<url>).
  526. "doAutoLinks" => 30,
  527. "encodeAmpsAndAngles" => 40,
  528. "doItalicsAndBold" => 50,
  529. "doHardBreaks" => 60,
  530. ];
  531. function runSpanGamut($text) {
  532. #
  533. # Run span gamut tranformations.
  534. #
  535. foreach ($this->span_gamut as $method => $priority) {
  536. $text = $this->$method($text);
  537. }
  538. return $text;
  539. }
  540. function doHardBreaks($text) {
  541. # Do hard breaks:
  542. return preg_replace_callback('/ {2,}\n/',
  543. [&$this, '_doHardBreaks_callback'], $text);
  544. }
  545. function _doHardBreaks_callback($matches) {
  546. return $this->hashPart("<br$this->empty_element_suffix\n");
  547. }
  548. function doAnchors($text) {
  549. #
  550. # Turn Markdown link shortcuts into XHTML <a> tags.
  551. #
  552. if ($this->in_anchor) return $text;
  553. $this->in_anchor = true;
  554. #
  555. # First, handle reference-style links: [link text] [id]
  556. #
  557. $text = preg_replace_callback('{
  558. ( # wrap whole match in $1
  559. \[
  560. ('.$this->nested_brackets_re.') # link text = $2
  561. \]
  562. [ ]? # one optional space
  563. (?:\n[ ]*)? # one optional newline followed by spaces
  564. \[
  565. (.*?) # id = $3
  566. \]
  567. )
  568. }xs',
  569. [&$this, '_doAnchors_reference_callback'], $text);
  570. #
  571. # Next, inline-style links: [link text](url "optional title")
  572. #
  573. $text = preg_replace_callback('{
  574. ( # wrap whole match in $1
  575. \[
  576. ('.$this->nested_brackets_re.') # link text = $2
  577. \]
  578. \( # literal paren
  579. [ ]*
  580. (?:
  581. <(\S*)> # href = $3
  582. |
  583. ('.$this->nested_url_parenthesis_re.') # href = $4
  584. )
  585. [ ]*
  586. ( # $5
  587. ([\'"]) # quote char = $6
  588. (.*?) # Title = $7
  589. \6 # matching quote
  590. [ ]* # ignore any spaces/tabs between closing quote and )
  591. )? # title is optional
  592. \)
  593. )
  594. }xs',
  595. [&$this, '_DoAnchors_inline_callback'], $text);
  596. #
  597. # Last, handle reference-style shortcuts: [link text]
  598. # These must come last in case you've also got [link test][1]
  599. # or [link test](/foo)
  600. #
  601. // $text = preg_replace_callback('{
  602. // ( # wrap whole match in $1
  603. // \[
  604. // ([^\[\]]+) # link text = $2; can\'t contain [ or ]
  605. // \]
  606. // )
  607. // }xs',
  608. // array(&$this, '_doAnchors_reference_callback'), $text);
  609. $this->in_anchor = false;
  610. return $text;
  611. }
  612. function _doAnchors_reference_callback($matches) {
  613. $whole_match = $matches[1];
  614. $link_text = $matches[2];
  615. $link_id =& $matches[3];
  616. if ($link_id == "") {
  617. # for shortcut links like [this][] or [this].
  618. $link_id = $link_text;
  619. }
  620. # lower-case and turn embedded newlines into spaces
  621. $link_id = strtolower($link_id);
  622. $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
  623. if (isset($this->urls[$link_id])) {
  624. $url = $this->urls[$link_id];
  625. $url = $this->encodeAttribute($url);
  626. $result = "<a href=\"$url\"";
  627. if ( isset( $this->titles[$link_id] ) ) {
  628. $title = $this->titles[$link_id];
  629. $title = $this->encodeAttribute($title);
  630. $result .= " title=\"$title\"";
  631. }
  632. $link_text = $this->runSpanGamut($link_text);
  633. $result .= ">$link_text</a>";
  634. $result = $this->hashPart($result);
  635. }
  636. else {
  637. $result = $whole_match;
  638. }
  639. return $result;
  640. }
  641. function _doAnchors_inline_callback($matches) {
  642. $whole_match = $matches[1];
  643. $link_text = $this->runSpanGamut($matches[2]);
  644. $url = $matches[3] == '' ? $matches[4] : $matches[3];
  645. $title =& $matches[7];
  646. $url = $this->encodeAttribute($url);
  647. $result = "<a href=\"$url\"";
  648. if (isset($title)) {
  649. $title = $this->encodeAttribute($title);
  650. $result .= " title=\"$title\"";
  651. }
  652. $link_text = $this->runSpanGamut($link_text);
  653. $result .= ">$link_text</a>";
  654. return $this->hashPart($result);
  655. }
  656. function doImages($text) {
  657. #
  658. # Turn Markdown image shortcuts into <img> tags.
  659. #
  660. #
  661. # First, handle reference-style labeled images: ![alt text][id]
  662. #
  663. $text = preg_replace_callback('{
  664. ( # wrap whole match in $1
  665. !\[
  666. ('.$this->nested_brackets_re.') # alt text = $2
  667. \]
  668. [ ]? # one optional space
  669. (?:\n[ ]*)? # one optional newline followed by spaces
  670. \[
  671. (.*?) # id = $3
  672. \]
  673. )
  674. }xs',
  675. [&$this, '_doImages_reference_callback'], $text);
  676. #
  677. # Next, handle inline images: ![alt text](url "optional title")
  678. # Don't forget: encode * and _
  679. #
  680. $text = preg_replace_callback('{
  681. ( # wrap whole match in $1
  682. !\[
  683. ('.$this->nested_brackets_re.') # alt text = $2
  684. \]
  685. \s? # One optional whitespace character
  686. \( # literal paren
  687. [ ]*
  688. (?:
  689. <(\S*)> # src url = $3
  690. |
  691. ('.$this->nested_url_parenthesis_re.') # src url = $4
  692. )
  693. [ ]*
  694. ( # $5
  695. ([\'"]) # quote char = $6
  696. (.*?) # title = $7
  697. \6 # matching quote
  698. [ ]*
  699. )? # title is optional
  700. \)
  701. )
  702. }xs',
  703. [&$this, '_doImages_inline_callback'], $text);
  704. return $text;
  705. }
  706. function _doImages_reference_callback($matches) {
  707. $whole_match = $matches[1];
  708. $alt_text = $matches[2];
  709. $link_id = strtolower($matches[3]);
  710. if ($link_id == "") {
  711. $link_id = strtolower($alt_text); # for shortcut links like ![this][].
  712. }
  713. $alt_text = $this->encodeAttribute($alt_text);
  714. if (isset($this->urls[$link_id])) {
  715. $url = $this->encodeAttribute($this->urls[$link_id]);
  716. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  717. if (isset($this->titles[$link_id])) {
  718. $title = $this->titles[$link_id];
  719. $title = $this->encodeAttribute($title);
  720. $result .= " title=\"$title\"";
  721. }
  722. $result .= $this->empty_element_suffix;
  723. $result = $this->hashPart($result);
  724. }
  725. else {
  726. # If there's no such link ID, leave intact:
  727. $result = $whole_match;
  728. }
  729. return $result;
  730. }
  731. function _doImages_inline_callback($matches) {
  732. $whole_match = $matches[1];
  733. $alt_text = $matches[2];
  734. $url = $matches[3] == '' ? $matches[4] : $matches[3];
  735. $title =& $matches[7];
  736. $alt_text = $this->encodeAttribute($alt_text);
  737. $url = $this->encodeAttribute($url);
  738. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  739. if (isset($title)) {
  740. $title = $this->encodeAttribute($title);
  741. $result .= " title=\"$title\""; # $title already quoted
  742. }
  743. $result .= $this->empty_element_suffix;
  744. return $this->hashPart($result);
  745. }
  746. function doHeaders($text) {
  747. # Setext-style headers:
  748. # Header 1
  749. # ========
  750. #
  751. # Header 2
  752. # --------
  753. #
  754. $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx',
  755. [&$this, '_doHeaders_callback_setext'], $text);
  756. # atx-style headers:
  757. # # Header 1
  758. # ## Header 2
  759. # ## Header 2 with closing hashes ##
  760. # ...
  761. # ###### Header 6
  762. #
  763. $text = preg_replace_callback('{
  764. ^(\#{1,6}) # $1 = string of #\'s
  765. [ ]*
  766. (.+?) # $2 = Header text
  767. [ ]*
  768. \#* # optional closing #\'s (not counted)
  769. \n+
  770. }xm',
  771. [&$this, '_doHeaders_callback_atx'], $text);
  772. return $text;
  773. }
  774. function _doHeaders_callback_setext($matches) {
  775. # Terrible hack to check we haven't found an empty list item.
  776. if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1]))
  777. return $matches[0];
  778. $level = $matches[2][0] == '=' ? 1 : 2;
  779. $block = "<h$level>".$this->runSpanGamut($matches[1])."</h$level>";
  780. return "\n" . $this->hashBlock($block) . "\n\n";
  781. }
  782. function _doHeaders_callback_atx($matches) {
  783. $level = strlen($matches[1]);
  784. $block = "<h$level>".$this->runSpanGamut($matches[2])."</h$level>";
  785. return "\n" . $this->hashBlock($block) . "\n\n";
  786. }
  787. function doLists($text) {
  788. #
  789. # Form HTML ordered (numbered) and unordered (bulleted) lists.
  790. #
  791. $less_than_tab = $this->tab_width - 1;
  792. # Re-usable patterns to match list item bullets and number markers:
  793. $marker_ul_re = '[*+-]';
  794. $marker_ol_re = '\d+[.]';
  795. $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  796. $markers_relist = [$marker_ul_re, $marker_ol_re];
  797. foreach ($markers_relist as $marker_re) {
  798. # Re-usable pattern to match any entirel ul or ol list:
  799. $whole_list_re = '
  800. ( # $1 = whole list
  801. ( # $2
  802. [ ]{0,'.$less_than_tab.'}
  803. ('.$marker_re.') # $3 = first list item marker
  804. [ ]+
  805. )
  806. (?s:.+?)
  807. ( # $4
  808. \z
  809. |
  810. \n{2,}
  811. (?=\S)
  812. (?! # Negative lookahead for another list item marker
  813. [ ]*
  814. '.$marker_re.'[ ]+
  815. )
  816. )
  817. )
  818. '; // mx
  819. # We use a different prefix before nested lists than top-level lists.
  820. # See extended comment in _ProcessListItems().
  821. if ($this->list_level) {
  822. $text = preg_replace_callback('{
  823. ^
  824. '.$whole_list_re.'
  825. }mx',
  826. [&$this, '_doLists_callback'], $text);
  827. }
  828. else {
  829. $text = preg_replace_callback('{
  830. (?:(?<=\n)\n|\A\n?) # Must eat the newline
  831. '.$whole_list_re.'
  832. }mx',
  833. [&$this, '_doLists_callback'], $text);
  834. }
  835. }
  836. return $text;
  837. }
  838. function _doLists_callback($matches) {
  839. # Re-usable patterns to match list item bullets and number markers:
  840. $marker_ul_re = '[*+-]';
  841. $marker_ol_re = '\d+[.]';
  842. $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  843. $list = $matches[1];
  844. $list_type = preg_match("/$marker_ul_re/", $matches[3]) ? "ul" : "ol";
  845. $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re );
  846. $list .= "\n";
  847. $result = $this->processListItems($list, $marker_any_re);
  848. $result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>");
  849. return "\n". $result ."\n\n";
  850. }
  851. var $list_level = 0;
  852. function processListItems($list_str, $marker_any_re) {
  853. #
  854. # Process the contents of a single ordered or unordered list, splitting it
  855. # into individual list items.
  856. #
  857. # The $this->list_level global keeps track of when we're inside a list.
  858. # Each time we enter a list, we increment it; when we leave a list,
  859. # we decrement. If it's zero, we're not in a list anymore.
  860. #
  861. # We do this because when we're not inside a list, we want to treat
  862. # something like this:
  863. #
  864. # I recommend upgrading to version
  865. # 8. Oops, now this line is treated
  866. # as a sub-list.
  867. #
  868. # As a single paragraph, despite the fact that the second line starts
  869. # with a digit-period-space sequence.
  870. #
  871. # Whereas when we're inside a list (or sub-list), that line will be
  872. # treated as the start of a sub-list. What a kludge, huh? This is
  873. # an aspect of Markdown's syntax that's hard to parse perfectly
  874. # without resorting to mind-reading. Perhaps the solution is to
  875. # change the syntax rules such that sub-lists must start with a
  876. # starting cardinal number; e.g. "1." or "a.".
  877. $this->list_level++;
  878. # trim trailing blank lines:
  879. $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  880. $list_str = preg_replace_callback('{
  881. (\n)? # leading line = $1
  882. (^[ ]*) # leading whitespace = $2
  883. ('.$marker_any_re.' # list marker and space = $3
  884. (?:[ ]+|(?=\n)) # space only required if item is not empty
  885. )
  886. ((?s:.*?)) # list item text = $4
  887. (?:(\n+(?=\n))|\n) # tailing blank line = $5
  888. (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n))))
  889. }xm',
  890. [&$this, '_processListItems_callback'], $list_str);
  891. $this->list_level--;
  892. return $list_str;
  893. }
  894. function _processListItems_callback($matches) {
  895. $item = $matches[4];
  896. $leading_line =& $matches[1];
  897. $leading_space =& $matches[2];
  898. $marker_space = $matches[3];
  899. $tailing_blank_line =& $matches[5];
  900. if ($leading_line || $tailing_blank_line ||
  901. preg_match('/\n{2,}/', $item))
  902. {
  903. # Replace marker with the appropriate whitespace indentation
  904. $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;
  905. $item = $this->runBlockGamut($this->outdent($item)."\n");
  906. }
  907. else {
  908. # Recursion for sub-lists:
  909. $item = $this->doLists($this->outdent($item));
  910. $item = preg_replace('/\n+$/', '', $item);
  911. $item = $this->runSpanGamut($item);
  912. }
  913. return "<li>" . $item . "</li>\n";
  914. }
  915. function doCodeBlocks($text) {
  916. #
  917. # Process Markdown `<pre><code>` blocks.
  918. #
  919. $text = preg_replace_callback('{
  920. (?:\n\n|\A\n?)
  921. ( # $1 = the code block -- one or more lines, starting with a space/tab
  922. (?>
  923. [ ]{'.$this->tab_width.'} # Lines must start with a tab or a tab-width of spaces
  924. .*\n+
  925. )+
  926. )
  927. ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
  928. }xm',
  929. [&$this, '_doCodeBlocks_callback'], $text);
  930. return $text;
  931. }
  932. function _doCodeBlocks_callback($matches) {
  933. $codeblock = $matches[1];
  934. $codeblock = $this->outdent($codeblock);
  935. $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
  936. # trim leading newlines and trailing newlines
  937. $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
  938. $codeblock = "<pre><code>$codeblock\n</code></pre>";
  939. return "\n\n".$this->hashBlock($codeblock)."\n\n";
  940. }
  941. function makeCodeSpan($code) {
  942. #
  943. # Create a code span markup for $code. Called from handleSpanToken.
  944. #
  945. $code = htmlspecialchars(trim($code), ENT_NOQUOTES);
  946. return $this->hashPart("<code>$code</code>");
  947. }
  948. var $em_relist = [
  949. '' => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S)(?![.,:;]\s)',
  950. '*' => '(?<=\S)(?<!\*)\*(?!\*)',
  951. '_' => '(?<=\S)(?<!_)_(?!_)',
  952. ];
  953. var $strong_relist = [
  954. '' => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S)(?![.,:;]\s)',
  955. '**' => '(?<=\S)(?<!\*)\*\*(?!\*)',
  956. '__' => '(?<=\S)(?<!_)__(?!_)',
  957. ];
  958. var $em_strong_relist = [
  959. '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S)(?![.,:;]\s)',
  960. '***' => '(?<=\S)(?<!\*)\*\*\*(?!\*)',
  961. '___' => '(?<=\S)(?<!_)___(?!_)',
  962. ];
  963. var $em_strong_prepared_relist;
  964. function prepareItalicsAndBold() {
  965. #
  966. # Prepare regular expressions for seraching emphasis tokens in any
  967. # context.
  968. #
  969. foreach ($this->em_relist as $em => $em_re) {
  970. foreach ($this->strong_relist as $strong => $strong_re) {
  971. # Construct list of allowed token expressions.
  972. $token_relist = [];
  973. if (isset($this->em_strong_relist["$em$strong"])) {
  974. $token_relist[] = $this->em_strong_relist["$em$strong"];
  975. }
  976. $token_relist[] = $em_re;
  977. $token_relist[] = $strong_re;
  978. # Construct master expression from list.
  979. $token_re = '{('. implode('|', $token_relist) .')}';
  980. $this->em_strong_prepared_relist["$em$strong"] = $token_re;
  981. }
  982. }
  983. }
  984. function doItalicsAndBold($text) {
  985. $token_stack = [''];
  986. $text_stack = [''];
  987. $em = '';
  988. $strong = '';
  989. $tree_char_em = false;
  990. while (1) {
  991. #
  992. # Get prepared regular expression for seraching emphasis tokens
  993. # in current context.
  994. #
  995. $token_re = $this->em_strong_prepared_relist["$em$strong"];
  996. #
  997. # Each loop iteration seach for the next emphasis token.
  998. # Each token is then passed to handleSpanToken.
  999. #
  1000. $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
  1001. $text_stack[0] .= $parts[0];
  1002. $token =& $parts[1];
  1003. $text =& $parts[2];
  1004. if (empty($token)) {
  1005. # Reached end of text span: empty stack without emitting.
  1006. # any more emphasis.
  1007. while ($token_stack[0]) {
  1008. $text_stack[1] .= array_shift($token_stack);
  1009. $text_stack[0] .= array_shift($text_stack);
  1010. }
  1011. break;
  1012. }
  1013. $token_len = strlen($token);
  1014. if ($tree_char_em) {
  1015. # Reached closing marker while inside a three-char emphasis.
  1016. if ($token_len == 3) {
  1017. # Three-char closing marker, close em and strong.
  1018. array_shift($token_stack);
  1019. $span = array_shift($text_stack);
  1020. $span = $this->runSpanGamut($span);
  1021. $span = "<strong><em>$span</em></strong>";
  1022. $text_stack[0] .= $this->hashPart($span);
  1023. $em = '';
  1024. $strong = '';
  1025. } else {
  1026. # Other closing marker: close one em or strong and
  1027. # change current token state to match the other
  1028. $token_stack[0] = str_repeat($token[0], 3-$token_len);
  1029. $tag = $token_len == 2 ? "strong" : "em";
  1030. $span = $text_stack[0];
  1031. $span = $this->runSpanGamut($span);
  1032. $span = "<$tag>$span</$tag>";
  1033. $text_stack[0] = $this->hashPart($span);
  1034. $$tag = ''; # $$tag stands for $em or $strong
  1035. }
  1036. $tree_char_em = false;
  1037. } else if ($token_len == 3) {
  1038. if ($em) {
  1039. # Reached closing marker for both em and strong.
  1040. # Closing strong marker:
  1041. for ($i = 0; $i < 2; ++$i) {
  1042. $shifted_token = array_shift($token_stack);
  1043. $tag = strlen($shifted_token) == 2 ? "strong" : "em";
  1044. $span = array_shift($text_stack);
  1045. $span = $this->runSpanGamut($span);
  1046. $span = "<$tag>$span</$tag>";
  1047. $text_stack[0] .= $this->hashPart($span);
  1048. $$tag = ''; # $$tag stands for $em or $strong
  1049. }
  1050. } else {
  1051. # Reached opening three-char emphasis marker. Push on token
  1052. # stack; will be handled by the special condition above.
  1053. $em = $token[0];
  1054. $strong = "$em$em";
  1055. array_unshift($token_stack, $token);
  1056. array_unshift($text_stack, '');
  1057. $tree_char_em = true;
  1058. }
  1059. } else if ($token_len == 2) {
  1060. if ($strong) {
  1061. # Unwind any dangling emphasis marker:
  1062. if (strlen($token_stack[0]) == 1) {
  1063. $text_stack[1] .= array_shift($token_stack);
  1064. $text_stack[0] .= array_shift($text_stack);
  1065. }
  1066. # Closing strong marker:
  1067. array_shift($token_stack);
  1068. $span = array_shift($text_stack);
  1069. $span = $this->runSpanGamut($span);
  1070. $span = "<strong>$span</strong>";
  1071. $text_stack[0] .= $this->hashPart($span);
  1072. $strong = '';
  1073. } else {
  1074. array_unshift($token_stack, $token);
  1075. array_unshift($text_stack, '');
  1076. $strong = $token;
  1077. }
  1078. } else {
  1079. # Here $token_len == 1
  1080. if ($em) {
  1081. if (strlen($token_stack[0]) == 1) {
  1082. # Closing emphasis marker:
  1083. array_shift($token_stack);
  1084. $span = array_shift($text_stack);
  1085. $span = $this->runSpanGamut($span);
  1086. $span = "<em>$span</em>";
  1087. $text_stack[0] .= $this->hashPart($span);
  1088. $em = '';
  1089. } else {
  1090. $text_stack[0] .= $token;
  1091. }
  1092. } else {
  1093. array_unshift($token_stack, $token);
  1094. array_unshift($text_stack, '');
  1095. $em = $token;
  1096. }
  1097. }
  1098. }
  1099. return $text_stack[0];
  1100. }
  1101. function doBlockQuotes($text) {
  1102. $text = preg_replace_callback('/
  1103. ( # Wrap whole match in $1
  1104. (?>
  1105. ^[ ]*>[ ]? # ">" at the start of a line
  1106. .+\n # rest of the first line
  1107. (.+\n)* # subsequent consecutive lines
  1108. \n* # blanks
  1109. )+
  1110. )
  1111. /xm',
  1112. [&$this, '_doBlockQuotes_callback'], $text);
  1113. return $text;
  1114. }
  1115. function _doBlockQuotes_callback($matches) {
  1116. $bq = $matches[1];
  1117. # trim one level of quoting - trim whitespace-only lines
  1118. $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
  1119. $bq = $this->runBlockGamut($bq); # recurse
  1120. $bq = preg_replace('/^/m', " ", $bq);
  1121. # These leading spaces cause problem with <pre> content,
  1122. # so we need to fix that:
  1123. $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx',
  1124. [&$this, '_DoBlockQuotes_callback2'], $bq);
  1125. return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n";
  1126. }
  1127. function _doBlockQuotes_callback2($matches) {
  1128. $pre = $matches[1];
  1129. $pre = preg_replace('/^ /m', '', $pre);
  1130. return $pre;
  1131. }
  1132. function formParagraphs($text) {
  1133. #
  1134. # Params:
  1135. # $text - string to process with html <p> tags
  1136. #
  1137. # Strip leading and trailing lines:
  1138. $text = preg_replace('/\A\n+|\n+\z/', '', $text);
  1139. $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
  1140. #
  1141. # Wrap <p> tags and unhashify HTML blocks
  1142. #
  1143. foreach ($grafs as $key => $value) {
  1144. if (!preg_match('/^B\x1A[0-9]+B$/', $value)) {
  1145. # Is a paragraph.
  1146. $value = $this->runSpanGamut($value);
  1147. $value = preg_replace('/^([ ]*)/', "<p>", $value);
  1148. $value .= "</p>";
  1149. $grafs[$key] = $this->unhash($value);
  1150. }
  1151. else {
  1152. # Is a block.
  1153. # Modify elements of @grafs in-place...
  1154. $graf = $value;
  1155. $block = $this->html_hashes[$graf];
  1156. $graf = $block;
  1157. // if (preg_match('{
  1158. // \A
  1159. // ( # $1 = <div> tag
  1160. // <div \s+
  1161. // [^>]*
  1162. // \b
  1163. // markdown\s*=\s* ([\'"]) # $2 = attr quote char
  1164. // 1
  1165. // \2
  1166. // [^>]*
  1167. // >
  1168. // )
  1169. // ( # $3 = contents
  1170. // .*
  1171. // )
  1172. // (</div>) # $4 = closing tag
  1173. // \z
  1174. // }xs', $block, $matches))
  1175. // {
  1176. // list(, $div_open, , $div_content, $div_close) = $matches;
  1177. //
  1178. // # We can't call Markdown(), because that resets the hash;
  1179. // # that initialization code should be pulled into its own sub, though.
  1180. // $div_content = $this->hashHTMLBlocks($div_content);
  1181. //
  1182. // # Run document gamut methods on the content.
  1183. // foreach ($this->document_gamut as $method => $priority) {
  1184. // $div_content = $this->$method($div_content);
  1185. // }
  1186. //
  1187. // $div_open = preg_replace(
  1188. // '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open);
  1189. //
  1190. // $graf = $div_open . "\n" . $div_content . "\n" . $div_close;
  1191. // }
  1192. $grafs[$key] = $graf;
  1193. }
  1194. }
  1195. return implode("\n\n", $grafs);
  1196. }
  1197. function encodeAttribute($text) {
  1198. #
  1199. # Encode text for a double-quoted HTML attribute. This function
  1200. # is *not* suitable for attributes enclosed in single quotes.
  1201. #
  1202. $text = $this->encodeAmpsAndAngles($text);
  1203. $text = str_replace('"', '&quot;', $text);
  1204. return $text;
  1205. }
  1206. function encodeAmpsAndAngles($text) {
  1207. #
  1208. # Smart processing for ampersands and angle brackets that need to
  1209. # be encoded. Valid character entities are left alone unless the
  1210. # no-entities mode is set.
  1211. #
  1212. if ($this->no_entities) {
  1213. $text = str_replace('&', '&amp;', $text);
  1214. } else {
  1215. # Ampersand-encoding based entirely on Nat Irons's Amputator
  1216. # MT plugin: <http://bumppo.net/projects/amputator/>
  1217. $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
  1218. '&amp;', $text);
  1219. }
  1220. # Encode remaining <'s
  1221. $text = str_replace('<', '&lt;', $text);
  1222. return $text;
  1223. }
  1224. function doAutoLinks($text) {
  1225. $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i',
  1226. [&$this, '_doAutoLinks_url_callback'], $text);
  1227. # Email addresses: <address@domain.foo>
  1228. $text = preg_replace_callback('{
  1229. <
  1230. (?:mailto:)?
  1231. (
  1232. [-.\w\x80-\xFF]+
  1233. \@
  1234. [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+
  1235. )
  1236. >
  1237. }xi',
  1238. [&$this, '_doAutoLinks_email_callback'], $text);
  1239. return $text;
  1240. }
  1241. function _doAutoLinks_url_callback($matches) {
  1242. $url = $this->encodeAttribute($matches[1]);
  1243. $link = "<a href=\"$url\">$url</a>";
  1244. return $this->hashPart($link);
  1245. }
  1246. function _doAutoLinks_email_callback($matches) {
  1247. $address = $matches[1];
  1248. $link = $this->encodeEmailAddress($address);
  1249. return $this->hashPart($link);
  1250. }
  1251. function encodeEmailAddress($addr) {
  1252. #
  1253. # Input: an email address, e.g. "foo@example.com"
  1254. #
  1255. # Output: the email address as a mailto link, with each character
  1256. # of the address encoded as either a decimal or hex entity, in
  1257. # the hopes of foiling most address harvesting spam bots. E.g.:
  1258. #
  1259. # <p><a href="&#109;&#x61;&#105;&#x6c;&#116;&#x6f;&#58;&#x66;o&#111;
  1260. # &#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;&#101;&#46;&#x63;&#111;
  1261. # &#x6d;">&#x66;o&#111;&#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;
  1262. # &#101;&#46;&#x63;&#111;&#x6d;</a></p>
  1263. #
  1264. # Based by a filter by Matthew Wickline, posted to BBEdit-Talk.
  1265. # With some optimizations by Milian Wolff.
  1266. #
  1267. $addr = "mailto:" . $addr;
  1268. $chars = preg_split('/(?<!^)(?!$)/', $addr);
  1269. $seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed.
  1270. foreach ($chars as $key => $char) {
  1271. $ord = ord($char);
  1272. # Ignore non-ascii chars.
  1273. if ($ord < 128) {
  1274. $r = ($seed * (1 + $key)) % 100; # Pseudo-random function.
  1275. # roughly 10% raw, 45% hex, 45% dec
  1276. # '@' *must* be encoded. I insist.
  1277. if ($r > 90 && $char != '@') /* do nothing */;
  1278. else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';';
  1279. else $chars[$key] = '&#'.$ord.';';
  1280. }
  1281. }
  1282. $addr = implode('', $chars);
  1283. $text = implode('', array_slice($chars, 7)); # text without `mailto:`
  1284. $addr = "<a href=\"$addr\">$text</a>";
  1285. return $addr;
  1286. }
  1287. function parseSpan($str) {
  1288. #
  1289. # Take the string $str and parse it into tokens, hashing embeded HTML,
  1290. # escaped characters and handling code spans.
  1291. #
  1292. $output = '';
  1293. $span_re = '{
  1294. (
  1295. \\\\'.$this->escape_chars_re.'
  1296. |
  1297. (?<![`\\\\])
  1298. `+ # code span marker
  1299. '.( $this->no_markup ? '' : '
  1300. |
  1301. <!-- .*? --> # comment
  1302. |
  1303. <\?.*?\?> | <%.*?%> # processing instruction
  1304. |
  1305. <[/!$]?[-a-zA-Z0-9:]+ # regular tags
  1306. (?>
  1307. \s
  1308. (?>[^"\'>]+|"[^"]*"|\'[^\']*\')*
  1309. )?
  1310. >
  1311. ').'
  1312. )
  1313. }xs';
  1314. while (1) {
  1315. #
  1316. # Each loop iteration seach for either the next tag, the next
  1317. # openning code span marker, or the next escaped character.
  1318. # Each token is then passed to handleSpanToken.
  1319. #
  1320. $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE);
  1321. # Create token from text preceding tag.
  1322. if ($parts[0] != "") {
  1323. $output .= $parts[0];
  1324. }
  1325. # Check if we reach the end.
  1326. if (isset($parts[1])) {
  1327. $output .= $this->handleSpanToken($parts[1], $parts[2]);
  1328. $str = $parts[2];
  1329. }
  1330. else {
  1331. break;
  1332. }
  1333. }
  1334. return $output;
  1335. }
  1336. function handleSpanToken($token, &$str) {
  1337. #
  1338. # Handle $token provided by parseSpan by determining its nature and
  1339. # returning the corresponding value that should replace it.
  1340. #
  1341. switch ($token[0]) {
  1342. case "\\":
  1343. return $this->hashPart("&#". ord($token[1]). ";");
  1344. case "`":
  1345. # Search for end marker in remaining text.
  1346. if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm',
  1347. $str, $matches))
  1348. {
  1349. $str = $matches[2];
  1350. $codespan = $this->makeCodeSpan($matches[1]);
  1351. return $this->hashPart($codespan);
  1352. }
  1353. return $token; // return as text since no ending marker found.
  1354. default:
  1355. return $this->hashPart($token);
  1356. }
  1357. }
  1358. function outdent($text) {
  1359. #
  1360. # Remove one level of line-leading tabs or spaces
  1361. #
  1362. return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text);
  1363. }
  1364. # String length function for detab. `_initDetab` will create a function to
  1365. # hanlde UTF-8 if the default function does not exist.
  1366. var $utf8_strlen = 'mb_strlen';
  1367. function detab($text) {
  1368. #
  1369. # Replace tabs with the appropriate amount of space.
  1370. #
  1371. # For each line we separate the line in blocks delemited by
  1372. # tab characters. Then we reconstruct every line by adding the
  1373. # appropriate number of space between each blocks.
  1374. $text = preg_replace_callback('/^.*\t.*$/m',
  1375. [&$this, '_detab_callback'], $text);
  1376. return $text;
  1377. }
  1378. function _detab_callback($matches) {
  1379. $line = $matches[0];
  1380. $strlen = $this->utf8_strlen; # strlen function for UTF-8.
  1381. # Split in blocks.
  1382. $blocks = explode("\t", $line);
  1383. # Add each blocks to the line.
  1384. $line = $blocks[0];
  1385. unset($blocks[0]); # Do not add first block twice.
  1386. foreach ($blocks as $block) {
  1387. # Calculate amount of space, insert spaces, insert block.
  1388. $amount = $this->tab_width -
  1389. $strlen($line, 'UTF-8') % $this->tab_width;
  1390. $line .= str_repeat(" ", $amount) . $block;
  1391. }
  1392. return $line;
  1393. }
  1394. function _initDetab() {
  1395. #
  1396. # Check for the availability of the function in the `utf8_strlen` property
  1397. # (initially `mb_strlen`). If the function is not available, create a
  1398. # function that will loosely count the number of UTF-8 characters with a
  1399. # regular expression.
  1400. #
  1401. if (function_exists($this->utf8_strlen)) return;
  1402. $this->utf8_strlen = function($text) {
  1403. return preg_match_all('/[\x00-\xBF]|[\xC0-\xFF][\x80-\xBF]*/', $text, $m);
  1404. };
  1405. }
  1406. function unhash($text) {
  1407. #
  1408. # Swap back in all the tags hashed by _HashHTMLBlocks.
  1409. #
  1410. return preg_replace_callback('/(.)\x1A[0-9]+\1/',
  1411. [&$this, '_unhash_callback'], $text);
  1412. }
  1413. function _unhash_callback($matches) {
  1414. return $this->html_hashes[$matches[0]];
  1415. }
  1416. }
  1417. #
  1418. # Markdown Extra Parser Class
  1419. #
  1420. class MarkdownExtra_Parser extends Markdown_Parser {
  1421. # Prefix for footnote ids.
  1422. var $fn_id_prefix = "";
  1423. # Optional title attribute for footnote links and backlinks.
  1424. var $fn_link_title = MARKDOWN_FN_LINK_TITLE;
  1425. var $fn_backlink_title = MARKDOWN_FN_BACKLINK_TITLE;
  1426. # Optional class attribute for footnote links and backlinks.
  1427. var $fn_link_class = MARKDOWN_FN_LINK_CLASS;
  1428. var $fn_backlink_class = MARKDOWN_FN_BACKLINK_CLASS;
  1429. # Predefined abbreviations.
  1430. var $predef_abbr = [];
  1431. function __construct() {
  1432. #
  1433. # Constructor function. Initialize the parser object.
  1434. #
  1435. # Add extra escapable characters before parent constructor
  1436. # initialize the table.
  1437. $this->escape_chars .= ':|';
  1438. # Insert extra document, block, and span transformations.
  1439. # Parent constructor will do the sorting.
  1440. $this->document_gamut += [
  1441. "doFencedCodeBlocks" => 5,
  1442. "stripFootnotes" => 15,
  1443. "stripAbbreviations" => 25,
  1444. "appendFootnotes" => 50,
  1445. ];
  1446. $this->block_gamut += [
  1447. "doFencedCodeBlocks" => 5,
  1448. "doTables" => 15,
  1449. "doDefLists" => 45,
  1450. ];
  1451. $this->span_gamut += [
  1452. "doFootnotes" => 5,
  1453. "doAbbreviations" => 70,
  1454. ];
  1455. parent::__construct();
  1456. }
  1457. # Extra variables used during extra transformations.
  1458. var $footnotes = [];
  1459. var $footnotes_ordered = [];
  1460. var $abbr_desciptions = [];
  1461. var $abbr_word_re = '';
  1462. # Give the current footnote number.
  1463. var $footnote_counter = 1;
  1464. function setup() {
  1465. #
  1466. # Setting up Extra-specific variables.
  1467. #
  1468. parent::setup();
  1469. $this->footnotes = [];
  1470. $this->footnotes_ordered = [];
  1471. $this->abbr_desciptions = [];
  1472. $this->abbr_word_re = '';
  1473. $this->footnote_counter = 1;
  1474. foreach ($this->predef_abbr as $abbr_word => $abbr_desc) {
  1475. if ($this->abbr_word_re)
  1476. $this->abbr_word_re .= '|';
  1477. $this->abbr_word_re .= preg_quote($abbr_word);
  1478. $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
  1479. }
  1480. }
  1481. function teardown() {
  1482. #
  1483. # Clearing Extra-specific variables.
  1484. #
  1485. $this->footnotes = [];
  1486. $this->footnotes_ordered = [];
  1487. $this->abbr_desciptions = [];
  1488. $this->abbr_word_re = '';
  1489. parent::teardown();
  1490. }
  1491. ### HTML Block Parser ###
  1492. # Tags that are always treated as block tags:
  1493. var $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend';
  1494. # Tags treated as block tags only if the opening tag is alone on it's line:
  1495. var $context_block_tags_re = 'script|noscript|math|ins|del';
  1496. # Tags where markdown="1" default to span mode:
  1497. var $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address';
  1498. # Tags which must not have their contents modified, no matter where
  1499. # they appear:
  1500. var $clean_tags_re = 'script|math';
  1501. # Tags that do not need to be closed.
  1502. var $auto_close_tags_re = 'hr|img';
  1503. function hashHTMLBlocks($text) {
  1504. #
  1505. # Hashify HTML Blocks and "clean tags".
  1506. #
  1507. # We only want to do this for block-level HTML tags, such as headers,
  1508. # lists, and tables. That's because we still want to wrap <p>s around
  1509. # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  1510. # phrase emphasis, and spans. The list of tags we're looking for is
  1511. # hard-coded.
  1512. #
  1513. # This works by calling _HashHTMLBlocks_InMarkdown, which then calls
  1514. # _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1"
  1515. # attribute is found whitin a tag, _HashHTMLBlocks_InHTML calls back
  1516. # _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag.
  1517. # These two functions are calling each other. It's recursive!
  1518. #
  1519. #
  1520. # Call the HTML-in-Markdown hasher.
  1521. #
  1522. [$text, ] = $this->_hashHTMLBlocks_inMarkdown($text);
  1523. return $text;
  1524. }
  1525. function _hashHTMLBlocks_inMarkdown($text, $indent = 0,
  1526. $enclosing_tag_re = '', $span = false)
  1527. {
  1528. #
  1529. # Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags.
  1530. #
  1531. # * $indent is the number of space to be ignored when checking for code
  1532. # blocks. This is important because if we don't take the indent into
  1533. # account, something like this (which looks right) won't work as expected:
  1534. #
  1535. # <div>
  1536. # <div markdown="1">
  1537. # Hello World. <-- Is this a Markdown code block or text?
  1538. # </div> <-- Is this a Markdown code block or a real tag?
  1539. # <div>
  1540. #
  1541. # If you don't like this, just don't indent the tag on which
  1542. # you apply the markdown="1" attribute.
  1543. #
  1544. # * If $enclosing_tag_re is not empty, stops at the first unmatched closing
  1545. # tag with that name. Nested tags supported.
  1546. #
  1547. # * If $span is true, text inside must treated as span. So any double
  1548. # newline will be replaced by a single newline so that it does not create
  1549. # paragraphs.
  1550. #
  1551. # Returns an array of that form: ( processed text , remaining text )
  1552. #
  1553. if ($text === '') return ['', ''];
  1554. # Regex to check for the presense of newlines around a block tag.
  1555. $newline_before_re = '/(?:^\n?|\n\n)*$/';
  1556. $newline_after_re =
  1557. '{
  1558. ^ # Start of text following the tag.
  1559. (?>[ ]*<!--.*?-->)? # Optional comment.
  1560. [ ]*\n # Must be followed by newline.
  1561. }xs';
  1562. # Regex to match any tag.
  1563. $block_tag_re =
  1564. '{
  1565. ( # $2: Capture hole tag.
  1566. </? # Any opening or closing tag.
  1567. (?> # Tag name.
  1568. '.$this->block_tags_re.' |
  1569. '.$this->context_block_tags_re.' |
  1570. '.$this->clean_tags_re.' |
  1571. (?!\s)'.$enclosing_tag_re.'
  1572. )
  1573. (?:
  1574. (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
  1575. (?>
  1576. ".*?" | # Double quotes (can contain `>`)
  1577. \'.*?\' | # Single quotes (can contain `>`)
  1578. .+? # Anything but quotes and `>`.
  1579. )*?
  1580. )?
  1581. > # End of tag.
  1582. |
  1583. <!-- .*? --> # HTML Comment
  1584. |
  1585. <\?.*?\?> | <%.*?%> # Processing instruction
  1586. |
  1587. <!\[CDATA\[.*?\]\]> # CData Block
  1588. |
  1589. # Code span marker
  1590. `+
  1591. '. ( !$span ? ' # If not in span.
  1592. |
  1593. # Indented code block
  1594. (?> ^[ ]*\n? | \n[ ]*\n )
  1595. [ ]{'.($indent+4).'}[^\n]* \n
  1596. (?>
  1597. (?: [ ]{'.($indent+4).'}[^\n]* | [ ]* ) \n
  1598. )*
  1599. |
  1600. # Fenced code block marker
  1601. (?> ^ | \n )
  1602. [ ]{'.($indent).'}~~~+[ ]*\n
  1603. ' : '' ). ' # End (if not is span).
  1604. )
  1605. }xs';
  1606. $depth = 0; # Current depth inside the tag tree.
  1607. $parsed = ""; # Parsed text that will be returned.
  1608. #
  1609. # Loop through every tag until we find the closing tag of the parent
  1610. # or loop until reaching the end of text if no parent tag specified.
  1611. #
  1612. do {
  1613. #
  1614. # Split the text using the first $tag_match pattern found.
  1615. # Text before pattern will be first in the array, text after
  1616. # pattern will be at the end, and between will be any catches made
  1617. # by the pattern.
  1618. #
  1619. $parts = preg_split($block_tag_re, $text, 2,
  1620. PREG_SPLIT_DELIM_CAPTURE);
  1621. # If in Markdown span mode, add a empty-string span-level hash
  1622. # after each newline to prevent triggering any block element.
  1623. if ($span) {
  1624. $void = $this->hashPart("", ':');
  1625. $newline = "$void\n";
  1626. $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void;
  1627. }
  1628. $parsed .= $parts[0]; # Text before current tag.
  1629. # If end of $text has been reached. Stop loop.
  1630. if (count($parts) < 3) {
  1631. $text = "";
  1632. break;
  1633. }
  1634. $tag = $parts[1]; # Tag to handle.
  1635. $text = $parts[2]; # Remaining text after current tag.
  1636. $tag_re = preg_quote($tag); # For use in a regular expression.
  1637. #
  1638. # Check for: Code span marker
  1639. #
  1640. if ($tag[0] == "`") {
  1641. # Find corresponding end marker.
  1642. $tag_re = preg_quote($tag);
  1643. if (preg_match('{^(?>.+?|\n(?!\n))*?(?<!`)'.$tag_re.'(?!`)}',
  1644. $text, $matches))
  1645. {
  1646. # End marker found: pass text unchanged until marker.
  1647. $parsed .= $tag . $matches[0];
  1648. $text = substr($text, strlen($matches[0]));
  1649. }
  1650. else {
  1651. # Unmatched marker: just skip it.
  1652. $parsed .= $tag;
  1653. }
  1654. }
  1655. #
  1656. # Check for: Indented code block or fenced code block marker.
  1657. #
  1658. else if ($tag[0] == "\n" || $tag[0] == "~") {
  1659. if ($tag[1] == "\n" || $tag[1] == " ") {
  1660. # Indented code block: pass it unchanged, will be handled
  1661. # later.
  1662. $parsed .= $tag;
  1663. }
  1664. else {
  1665. # Fenced code block marker: find matching end marker.
  1666. $tag_re = preg_quote(trim($tag));
  1667. if (preg_match('{^(?>.*\n)+?'.$tag_re.' *\n}', $text,
  1668. $matches))
  1669. {
  1670. # End marker found: pass text unchanged until marker.
  1671. $parsed .= $tag . $matches[0];
  1672. $text = substr($text, strlen($matches[0]));
  1673. }
  1674. else {
  1675. # No end marker: just skip it.
  1676. $parsed .= $tag;
  1677. }
  1678. }
  1679. }
  1680. #
  1681. # Check for: Opening Block level tag or
  1682. # Opening Context Block tag (like ins and del)
  1683. # used as a block tag (tag is alone on it's line).
  1684. #
  1685. else if (preg_match('{^<(?:'.$this->block_tags_re.')\b}', $tag) ||
  1686. ( preg_match('{^<(?:'.$this->context_block_tags_re.')\b}', $tag) &&
  1687. preg_match($newline_before_re, $parsed) &&
  1688. preg_match($newline_after_re, $text) )
  1689. )
  1690. {
  1691. # Need to parse tag and following text using the HTML parser.
  1692. [$block_text, $text] =
  1693. $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true);
  1694. # Make sure it stays outside of any paragraph by adding newlines.
  1695. $parsed .= "\n\n$block_text\n\n";
  1696. }
  1697. #
  1698. # Check for: Clean tag (like script, math)
  1699. # HTML Comments, processing instructions.
  1700. #
  1701. else if (preg_match('{^<(?:'.$this->clean_tags_re.')\b}', $tag) ||
  1702. $tag[1] == '!' || $tag[1] == '?') {
  1703. # Need to parse tag and following text using the HTML parser.
  1704. # (don't check for markdown attribute)
  1705. [$block_text, $text] =
  1706. $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false);
  1707. $parsed .= $block_text;
  1708. }
  1709. #
  1710. # Check for: Tag with same name as enclosing tag.
  1711. #
  1712. else if ($enclosing_tag_re !== '' &&
  1713. # Same name as enclosing tag.
  1714. preg_match('{^</?(?:'.$enclosing_tag_re.')\b}', $tag))
  1715. {
  1716. #
  1717. # Increase/decrease nested tag count.
  1718. #
  1719. if ($tag[1] == '/') $depth--;
  1720. else if ($tag[strlen($tag) -2] != '/') $depth++;
  1721. if ($depth < 0) {
  1722. #
  1723. # Going out of parent element. Clean up and break so we
  1724. # return to the calling function.
  1725. #
  1726. $text = $tag . $text;
  1727. break;
  1728. }
  1729. $parsed .= $tag;
  1730. }
  1731. else {
  1732. $parsed .= $tag;
  1733. }
  1734. } while ($depth >= 0);
  1735. return [$parsed, $text];
  1736. }
  1737. function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) {
  1738. #
  1739. # Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags.
  1740. #
  1741. # * Calls $hash_method to convert any blocks.
  1742. # * Stops when the first opening tag closes.
  1743. # * $md_attr indicate if the use of the `markdown="1"` attribute is allowed.
  1744. # (it is not inside clean tags)
  1745. #
  1746. # Returns an array of that form: ( processed text , remaining text )
  1747. #
  1748. if ($text === '') return ['', ''];
  1749. # Regex to match `markdown` attribute inside of a tag.
  1750. $markdown_attr_re = '
  1751. {
  1752. \s* # Eat whitespace before the `markdown` attribute
  1753. markdown
  1754. \s*=\s*
  1755. (?>
  1756. (["\']) # $1: quote delimiter
  1757. (.*?) # $2: attribute value
  1758. \1 # matching delimiter
  1759. |
  1760. ([^\s>]*) # $3: unquoted attribute value
  1761. )
  1762. () # $4: make $3 always defined (avoid warnings)
  1763. }xs';
  1764. # Regex to match any tag.
  1765. $tag_re = '{
  1766. ( # $2: Capture hole tag.
  1767. </? # Any opening or closing tag.
  1768. [\w:$]+ # Tag name.
  1769. (?:
  1770. (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
  1771. (?>
  1772. ".*?" | # Double quotes (can contain `>`)
  1773. \'.*?\' | # Single quotes (can contain `>`)
  1774. .+? # Anything but quotes and `>`.
  1775. )*?
  1776. )?
  1777. > # End of tag.
  1778. |
  1779. <!-- .*? --> # HTML Comment
  1780. |
  1781. <\?.*?\?> | <%.*?%> # Processing instruction
  1782. |
  1783. <!\[CDATA\[.*?\]\]> # CData Block
  1784. )
  1785. }xs';
  1786. $original_text = $text; # Save original text in case of faliure.
  1787. $depth = 0; # Current depth inside the tag tree.
  1788. $block_text = ""; # Temporary text holder for current text.
  1789. $parsed = ""; # Parsed text that will be returned.
  1790. #
  1791. # Get the name of the starting tag.
  1792. # (This pattern makes $base_tag_name_re safe without quoting.)
  1793. #
  1794. if (preg_match('/^<([\w:$]*)\b/', $text, $matches))
  1795. $base_tag_name_re = $matches[1];
  1796. #
  1797. # Loop through every tag until we find the corresponding closing tag.
  1798. #
  1799. do {
  1800. #
  1801. # Split the text using the first $tag_match pattern found.
  1802. # Text before pattern will be first in the array, text after
  1803. # pattern will be at the end, and between will be any catches made
  1804. # by the pattern.
  1805. #
  1806. $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
  1807. if (count($parts) < 3) {
  1808. #
  1809. # End of $text reached with unbalenced tag(s).
  1810. # In that case, we return original text unchanged and pass the
  1811. # first character as filtered to prevent an infinite loop in the
  1812. # parent function.
  1813. #
  1814. return [$original_text[0], substr($original_text, 1)];
  1815. }
  1816. $block_text .= $parts[0]; # Text before current tag.
  1817. $tag = $parts[1]; # Tag to handle.
  1818. $text = $parts[2]; # Remaining text after current tag.
  1819. #
  1820. # Check for: Auto-close tag (like <hr/>)
  1821. # Comments and Processing Instructions.
  1822. #
  1823. if (preg_match('{^</?(?:'.$this->auto_close_tags_re.')\b}', $tag) ||
  1824. $tag[1] == '!' || $tag[1] == '?') {
  1825. # Just add the tag to the block as if it was text.
  1826. $block_text .= $tag;
  1827. }
  1828. else {
  1829. #
  1830. # Increase/decrease nested tag count. Only do so if
  1831. # the tag's name match base tag's.
  1832. #
  1833. if (preg_match('{^</?'.$base_tag_name_re.'\b}', $tag)) {
  1834. if ($tag[1] == '/') $depth--;
  1835. else if ($tag[strlen($tag) -2] != '/') $depth++;
  1836. }
  1837. #
  1838. # Check for `markdown="1"` attribute and handle it.
  1839. #
  1840. if ($md_attr &&
  1841. preg_match($markdown_attr_re, $tag, $attr_m) &&
  1842. preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3]))
  1843. {
  1844. # Remove `markdown` attribute from opening tag.
  1845. $tag = preg_replace($markdown_attr_re, '', $tag);
  1846. # Check if text inside this tag must be parsed in span mode.
  1847. $this->mode = $attr_m[2] . $attr_m[3];
  1848. $span_mode = $this->mode == 'span' || $this->mode != 'block' &&
  1849. preg_match('{^<(?:'.$this->contain_span_tags_re.')\b}', $tag);
  1850. # Calculate indent before tag.
  1851. if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) {
  1852. $strlen = $this->utf8_strlen;
  1853. $indent = $strlen($matches[1], 'UTF-8');
  1854. } else {
  1855. $indent = 0;
  1856. }
  1857. # End preceding block with this tag.
  1858. $block_text .= $tag;
  1859. $parsed .= $this->$hash_method($block_text);
  1860. # Get enclosing tag name for the ParseMarkdown function.
  1861. # (This pattern makes $tag_name_re safe without quoting.)
  1862. preg_match('/^<([\w:$]*)\b/', $tag, $matches);
  1863. $tag_name_re = $matches[1];
  1864. # Parse the content using the HTML-in-Markdown parser.
  1865. [$block_text, $text]
  1866. = $this->_hashHTMLBlocks_inMarkdown($text, $indent,
  1867. $tag_name_re, $span_mode);
  1868. # Outdent markdown text.
  1869. if ($indent > 0) {
  1870. $block_text = preg_replace("/^[ ]{1,$indent}/m", "",
  1871. $block_text);
  1872. }
  1873. # Append tag content to parsed text.
  1874. if (!$span_mode) $parsed .= "\n\n$block_text\n\n";
  1875. else $parsed .= "$block_text";
  1876. # Start over a new block.
  1877. $block_text = "";
  1878. }
  1879. else $block_text .= $tag;
  1880. }
  1881. } while ($depth > 0);
  1882. #
  1883. # Hash last block text that wasn't processed inside the loop.
  1884. #
  1885. $parsed .= $this->$hash_method($block_text);
  1886. return [$parsed, $text];
  1887. }
  1888. function hashClean($text) {
  1889. #
  1890. # Called whenever a tag must be hashed when a function insert a "clean" tag
  1891. # in $text, it pass through this function and is automaticaly escaped,
  1892. # blocking invalid nested overlap.
  1893. #
  1894. return $this->hashPart($text, 'C');
  1895. }
  1896. function doHeaders($text) {
  1897. #
  1898. # Redefined to add id attribute support.
  1899. #
  1900. # Setext-style headers:
  1901. # Header 1 {#header1}
  1902. # ========
  1903. #
  1904. # Header 2 {#header2}
  1905. # --------
  1906. #
  1907. $text = preg_replace_callback(
  1908. '{
  1909. (^.+?) # $1: Header text
  1910. (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # $2: Id attribute
  1911. [ ]*\n(=+|-+)[ ]*\n+ # $3: Header footer
  1912. }mx',
  1913. [&$this, '_doHeaders_callback_setext'], $text);
  1914. # atx-style headers:
  1915. # # Header 1 {#header1}
  1916. # ## Header 2 {#header2}
  1917. # ## Header 2 with closing hashes ## {#header3}
  1918. # ...
  1919. # ###### Header 6 {#header2}
  1920. #
  1921. $text = preg_replace_callback('{
  1922. ^(\#{1,6}) # $1 = string of #\'s
  1923. [ ]*
  1924. (.+?) # $2 = Header text
  1925. [ ]*
  1926. \#* # optional closing #\'s (not counted)
  1927. (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # id attribute
  1928. [ ]*
  1929. \n+
  1930. }xm',
  1931. [&$this, '_doHeaders_callback_atx'], $text);
  1932. return $text;
  1933. }
  1934. function _doHeaders_attr($attr) {
  1935. if (empty($attr)) return "";
  1936. return " id=\"$attr\"";
  1937. }
  1938. function _doHeaders_callback_setext($matches) {
  1939. if ($matches[3] == '-' && preg_match('{^- }', $matches[1]))
  1940. return $matches[0];
  1941. $level = $matches[3][0] == '=' ? 1 : 2;
  1942. $attr = $this->_doHeaders_attr($id =& $matches[2]);
  1943. $block = "<h$level$attr>".$this->runSpanGamut($matches[1])."</h$level>";
  1944. return "\n" . $this->hashBlock($block) . "\n\n";
  1945. }
  1946. function _doHeaders_callback_atx($matches) {
  1947. $level = strlen($matches[1]);
  1948. $attr = $this->_doHeaders_attr($id =& $matches[3]);
  1949. $block = "<h$level$attr>".$this->runSpanGamut($matches[2])."</h$level>";
  1950. return "\n" . $this->hashBlock($block) . "\n\n";
  1951. }
  1952. function doTables($text) {
  1953. #
  1954. # Form HTML tables.
  1955. #
  1956. $less_than_tab = $this->tab_width - 1;
  1957. #
  1958. # Find tables with leading pipe.
  1959. #
  1960. # | Header 1 | Header 2
  1961. # | -------- | --------
  1962. # | Cell 1 | Cell 2
  1963. # | Cell 3 | Cell 4
  1964. #
  1965. $text = preg_replace_callback('
  1966. {
  1967. ^ # Start of a line
  1968. [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
  1969. [|] # Optional leading pipe (present)
  1970. (.+) \n # $1: Header row (at least one pipe)
  1971. [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
  1972. [|] ([ ]*[-:]+[-| :]*) \n # $2: Header underline
  1973. ( # $3: Cells
  1974. (?>
  1975. [ ]* # Allowed whitespace.
  1976. [|] .* \n # Row content.
  1977. )*
  1978. )
  1979. (?=\n|\Z) # Stop at final double newline.
  1980. }xm',
  1981. [&$this, '_doTable_leadingPipe_callback'], $text);
  1982. #
  1983. # Find tables without leading pipe.
  1984. #
  1985. # Header 1 | Header 2
  1986. # -------- | --------
  1987. # Cell 1 | Cell 2
  1988. # Cell 3 | Cell 4
  1989. #
  1990. $text = preg_replace_callback('
  1991. {
  1992. ^ # Start of a line
  1993. [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
  1994. (\S.*[|].*) \n # $1: Header row (at least one pipe)
  1995. [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
  1996. ([-:]+[ ]*[|][-| :]*) \n # $2: Header underline
  1997. ( # $3: Cells
  1998. (?>
  1999. .* [|] .* \n # Row content
  2000. )*
  2001. )
  2002. (?=\n|\Z) # Stop at final double newline.
  2003. }xm',
  2004. [&$this, '_DoTable_callback'], $text);
  2005. return $text;
  2006. }
  2007. function _doTable_leadingPipe_callback($matches) {
  2008. $head = $matches[1];
  2009. $underline = $matches[2];
  2010. $content = $matches[3];
  2011. # Remove leading pipe for each row.
  2012. $content = preg_replace('/^ *[|]/m', '', $content);
  2013. return $this->_doTable_callback([$matches[0], $head, $underline, $content]);
  2014. }
  2015. function _doTable_callback($matches) {
  2016. $head = $matches[1];
  2017. $underline = $matches[2];
  2018. $content = $matches[3];
  2019. # Remove any tailing pipes for each line.
  2020. $head = preg_replace('/[|] *$/m', '', $head);
  2021. $underline = preg_replace('/[|] *$/m', '', $underline);
  2022. $content = preg_replace('/[|] *$/m', '', $content);
  2023. # Reading alignement from header underline.
  2024. $separators = preg_split('/ *[|] */', $underline);
  2025. foreach ($separators as $n => $s) {
  2026. if (preg_match('/^ *-+: *$/', $s)) $attr[$n] = ' align="right"';
  2027. else if (preg_match('/^ *:-+: *$/', $s))$attr[$n] = ' align="center"';
  2028. else if (preg_match('/^ *:-+ *$/', $s)) $attr[$n] = ' align="left"';
  2029. else $attr[$n] = '';
  2030. }
  2031. # Parsing span elements, including code spans, character escapes,
  2032. # and inline HTML tags, so that pipes inside those gets ignored.
  2033. $head = $this->parseSpan($head);
  2034. $headers = preg_split('/ *[|] */', $head);
  2035. $col_count = count($headers);
  2036. # Write column headers.
  2037. $text = "<table>\n";
  2038. $text .= "<thead>\n";
  2039. $text .= "<tr>\n";
  2040. foreach ($headers as $n => $header)
  2041. $text .= " <th$attr[$n]>".$this->runSpanGamut(trim($header))."</th>\n";
  2042. $text .= "</tr>\n";
  2043. $text .= "</thead>\n";
  2044. # Split content by row.
  2045. $rows = explode("\n", trim($content, "\n"));
  2046. $text .= "<tbody>\n";
  2047. foreach ($rows as $row) {
  2048. # Parsing span elements, including code spans, character escapes,
  2049. # and inline HTML tags, so that pipes inside those gets ignored.
  2050. $row = $this->parseSpan($row);
  2051. # Split row by cell.
  2052. $row_cells = preg_split('/ *[|] */', $row, $col_count);
  2053. $row_cells = array_pad($row_cells, $col_count, '');
  2054. $text .= "<tr>\n";
  2055. foreach ($row_cells as $n => $cell)
  2056. $text .= " <td$attr[$n]>".$this->runSpanGamut(trim($cell))."</td>\n";
  2057. $text .= "</tr>\n";
  2058. }
  2059. $text .= "</tbody>\n";
  2060. $text .= "</table>";
  2061. return $this->hashBlock($text) . "\n";
  2062. }
  2063. function doDefLists($text) {
  2064. #
  2065. # Form HTML definition lists.
  2066. #
  2067. $less_than_tab = $this->tab_width - 1;
  2068. # Re-usable pattern to match any entire dl list:
  2069. $whole_list_re = '(?>
  2070. ( # $1 = whole list
  2071. ( # $2
  2072. [ ]{0,'.$less_than_tab.'}
  2073. ((?>.*\S.*\n)+) # $3 = defined term
  2074. \n?
  2075. [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
  2076. )
  2077. (?s:.+?)
  2078. ( # $4
  2079. \z
  2080. |
  2081. \n{2,}
  2082. (?=\S)
  2083. (?! # Negative lookahead for another term
  2084. [ ]{0,'.$less_than_tab.'}
  2085. (?: \S.*\n )+? # defined term
  2086. \n?
  2087. [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
  2088. )
  2089. (?! # Negative lookahead for another definition
  2090. [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
  2091. )
  2092. )
  2093. )
  2094. )'; // mx
  2095. $text = preg_replace_callback('{
  2096. (?>\A\n?|(?<=\n\n))
  2097. '.$whole_list_re.'
  2098. }mx',
  2099. [&$this, '_doDefLists_callback'], $text);
  2100. return $text;
  2101. }
  2102. function _doDefLists_callback($matches) {
  2103. # Re-usable patterns to match list item bullets and number markers:
  2104. $list = $matches[1];
  2105. # Turn double returns into triple returns, so that we can make a
  2106. # paragraph for the last item in a list, if necessary:
  2107. $result = trim($this->processDefListItems($list));
  2108. $result = "<dl>\n" . $result . "\n</dl>";
  2109. return $this->hashBlock($result) . "\n\n";
  2110. }
  2111. function processDefListItems($list_str) {
  2112. #
  2113. # Process the contents of a single definition list, splitting it
  2114. # into individual term and definition list items.
  2115. #
  2116. $less_than_tab = $this->tab_width - 1;
  2117. # trim trailing blank lines:
  2118. $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  2119. # Process definition terms.
  2120. $list_str = preg_replace_callback('{
  2121. (?>\A\n?|\n\n+) # leading line
  2122. ( # definition terms = $1
  2123. [ ]{0,'.$less_than_tab.'} # leading whitespace
  2124. (?![:][ ]|[ ]) # negative lookahead for a definition
  2125. # mark (colon) or more whitespace.
  2126. (?> \S.* \n)+? # actual term (not whitespace).
  2127. )
  2128. (?=\n?[ ]{0,3}:[ ]) # lookahead for following line feed
  2129. # with a definition mark.
  2130. }xm',
  2131. [&$this, '_processDefListItems_callback_dt'], $list_str);
  2132. # Process actual definitions.
  2133. $list_str = preg_replace_callback('{
  2134. \n(\n+)? # leading line = $1
  2135. ( # marker space = $2
  2136. [ ]{0,'.$less_than_tab.'} # whitespace before colon
  2137. [:][ ]+ # definition mark (colon)
  2138. )
  2139. ((?s:.+?)) # definition text = $3
  2140. (?= \n+ # stop at next definition mark,
  2141. (?: # next term or end of text
  2142. [ ]{0,'.$less_than_tab.'} [:][ ] |
  2143. <dt> | \z
  2144. )
  2145. )
  2146. }xm',
  2147. [&$this, '_processDefListItems_callback_dd'], $list_str);
  2148. return $list_str;
  2149. }
  2150. function _processDefListItems_callback_dt($matches) {
  2151. $terms = explode("\n", trim($matches[1]));
  2152. $text = '';
  2153. foreach ($terms as $term) {
  2154. $term = $this->runSpanGamut(trim($term));
  2155. $text .= "\n<dt>" . $term . "</dt>";
  2156. }
  2157. return $text . "\n";
  2158. }
  2159. function _processDefListItems_callback_dd($matches) {
  2160. $leading_line = $matches[1];
  2161. $marker_space = $matches[2];
  2162. $def = $matches[3];
  2163. if ($leading_line || preg_match('/\n{2,}/', $def)) {
  2164. # Replace marker with the appropriate whitespace indentation
  2165. $def = str_repeat(' ', strlen($marker_space)) . $def;
  2166. $def = $this->runBlockGamut($this->outdent($def . "\n\n"));
  2167. $def = "\n". $def ."\n";
  2168. }
  2169. else {
  2170. $def = rtrim($def);
  2171. $def = $this->runSpanGamut($this->outdent($def));
  2172. }
  2173. return "\n<dd>" . $def . "</dd>\n";
  2174. }
  2175. function doFencedCodeBlocks($text) {
  2176. #
  2177. # Adding the fenced code block syntax to regular Markdown:
  2178. #
  2179. # ~~~
  2180. # Code block
  2181. # ~~~
  2182. #
  2183. $less_than_tab = $this->tab_width;
  2184. $text = preg_replace_callback('{
  2185. (?:\n|\A)
  2186. # 1: Opening marker
  2187. (
  2188. ~{3,} # Marker: three tilde or more.
  2189. )
  2190. [ ]* \n # Whitespace and newline following marker.
  2191. # 2: Content
  2192. (
  2193. (?>
  2194. (?!\1 [ ]* \n) # Not a closing marker.
  2195. .*\n+
  2196. )+
  2197. )
  2198. # Closing marker.
  2199. \1 [ ]* \n
  2200. }xm',
  2201. [&$this, '_doFencedCodeBlocks_callback'], $text);
  2202. return $text;
  2203. }
  2204. function _doFencedCodeBlocks_callback($matches) {
  2205. $codeblock = $matches[2];
  2206. $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
  2207. $codeblock = preg_replace_callback('/^\n+/',
  2208. [&$this, '_doFencedCodeBlocks_newlines'], $codeblock);
  2209. $codeblock = "<pre><code>$codeblock</code></pre>";
  2210. return "\n\n".$this->hashBlock($codeblock)."\n\n";
  2211. }
  2212. function _doFencedCodeBlocks_newlines($matches) {
  2213. return str_repeat("<br$this->empty_element_suffix",
  2214. strlen($matches[0]));
  2215. }
  2216. #
  2217. # Redefining emphasis markers so that emphasis by underscore does not
  2218. # work in the middle of a word.
  2219. #
  2220. var $em_relist = [
  2221. '' => '(?:(?<!\*)\*(?!\*)|(?<![a-zA-Z0-9_])_(?!_))(?=\S)(?![.,:;]\s)',
  2222. '*' => '(?<=\S)(?<!\*)\*(?!\*)',
  2223. '_' => '(?<=\S)(?<!_)_(?![a-zA-Z0-9_])',
  2224. ];
  2225. var $strong_relist = [
  2226. '' => '(?:(?<!\*)\*\*(?!\*)|(?<![a-zA-Z0-9_])__(?!_))(?=\S)(?![.,:;]\s)',
  2227. '**' => '(?<=\S)(?<!\*)\*\*(?!\*)',
  2228. '__' => '(?<=\S)(?<!_)__(?![a-zA-Z0-9_])',
  2229. ];
  2230. var $em_strong_relist = [
  2231. '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<![a-zA-Z0-9_])___(?!_))(?=\S)(?![.,:;]\s)',
  2232. '***' => '(?<=\S)(?<!\*)\*\*\*(?!\*)',
  2233. '___' => '(?<=\S)(?<!_)___(?![a-zA-Z0-9_])',
  2234. ];
  2235. function formParagraphs($text) {
  2236. #
  2237. # Params:
  2238. # $text - string to process with html <p> tags
  2239. #
  2240. # Strip leading and trailing lines:
  2241. $text = preg_replace('/\A\n+|\n+\z/', '', $text);
  2242. $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
  2243. #
  2244. # Wrap <p> tags and unhashify HTML blocks
  2245. #
  2246. foreach ($grafs as $key => $value) {
  2247. $value = trim($this->runSpanGamut($value));
  2248. # Check if this should be enclosed in a paragraph.
  2249. # Clean tag hashes & block tag hashes are left alone.
  2250. $is_p = !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value);
  2251. if ($is_p) {
  2252. $value = "<p>$value</p>";
  2253. }
  2254. $grafs[$key] = $value;
  2255. }
  2256. # Join grafs in one text, then unhash HTML tags.
  2257. $text = implode("\n\n", $grafs);
  2258. # Finish by removing any tag hashes still present in $text.
  2259. $text = $this->unhash($text);
  2260. return $text;
  2261. }
  2262. ### Footnotes
  2263. function stripFootnotes($text) {
  2264. #
  2265. # Strips link definitions from text, stores the URLs and titles in
  2266. # hash references.
  2267. #
  2268. $less_than_tab = $this->tab_width - 1;
  2269. # Link defs are in the form: [^id]: url "optional title"
  2270. $text = preg_replace_callback('{
  2271. ^[ ]{0,'.$less_than_tab.'}\[\^(.+?)\][ ]?: # note_id = $1
  2272. [ ]*
  2273. \n? # maybe *one* newline
  2274. ( # text = $2 (no blank lines allowed)
  2275. (?:
  2276. .+ # actual text
  2277. |
  2278. \n # newlines but
  2279. (?!\[\^.+?\]:\s)# negative lookahead for footnote marker.
  2280. (?!\n+[ ]{0,3}\S)# ensure line is not blank and followed
  2281. # by non-indented content
  2282. )*
  2283. )
  2284. }xm',
  2285. [&$this, '_stripFootnotes_callback'],
  2286. $text);
  2287. return $text;
  2288. }
  2289. function _stripFootnotes_callback($matches) {
  2290. $note_id = $this->fn_id_prefix . $matches[1];
  2291. $this->footnotes[$note_id] = $this->outdent($matches[2]);
  2292. return ''; # String that will replace the block
  2293. }
  2294. function doFootnotes($text) {
  2295. #
  2296. # Replace footnote references in $text [^id] with a special text-token
  2297. # which will be replaced by the actual footnote marker in appendFootnotes.
  2298. #
  2299. if (!$this->in_anchor) {
  2300. $text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text);
  2301. }
  2302. return $text;
  2303. }
  2304. function appendFootnotes($text) {
  2305. #
  2306. # Append footnote list to text.
  2307. #
  2308. $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
  2309. [&$this, '_appendFootnotes_callback'], $text);
  2310. if (!empty($this->footnotes_ordered)) {
  2311. $text .= "\n\n";
  2312. $text .= "<div class=\"footnotes\">\n";
  2313. $text .= "<hr". MARKDOWN_EMPTY_ELEMENT_SUFFIX ."\n";
  2314. $text .= "<ol>\n\n";
  2315. $attr = " rev=\"footnote\"";
  2316. if ($this->fn_backlink_class != "") {
  2317. $class = $this->fn_backlink_class;
  2318. $class = $this->encodeAttribute($class);
  2319. $attr .= " class=\"$class\"";
  2320. }
  2321. if ($this->fn_backlink_title != "") {
  2322. $title = $this->fn_backlink_title;
  2323. $title = $this->encodeAttribute($title);
  2324. $attr .= " title=\"$title\"";
  2325. }
  2326. $num = 0;
  2327. while (!empty($this->footnotes_ordered)) {
  2328. $footnote = reset($this->footnotes_ordered);
  2329. $note_id = key($this->footnotes_ordered);
  2330. unset($this->footnotes_ordered[$note_id]);
  2331. $footnote .= "\n"; # Need to append newline before parsing.
  2332. $footnote = $this->runBlockGamut("$footnote\n");
  2333. $footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
  2334. [&$this, '_appendFootnotes_callback'], $footnote);
  2335. $attr = str_replace("%%", ++$num, $attr);
  2336. $note_id = $this->encodeAttribute($note_id);
  2337. # Add backlink to last paragraph; create new paragraph if needed.
  2338. $backlink = "<a href=\"#fnref:$note_id\"$attr>&#8617;</a>";
  2339. if (preg_match('{</p>$}', $footnote)) {
  2340. $footnote = substr($footnote, 0, -4) . "&#160;$backlink</p>";
  2341. } else {
  2342. $footnote .= "\n\n<p>$backlink</p>";
  2343. }
  2344. $text .= "<li id=\"fn:$note_id\">\n";
  2345. $text .= $footnote . "\n";
  2346. $text .= "</li>\n\n";
  2347. }
  2348. $text .= "</ol>\n";
  2349. $text .= "</div>";
  2350. }
  2351. return $text;
  2352. }
  2353. function _appendFootnotes_callback($matches) {
  2354. $node_id = $this->fn_id_prefix . $matches[1];
  2355. # Create footnote marker only if it has a corresponding footnote *and*
  2356. # the footnote hasn't been used by another marker.
  2357. if (isset($this->footnotes[$node_id])) {
  2358. # Transfert footnote content to the ordered list.
  2359. $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id];
  2360. unset($this->footnotes[$node_id]);
  2361. $num = $this->footnote_counter++;
  2362. $attr = " rel=\"footnote\"";
  2363. if ($this->fn_link_class != "") {
  2364. $class = $this->fn_link_class;
  2365. $class = $this->encodeAttribute($class);
  2366. $attr .= " class=\"$class\"";
  2367. }
  2368. if ($this->fn_link_title != "") {
  2369. $title = $this->fn_link_title;
  2370. $title = $this->encodeAttribute($title);
  2371. $attr .= " title=\"$title\"";
  2372. }
  2373. $attr = str_replace("%%", $num, $attr);
  2374. $node_id = $this->encodeAttribute($node_id);
  2375. return
  2376. "<sup id=\"fnref:$node_id\">".
  2377. "<a href=\"#fn:$node_id\"$attr>$num</a>".
  2378. "</sup>";
  2379. }
  2380. return "[^".$matches[1]."]";
  2381. }
  2382. ### Abbreviations ###
  2383. function stripAbbreviations($text) {
  2384. #
  2385. # Strips abbreviations from text, stores titles in hash references.
  2386. #
  2387. $less_than_tab = $this->tab_width - 1;
  2388. # Link defs are in the form: [id]*: url "optional title"
  2389. $text = preg_replace_callback('{
  2390. ^[ ]{0,'.$less_than_tab.'}\*\[(.+?)\][ ]?: # abbr_id = $1
  2391. (.*) # text = $2 (no blank lines allowed)
  2392. }xm',
  2393. [&$this, '_stripAbbreviations_callback'],
  2394. $text);
  2395. return $text;
  2396. }
  2397. function _stripAbbreviations_callback($matches) {
  2398. $abbr_word = $matches[1];
  2399. $abbr_desc = $matches[2];
  2400. if ($this->abbr_word_re)
  2401. $this->abbr_word_re .= '|';
  2402. $this->abbr_word_re .= preg_quote($abbr_word);
  2403. $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
  2404. return ''; # String that will replace the block
  2405. }
  2406. function doAbbreviations($text) {
  2407. #
  2408. # Find defined abbreviations in text and wrap them in <abbr> elements.
  2409. #
  2410. if ($this->abbr_word_re) {
  2411. // cannot use the /x modifier because abbr_word_re may
  2412. // contain significant spaces:
  2413. $text = preg_replace_callback('{'.
  2414. '(?<![\w\x1A])'.
  2415. '(?:'.$this->abbr_word_re.')'.
  2416. '(?![\w\x1A])'.
  2417. '}',
  2418. [&$this, '_doAbbreviations_callback'], $text);
  2419. }
  2420. return $text;
  2421. }
  2422. function _doAbbreviations_callback($matches) {
  2423. $abbr = $matches[0];
  2424. if (isset($this->abbr_desciptions[$abbr])) {
  2425. $desc = $this->abbr_desciptions[$abbr];
  2426. if (empty($desc)) {
  2427. return $this->hashPart("<abbr>$abbr</abbr>");
  2428. } else {
  2429. $desc = $this->encodeAttribute($desc);
  2430. return $this->hashPart("<abbr title=\"$desc\">$abbr</abbr>");
  2431. }
  2432. } else {
  2433. return $matches[0];
  2434. }
  2435. }
  2436. }
  2437. /*
  2438. PHP Markdown Extra
  2439. ==================
  2440. Description
  2441. -----------
  2442. This is a PHP port of the original Markdown formatter written in Perl
  2443. by John Gruber. This special "Extra" version of PHP Markdown features
  2444. further enhancements to the syntax for making additional constructs
  2445. such as tables and definition list.
  2446. Markdown is a text-to-HTML filter; it translates an easy-to-read /
  2447. easy-to-write structured text format into HTML. Markdown's text format
  2448. is most similar to that of plain text email, and supports features such
  2449. as headers, *emphasis*, code blocks, blockquotes, and links.
  2450. Markdown's syntax is designed not as a generic markup language, but
  2451. specifically to serve as a front-end to (X)HTML. You can use span-level
  2452. HTML tags anywhere in a Markdown document, and you can use block level
  2453. HTML tags (like <div> and <table> as well).
  2454. For more information about Markdown's syntax, see:
  2455. <http://daringfireball.net/projects/markdown/>
  2456. Bugs
  2457. ----
  2458. To file bug reports please send email to:
  2459. <michel.fortin@michelf.com>
  2460. Please include with your report: (1) the example input; (2) the output you
  2461. expected; (3) the output Markdown actually produced.
  2462. Version History
  2463. ---------------
  2464. See the readme file for detailed release notes for this version.
  2465. Copyright and License
  2466. ---------------------
  2467. PHP Markdown & Extra
  2468. Copyright (c) 2004-2017 Michel Fortin
  2469. <http://www.michelf.com/>
  2470. All rights reserved.
  2471. Based on Markdown
  2472. Copyright (c) 2003-2017 John Gruber
  2473. <http://daringfireball.net/>
  2474. All rights reserved.
  2475. Redistribution and use in source and binary forms, with or without
  2476. modification, are permitted provided that the following conditions are
  2477. met:
  2478. * Redistributions of source code must retain the above copyright notice,
  2479. this list of conditions and the following disclaimer.
  2480. * Redistributions in binary form must reproduce the above copyright
  2481. notice, this list of conditions and the following disclaimer in the
  2482. documentation and/or other materials provided with the distribution.
  2483. * Neither the name "Markdown" nor the names of its contributors may
  2484. be used to endorse or promote products derived from this software
  2485. without specific prior written permission.
  2486. This software is provided by the copyright holders and contributors "as
  2487. is" and any express or implied warranties, including, but not limited
  2488. to, the implied warranties of merchantability and fitness for a
  2489. particular purpose are disclaimed. In no event shall the copyright owner
  2490. or contributors be liable for any direct, indirect, incidental, special,
  2491. exemplary, or consequential damages (including, but not limited to,
  2492. procurement of substitute goods or services; loss of use, data, or
  2493. profits; or business interruption) however caused and on any theory of
  2494. liability, whether in contract, strict liability, or tort (including
  2495. negligence or otherwise) arising in any way out of the use of this
  2496. software, even if advised of the possibility of such damage.
  2497. */
  2498. ?>