markdown.php 93 KB

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