PageRenderTime 50ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/jetpack/_inc/lib/markdown/gfm.php

https://gitlab.com/juanito.abelo/nlmobile
PHP | 372 lines | 167 code | 46 blank | 159 comment | 10 complexity | 3874c7107983403578420b41324c956d MD5 | raw file
  1. <?php
  2. /**
  3. * GitHub-Flavoured Markdown. Inspired by Evan's plugin, but modified.
  4. *
  5. * @author Evan Solomon
  6. * @author Matt Wiebe <wiebe@automattic.com>
  7. * @link https://github.com/evansolomon/wp-github-flavored-markdown-comments
  8. *
  9. * Add a few extras from GitHub's Markdown implementation. Must be used in a WordPress environment.
  10. */
  11. class WPCom_GHF_Markdown_Parser extends MarkdownExtra_Parser {
  12. /**
  13. * Hooray somewhat arbitrary numbers that are fearful of 1.0.x.
  14. */
  15. const WPCOM_GHF_MARDOWN_VERSION = '0.9.0';
  16. /**
  17. * Use a [code] shortcode when encountering a fenced code block
  18. * @var boolean
  19. */
  20. public $use_code_shortcode = true;
  21. /**
  22. * Preserve shortcodes, untouched by Markdown.
  23. * This requires use within a WordPress installation.
  24. * @var boolean
  25. */
  26. public $preserve_shortcodes = true;
  27. /**
  28. * Preserve the legacy $latex your-latex-code-here$ style
  29. * LaTeX markup
  30. */
  31. public $preserve_latex = true;
  32. /**
  33. * Preserve single-line <code> blocks.
  34. * @var boolean
  35. */
  36. public $preserve_inline_code_blocks = true;
  37. /**
  38. * Strip paragraphs from the output. This is the right default for WordPress,
  39. * which generally wants to create its own paragraphs with `wpautop`
  40. * @var boolean
  41. */
  42. public $strip_paras = true;
  43. // Will run through sprintf - you can supply your own syntax if you want
  44. public $shortcode_start = '[code lang=%s]';
  45. public $shortcode_end = '[/code]';
  46. // Stores shortcodes we remove and then replace
  47. protected $preserve_text_hash = array();
  48. /**
  49. * Set environment defaults based on presence of key functions/classes.
  50. */
  51. public function __construct() {
  52. $this->use_code_shortcode = class_exists( 'SyntaxHighlighter' );
  53. $this->preserve_shortcodes = function_exists( 'get_shortcode_regex' );
  54. $this->preserve_latex = function_exists( 'latex_markup' );
  55. $this->strip_paras = function_exists( 'wpautop' );
  56. parent::MarkdownExtra_Parser();
  57. }
  58. /**
  59. * Overload to specify heading styles only if the hash has space(s) after it. This is actually in keeping with
  60. * the documentation and eases the semantic overload of the hash character.
  61. * #Will Not Produce a Heading 1
  62. * # This Will Produce a Heading 1
  63. *
  64. * @param string $text Markdown text
  65. * @return string HTML-transformed text
  66. */
  67. public function transform( $text ) {
  68. // Preserve anything inside a single-line <code> element
  69. if ( $this->preserve_inline_code_blocks ) {
  70. $text = $this->single_line_code_preserve( $text );
  71. }
  72. // Remove all shortcodes so their interiors are left intact
  73. if ( $this->preserve_shortcodes ) {
  74. $text = $this->shortcode_preserve( $text );
  75. }
  76. // Remove legacy LaTeX so it's left intact
  77. if ( $this->preserve_latex ) {
  78. $text = $this->latex_preserve( $text );
  79. }
  80. // escape line-beginning # chars that do not have a space after them.
  81. $text = preg_replace_callback( '|^#{1,6}( )?|um', array( $this, '_doEscapeForHashWithoutSpacing' ), $text );
  82. // run through core Markdown
  83. $text = parent::transform( $text );
  84. // Occasionally Markdown Extra chokes on a para structure, producing odd paragraphs.
  85. $text = str_replace( "<p>&lt;</p>\n\n<p>p>", '<p>', $text );
  86. // put start-of-line # chars back in place
  87. $text = $this->restore_leading_hash( $text );
  88. // Strip paras if set
  89. if ( $this->strip_paras ) {
  90. $text = $this->unp( $text );
  91. }
  92. // Restore preserved things like shortcodes/LaTeX
  93. $text = $this->do_restore( $text );
  94. return $text;
  95. }
  96. /**
  97. * Prevents blocks like <code>__this__</code> from turning into <code><strong>this</strong></code>
  98. * @param string $text Text that may need preserving
  99. * @return string Text that was preserved if needed
  100. */
  101. public function single_line_code_preserve( $text ) {
  102. return preg_replace_callback( '|<code\b[^>]*>(.*?)</code>|', array( $this, 'do_single_line_code_preserve' ), $text );
  103. }
  104. /**
  105. * Regex callback for inline code presevation
  106. * @param array $matches Regex matches
  107. * @return string Hashed content for later restoration
  108. */
  109. public function do_single_line_code_preserve( $matches ) {
  110. return '<code>' . $this->hash_block( $matches[1] ) . '</code>';
  111. }
  112. /**
  113. * Preserve code block contents by HTML encoding them. Useful before getting to KSES stripping.
  114. * @param string $text Markdown/HTML content
  115. * @return string Markdown/HTML content with escaped code blocks
  116. */
  117. public function codeblock_preserve( $text ) {
  118. return preg_replace_callback( "/^([`~]{3})([^`\n]+)?\n([^`~]+)(\\1)/m", array( $this, 'do_codeblock_preserve' ), $text );
  119. }
  120. /**
  121. * Regex callback for code block preservation.
  122. * @param array $matches Regex matches
  123. * @return string Codeblock with escaped interior
  124. */
  125. public function do_codeblock_preserve( $matches ) {
  126. $block = stripslashes( $matches[3] );
  127. $block = esc_html( $block );
  128. $open = $matches[1] . $matches[2] . "\n";
  129. return $open . $block . $matches[4];
  130. }
  131. /**
  132. * Restore previously preserved (i.e. escaped) code block contents.
  133. * @param string $text Markdown/HTML content with escaped code blocks
  134. * @return string Markdown/HTML content
  135. */
  136. public function codeblock_restore( $text ) {
  137. return preg_replace_callback( "/^([`~]{3})([^`\n]+)?\n([^`~]+)(\\1)/m", array( $this, 'do_codeblock_restore' ), $text );
  138. }
  139. /**
  140. * Regex callback for code block restoration (unescaping).
  141. * @param array $matches Regex matches
  142. * @return string Codeblock with unescaped interior
  143. */
  144. public function do_codeblock_restore( $matches ) {
  145. $block = html_entity_decode( $matches[3], ENT_QUOTES );
  146. $open = $matches[1] . $matches[2] . "\n";
  147. return $open . $block . $matches[4];
  148. }
  149. /**
  150. * Called to preserve legacy LaTeX like $latex some-latex-text $
  151. * @param string $text Text in which to preserve LaTeX
  152. * @return string Text with LaTeX replaced by a hash that will be restored later
  153. */
  154. protected function latex_preserve( $text ) {
  155. // regex from latex_remove()
  156. $regex = '%
  157. \$latex(?:=\s*|\s+)
  158. ((?:
  159. [^$]+ # Not a dollar
  160. |
  161. (?<=(?<!\\\\)\\\\)\$ # Dollar preceded by exactly one slash
  162. )+)
  163. (?<!\\\\)\$ # Dollar preceded by zero slashes
  164. %ix';
  165. $text = preg_replace_callback( $regex, array( $this, '_doRemoveText'), $text );
  166. return $text;
  167. }
  168. /**
  169. * Called to preserve WP shortcodes from being formatted by Markdown in any way.
  170. * @param string $text Text in which to preserve shortcodes
  171. * @return string Text with shortcodes replaced by a hash that will be restored later
  172. */
  173. protected function shortcode_preserve( $text ) {
  174. $text = preg_replace_callback( $this->get_shortcode_regex(), array( $this, '_doRemoveText' ), $text );
  175. return $text;
  176. }
  177. /**
  178. * Restores any text preserved by $this->hash_block()
  179. * @param string $text Text that may have hashed preservation placeholders
  180. * @return string Text with hashed preseravtion placeholders replaced by original text
  181. */
  182. protected function do_restore( $text ) {
  183. foreach( $this->preserve_text_hash as $hash => $value ) {
  184. $placeholder = $this->hash_maker( $hash );
  185. $text = str_replace( $placeholder, $value, $text );
  186. }
  187. // reset the hash
  188. $this->preserve_text_hash = array();
  189. return $text;
  190. }
  191. /**
  192. * Regex callback for text preservation
  193. * @param array $m Regex $matches array
  194. * @return string A placeholder that will later be replaced by the original text
  195. */
  196. protected function _doRemoveText( $m ) {
  197. return $this->hash_block( $m[0] );
  198. }
  199. /**
  200. * Call this to store a text block for later restoration.
  201. * @param string $text Text to preserve for later
  202. * @return string Placeholder that will be swapped out later for the original text
  203. */
  204. protected function hash_block( $text ) {
  205. $hash = md5( $text );
  206. $this->preserve_text_hash[ $hash ] = $text;
  207. $placeholder = $this->hash_maker( $hash );
  208. return $placeholder;
  209. }
  210. /**
  211. * Less glamorous than the Keymaker
  212. * @param string $hash An md5 hash
  213. * @return string A placeholder hash
  214. */
  215. protected function hash_maker( $hash ) {
  216. return 'MARKDOWN_HASH' . $hash . 'MARKDOWN_HASH';
  217. }
  218. /**
  219. * Remove bare <p> elements. <p>s with attributes will be preserved.
  220. * @param string $text HTML content
  221. * @return string <p>-less content
  222. */
  223. public function unp( $text ) {
  224. return preg_replace( "#<p>(.*?)</p>(\n|$)#ums", '$1$2', $text );
  225. }
  226. /**
  227. * A regex of all shortcodes currently registered by the current
  228. * WordPress installation
  229. * @uses get_shortcode_regex()
  230. * @return string A regex for grabbing shortcodes.
  231. */
  232. protected function get_shortcode_regex() {
  233. $pattern = get_shortcode_regex();
  234. // don't match markdown link anchors that could be mistaken for shortcodes.
  235. $pattern .= '(?!\()';
  236. return "/$pattern/s";
  237. }
  238. /**
  239. * Since we escape unspaced #Headings, put things back later.
  240. * @param string $text text with a leading escaped hash
  241. * @return string text with leading hashes unescaped
  242. */
  243. protected function restore_leading_hash( $text ) {
  244. return preg_replace( "/^(<p>)?(&#35;|\\\\#)/um", "$1#", $text );
  245. }
  246. /**
  247. * Overload to support ```-fenced code blocks for pre-Markdown Extra 1.2.8
  248. * https://help.github.com/articles/github-flavored-markdown#fenced-code-blocks
  249. */
  250. public function doFencedCodeBlocks( $text ) {
  251. // If we're at least at 1.2.8, native fenced code blocks are in.
  252. // Below is just copied from it in case we somehow got loaded on
  253. // top of someone else's Markdown Extra
  254. if ( version_compare( MARKDOWNEXTRA_VERSION, '1.2.8', '>=' ) )
  255. return parent::doFencedCodeBlocks( $text );
  256. #
  257. # Adding the fenced code block syntax to regular Markdown:
  258. #
  259. # ~~~
  260. # Code block
  261. # ~~~
  262. #
  263. $less_than_tab = $this->tab_width;
  264. $text = preg_replace_callback('{
  265. (?:\n|\A)
  266. # 1: Opening marker
  267. (
  268. (?:~{3,}|`{3,}) # 3 or more tildes/backticks.
  269. )
  270. [ ]*
  271. (?:
  272. \.?([-_:a-zA-Z0-9]+) # 2: standalone class name
  273. |
  274. '.$this->id_class_attr_catch_re.' # 3: Extra attributes
  275. )?
  276. [ ]* \n # Whitespace and newline following marker.
  277. # 4: Content
  278. (
  279. (?>
  280. (?!\1 [ ]* \n) # Not a closing marker.
  281. .*\n+
  282. )+
  283. )
  284. # Closing marker.
  285. \1 [ ]* (?= \n )
  286. }xm',
  287. array($this, '_doFencedCodeBlocks_callback'), $text);
  288. return $text;
  289. }
  290. /**
  291. * Callback for pre-processing start of line hashes to slyly escape headings that don't
  292. * have a leading space
  293. * @param array $m preg_match matches
  294. * @return string possibly escaped start of line hash
  295. */
  296. public function _doEscapeForHashWithoutSpacing( $m ) {
  297. if ( ! isset( $m[1] ) )
  298. $m[0] = '\\' . $m[0];
  299. return $m[0];
  300. }
  301. /**
  302. * Overload to support Viper's [code] shortcode. Because awesome.
  303. */
  304. public function _doFencedCodeBlocks_callback( $matches ) {
  305. // in case we have some escaped leading hashes right at the start of the block
  306. $matches[4] = $this->restore_leading_hash( $matches[4] );
  307. // just MarkdownExtra_Parser if we're not going ultra-deluxe
  308. if ( ! $this->use_code_shortcode ) {
  309. return parent::_doFencedCodeBlocks_callback( $matches );
  310. }
  311. // default to a "text" class if one wasn't passed. Helps with encoding issues later.
  312. if ( empty( $matches[2] ) ) {
  313. $matches[2] = 'text';
  314. }
  315. $classname =& $matches[2];
  316. $codeblock = preg_replace_callback('/^\n+/', array( $this, '_doFencedCodeBlocks_newlines' ), $matches[4] );
  317. if ( $classname{0} == '.' )
  318. $classname = substr( $classname, 1 );
  319. $codeblock = esc_html( $codeblock );
  320. $codeblock = sprintf( $this->shortcode_start, $classname ) . "\n{$codeblock}" . $this->shortcode_end;
  321. return "\n\n" . $this->hashBlock( $codeblock ). "\n\n";
  322. }
  323. }