extra.php 88 KB

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