1
0
mirror of https://github.com/processwire/processwire.git synced 2025-08-09 08:17:12 +02:00

Upgrade TextformatterMarkdownExtra to use new versions of Parsedown and Parsedown Extra, update module config for new options and add a test option. This update also fixes processwire/processwire-issues#1401

This commit is contained in:
Ryan Cramer
2021-07-09 12:03:05 -04:00
parent 8c6c85c87d
commit 5b3300c530
6 changed files with 1348 additions and 589 deletions

View File

@@ -3,7 +3,7 @@
/** /**
* ProcessWire Markdown Textformatter * ProcessWire Markdown Textformatter
* *
* ProcessWire 3.x, Copyright 2016 by Ryan Cramer * ProcessWire 3.x, Copyright 2021 by Ryan Cramer
* https://processwire.com * https://processwire.com
* *
@@ -11,6 +11,7 @@
* Markdown invented by John Gruber. * Markdown invented by John Gruber.
* *
* @property int $flavor Markdown flavor (see flavor constants) * @property int $flavor Markdown flavor (see flavor constants)
* @property bool|int $safeMode Whether or not we are in safe mode (https://github.com/erusev/parsedown#security)
* *
*/ */
@@ -19,7 +20,7 @@ class TextformatterMarkdownExtra extends Textformatter implements ConfigurableMo
public static function getModuleInfo() { public static function getModuleInfo() {
return array( return array(
'title' => 'Markdown/Parsedown Extra', 'title' => 'Markdown/Parsedown Extra',
'version' => 130, 'version' => 180,
'summary' => "Markdown/Parsedown extra lightweight markup language by Emanuil Rusev. Based on Markdown by John Gruber.", 'summary' => "Markdown/Parsedown extra lightweight markup language by Emanuil Rusev. Based on Markdown by John Gruber.",
); );
} }
@@ -31,51 +32,88 @@ class TextformatterMarkdownExtra extends Textformatter implements ConfigurableMo
const flavorRCD = 16; // add RCD extensions to one of above, @see markdownExtensions() method (@deprecated) const flavorRCD = 16; // add RCD extensions to one of above, @see markdownExtensions() method (@deprecated)
public function __construct() { public function __construct() {
parent::__construct();
$this->set('flavor', self::flavorDefault); $this->set('flavor', self::flavorDefault);
$this->set('safeMode', false);
} }
public function format(&$str) { public function format(&$str) {
$str = $this->markdown($str, $this->flavor); $str = $this->markdown($str, (int) $this->flavor);
} }
public function formatValue(Page $page, Field $field, &$value) { public function formatValue(Page $page, Field $field, &$value) {
$value = $this->markdown($value, $this->flavor); $value = $this->markdown($value, (int) $this->flavor);
}
/**
* Get or set safe mode
*
* “Parsedown is capable of escaping user-input within the HTML that it generates.
* Additionally Parsedown will apply sanitisation to additional scripting vectors
* (such as scripting link destinations) that are introduced by the markdown syntax
* itself. To tell Parsedown that it is processing untrusted user-input, use the
* following...” See: <https://github.com/erusev/parsedown#security>
*
* @param bool|null $safeMode
* @return bool
*
*/
public function safeMode($safeMode = null) {
if($safeMode !== null) $this->safeMode = $safeMode ? true : false;
return (bool) $this->safeMode;
} }
/** /**
* Given a string, return a version processed with markdown * Given a string, return a version processed with markdown
* *
* @param $str String to process * @param $str String to process
* @param int $flavor Flavor of markdown (default=parsedown extra) * @param int|null $flavor Flavor of markdown (null=use module configured setting)
* @param bool|null $safeMode Safe mode ON or OFF (null=use module configured setting)
* @return string Processed string * @return string Processed string
* *
*/ */
public function markdown($str, $flavor = 0) { public function markdown($str, $flavor = null, $safeMode = null) {
$parsedown = $this->getParsedown($flavor);
if(!class_exists("\\Parsedown")) { if(is_bool($safeMode)) $parsedown->setSafeMode($safeMode);
require_once(dirname(__FILE__) . "/parsedown/Parsedown.php"); $str = $parsedown->text($str);
}
if($flavor & self::flavorParsedown) {
// regular parsedown
$parsedown = new \Parsedown();
$str = $parsedown->text($str);
} else {
// parsedown extra
if(!class_exists("\\ParsedownExtra")) {
require_once(dirname(__FILE__) . "/parsedown-extra/ParsedownExtra.php");
}
$extra = new \ParsedownExtra();
$str = $extra->text($str);
}
if($flavor & self::flavorRCD) $this->markdownExtensions($str); if($flavor & self::flavorRCD) $this->markdownExtensions($str);
return $str; return $str;
} }
/**
* Given a string, return a version processed with markdown in safe mode
*
* https://github.com/erusev/parsedown#security
*
* @param $str String to process
* @param int $flavor Flavor of markdown (default=parsedown extra)
* @return string Processed string
*
*/
public function markdownSafe($str, $flavor = 0) {
return $this->markdown($str, $flavor, true);
}
/**
* @param int|null $flavor
* @return \ParsedownExtra|\Parsedown
*
*/
public function getParsedown($flavor = null) {
if($flavor === null) $flavor = (int) $this->flavor;
if(!class_exists("\\Parsedown")) require_once(dirname(__FILE__) . "/parsedown/Parsedown.php");
if(!class_exists("\\ParsedownExtra")) require_once(dirname(__FILE__) . "/parsedown-extra/ParsedownExtra.php");
if($flavor & self::flavorParsedown) {
// regular parsedown
$parsedown = new \Parsedown();
} else {
// parsedown extra
$parsedown = new \ParsedownExtra();
}
if($this->safeMode) $parsedown->setSafeMode(true);
return $parsedown;
}
/** /**
* A few RCD extentions to MarkDown syntax, to be executed after Markdown has already had it's way with the text * A few RCD extentions to MarkDown syntax, to be executed after Markdown has already had it's way with the text
* *
@@ -98,16 +136,52 @@ class TextformatterMarkdownExtra extends Textformatter implements ConfigurableMo
if(strpos($str, '/*') !== false) $str = preg_replace('{/\*.*?\*/}s', '', $str); if(strpos($str, '/*') !== false) $str = preg_replace('{/\*.*?\*/}s', '', $str);
if(strpos($str, '//') !== false) $str = preg_replace('{^//.*$}m', '', $str); if(strpos($str, '//') !== false) $str = preg_replace('{^//.*$}m', '', $str);
} }
public function getModuleConfigInputfields(array $data) { /**
$inputfields = $this->wire(new InputfieldWrapper()); * @param InputfieldWrapper $inputfields
$f = $this->wire('modules')->get('InputfieldRadios'); *
*/
public function getModuleConfigInputfields(InputfieldWrapper $inputfields) {
$f = $inputfields->InputfieldRadios;
$f->attr('name', 'flavor'); $f->attr('name', 'flavor');
$f->label = $this->_('Markdown flavor to use'); $f->label = $this->_('Markdown flavor to use');
$f->addOption(self::flavorParsedownExtra, 'Parsedown Extra'); $f->addOption(self::flavorParsedownExtra, 'Parsedown Extra');
$f->addOption(self::flavorParsedown, 'Parsedown'); $f->addOption(self::flavorParsedown, 'Parsedown');
$f->attr('value', isset($data['flavor']) ? (int) $data['flavor'] : self::flavorDefault); $f->attr('value', (int) $this->flavor);
$inputfields->add($f); $inputfields->add($f);
return $inputfields;
$f = $inputfields->InputfieldToggle;
$f->attr('name', 'safeMode');
$f->label = $this->_('Safe mode?');
$f->description = $this->_('Enable this to Markdown that it is processing untrusted user-input.') . ' ' .
"[" . $this->_('Details') . "](https://github.com/erusev/parsedown#security)";
$f->val((int) $this->safeMode);
$inputfields->add($f);
$f = $inputfields->InputfieldTextarea;
$f->attr('name', '_test_markdown');
$f->label = $this->_('Test markdown');
$f->description = $this->_('Enter some markdown and click submit to test the result with your current settings.');
$f->collapsed = Inputfield::collapsedBlank;
$f->icon = 'flask';
$inputfields->add($f);
$session = $this->wire()->session;
$text = $this->wire()->input->post('_test_markdown');
if($text) {
$session->setFor($this, 'text', $text);
} else {
$text = $session->getFor($this, 'text');
$session->removeFor($this, 'text');
$f->val($text);
if($text) {
$markup = $this->markdown($text);
$this->message("<strong>$f->label results:</strong><br />" .
"<pre>" . $this->wire()->sanitizer->entities($markup) . '</pre>',
Notice::allowMarkup | Notice::noGroup
);
}
}
} }
} }

View File

@@ -1,4 +1,4 @@
<?php <?php
# #
# #
@@ -17,15 +17,15 @@ class ParsedownExtra extends Parsedown
{ {
# ~ # ~
const version = '0.7.0'; const version = '0.8.0';
# ~ # ~
function __construct() function __construct()
{ {
if (parent::version < '1.5.0') if (version_compare(parent::version, '1.7.1') < 0)
{ {
throw new \Exception('ParsedownExtra requires a later version of Parsedown'); throw new Exception('ParsedownExtra requires a later version of Parsedown');
} }
$this->BlockTypes[':'] []= 'DefinitionList'; $this->BlockTypes[':'] []= 'DefinitionList';
@@ -43,7 +43,13 @@ class ParsedownExtra extends Parsedown
function text($text) function text($text)
{ {
$markup = parent::text($text); $Elements = $this->textElements($text);
# convert to markup
$markup = $this->elements($Elements);
# trim line breaks
$markup = trim($markup, "\n");
# merge consecutive dl elements # merge consecutive dl elements
@@ -139,25 +145,27 @@ class ParsedownExtra extends Parsedown
protected function blockDefinitionList($Line, $Block) protected function blockDefinitionList($Line, $Block)
{ {
if ( ! isset($Block) or isset($Block['type'])) if ( ! isset($Block) or $Block['type'] !== 'Paragraph')
{ {
return; return;
} }
$Element = array( $Element = array(
'name' => 'dl', 'name' => 'dl',
'handler' => 'elements', 'elements' => array(),
'text' => array(),
); );
$terms = explode("\n", $Block['element']['text']); $terms = explode("\n", $Block['element']['handler']['argument']);
foreach ($terms as $term) foreach ($terms as $term)
{ {
$Element['text'] []= array( $Element['elements'] []= array(
'name' => 'dt', 'name' => 'dt',
'handler' => 'line', 'handler' => array(
'text' => $term, 'function' => 'lineElements',
'argument' => $term,
'destination' => 'elements'
),
); );
} }
@@ -185,15 +193,17 @@ class ParsedownExtra extends Parsedown
if (isset($Block['interrupted'])) if (isset($Block['interrupted']))
{ {
$Block['dd']['handler'] = 'text'; $Block['dd']['handler']['function'] = 'textElements';
$Block['dd']['text'] .= "\n\n"; $Block['dd']['handler']['argument'] .= "\n\n";
$Block['dd']['handler']['destination'] = 'elements';
unset($Block['interrupted']); unset($Block['interrupted']);
} }
$text = substr($Line['body'], min($Line['indent'], 4)); $text = substr($Line['body'], min($Line['indent'], 4));
$Block['dd']['text'] .= "\n" . $text; $Block['dd']['handler']['argument'] .= "\n" . $text;
return $Block; return $Block;
} }
@@ -206,13 +216,13 @@ class ParsedownExtra extends Parsedown
{ {
$Block = parent::blockHeader($Line); $Block = parent::blockHeader($Line);
if (preg_match('/[ #]*{('.$this->regexAttribute.'+)}[ ]*$/', $Block['element']['text'], $matches, PREG_OFFSET_CAPTURE)) if ($Block !== null && preg_match('/[ #]*{('.$this->regexAttribute.'+)}[ ]*$/', $Block['element']['handler']['argument'], $matches, PREG_OFFSET_CAPTURE))
{ {
$attributeString = $matches[1][0]; $attributeString = $matches[1][0];
$Block['element']['attributes'] = $this->parseAttributeData($attributeString); $Block['element']['attributes'] = $this->parseAttributeData($attributeString);
$Block['element']['text'] = substr($Block['element']['text'], 0, $matches[0][1]); $Block['element']['handler']['argument'] = substr($Block['element']['handler']['argument'], 0, $matches[0][1]);
} }
return $Block; return $Block;
@@ -221,11 +231,98 @@ class ParsedownExtra extends Parsedown
# #
# Markup # Markup
protected function blockMarkup($Line)
{
if ($this->markupEscaped or $this->safeMode)
{
return;
}
if (preg_match('/^<(\w[\w-]*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches))
{
$element = strtolower($matches[1]);
if (in_array($element, $this->textLevelElements))
{
return;
}
$Block = array(
'name' => $matches[1],
'depth' => 0,
'element' => array(
'rawHtml' => $Line['text'],
'autobreak' => true,
),
);
$length = strlen($matches[0]);
$remainder = substr($Line['text'], $length);
if (trim($remainder) === '')
{
if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
{
$Block['closed'] = true;
$Block['void'] = true;
}
}
else
{
if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
{
return;
}
if (preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder))
{
$Block['closed'] = true;
}
}
return $Block;
}
}
protected function blockMarkupContinue($Line, array $Block)
{
if (isset($Block['closed']))
{
return;
}
if (preg_match('/^<'.$Block['name'].'(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*>/i', $Line['text'])) # open
{
$Block['depth'] ++;
}
if (preg_match('/(.*?)<\/'.$Block['name'].'>[ ]*$/i', $Line['text'], $matches)) # close
{
if ($Block['depth'] > 0)
{
$Block['depth'] --;
}
else
{
$Block['closed'] = true;
}
}
if (isset($Block['interrupted']))
{
$Block['element']['rawHtml'] .= "\n";
unset($Block['interrupted']);
}
$Block['element']['rawHtml'] .= "\n".$Line['body'];
return $Block;
}
protected function blockMarkupComplete($Block) protected function blockMarkupComplete($Block)
{ {
if ( ! isset($Block['void'])) if ( ! isset($Block['void']))
{ {
$Block['markup'] = $this->processTag($Block['markup']); $Block['element']['rawHtml'] = $this->processTag($Block['element']['rawHtml']);
} }
return $Block; return $Block;
@@ -238,13 +335,13 @@ class ParsedownExtra extends Parsedown
{ {
$Block = parent::blockSetextHeader($Line, $Block); $Block = parent::blockSetextHeader($Line, $Block);
if (preg_match('/[ ]*{('.$this->regexAttribute.'+)}[ ]*$/', $Block['element']['text'], $matches, PREG_OFFSET_CAPTURE)) if ($Block !== null && preg_match('/[ ]*{('.$this->regexAttribute.'+)}[ ]*$/', $Block['element']['handler']['argument'], $matches, PREG_OFFSET_CAPTURE))
{ {
$attributeString = $matches[1][0]; $attributeString = $matches[1][0];
$Block['element']['attributes'] = $this->parseAttributeData($attributeString); $Block['element']['attributes'] = $this->parseAttributeData($attributeString);
$Block['element']['text'] = substr($Block['element']['text'], 0, $matches[0][1]); $Block['element']['handler']['argument'] = substr($Block['element']['handler']['argument'], 0, $matches[0][1]);
} }
return $Block; return $Block;
@@ -278,8 +375,7 @@ class ParsedownExtra extends Parsedown
$Element = array( $Element = array(
'name' => 'sup', 'name' => 'sup',
'attributes' => array('id' => 'fnref'.$this->DefinitionData['Footnote'][$name]['count'].':'.$name), 'attributes' => array('id' => 'fnref'.$this->DefinitionData['Footnote'][$name]['count'].':'.$name),
'handler' => 'element', 'element' => array(
'text' => array(
'name' => 'a', 'name' => 'a',
'attributes' => array('href' => '#fn:'.$name, 'class' => 'footnote-ref'), 'attributes' => array('href' => '#fn:'.$name, 'class' => 'footnote-ref'),
'text' => $this->DefinitionData['Footnote'][$name]['number'], 'text' => $this->DefinitionData['Footnote'][$name]['number'],
@@ -302,7 +398,7 @@ class ParsedownExtra extends Parsedown
{ {
$Link = parent::inlineLink($Excerpt); $Link = parent::inlineLink($Excerpt);
$remainder = substr($Excerpt['text'], $Link['extent']); $remainder = $Link !== null ? substr($Excerpt['text'], $Link['extent']) : '';
if (preg_match('/^[ ]*{('.$this->regexAttribute.'+)}/', $remainder, $matches)) if (preg_match('/^[ ]*{('.$this->regexAttribute.'+)}/', $remainder, $matches))
{ {
@@ -318,21 +414,52 @@ class ParsedownExtra extends Parsedown
# ~ # ~
# #
protected function unmarkedText($text) private $currentAbreviation;
private $currentMeaning;
protected function insertAbreviation(array $Element)
{ {
$text = parent::unmarkedText($text); if (isset($Element['text']))
{
$Element['elements'] = self::pregReplaceElements(
'/\b'.preg_quote($this->currentAbreviation, '/').'\b/',
array(
array(
'name' => 'abbr',
'attributes' => array(
'title' => $this->currentMeaning,
),
'text' => $this->currentAbreviation,
)
),
$Element['text']
);
unset($Element['text']);
}
return $Element;
}
protected function inlineText($text)
{
$Inline = parent::inlineText($text);
if (isset($this->DefinitionData['Abbreviation'])) if (isset($this->DefinitionData['Abbreviation']))
{ {
foreach ($this->DefinitionData['Abbreviation'] as $abbreviation => $meaning) foreach ($this->DefinitionData['Abbreviation'] as $abbreviation => $meaning)
{ {
$pattern = '/\b'.preg_quote($abbreviation).'\b/'; $this->currentAbreviation = $abbreviation;
$this->currentMeaning = $meaning;
$text = preg_replace($pattern, '<abbr title="'.$meaning.'">'.$abbreviation.'</abbr>', $text); $Inline['element'] = $this->elementApplyRecursiveDepthFirst(
array($this, 'insertAbreviation'),
$Inline['element']
);
} }
} }
return $text; return $Inline;
} }
# #
@@ -348,18 +475,21 @@ class ParsedownExtra extends Parsedown
$Block['dd'] = array( $Block['dd'] = array(
'name' => 'dd', 'name' => 'dd',
'handler' => 'line', 'handler' => array(
'text' => $text, 'function' => 'lineElements',
'argument' => $text,
'destination' => 'elements'
),
); );
if (isset($Block['interrupted'])) if (isset($Block['interrupted']))
{ {
$Block['dd']['handler'] = 'text'; $Block['dd']['handler']['function'] = 'textElements';
unset($Block['interrupted']); unset($Block['interrupted']);
} }
$Block['element']['text'] []= & $Block['dd']; $Block['element']['elements'] []= & $Block['dd'];
return $Block; return $Block;
} }
@@ -369,15 +499,11 @@ class ParsedownExtra extends Parsedown
$Element = array( $Element = array(
'name' => 'div', 'name' => 'div',
'attributes' => array('class' => 'footnotes'), 'attributes' => array('class' => 'footnotes'),
'handler' => 'elements', 'elements' => array(
'text' => array( array('name' => 'hr'),
array(
'name' => 'hr',
),
array( array(
'name' => 'ol', 'name' => 'ol',
'handler' => 'elements', 'elements' => array(),
'text' => array(),
), ),
), ),
); );
@@ -393,34 +519,68 @@ class ParsedownExtra extends Parsedown
$text = $DefinitionData['text']; $text = $DefinitionData['text'];
$text = parent::text($text); $textElements = parent::textElements($text);
$numbers = range(1, $DefinitionData['count']); $numbers = range(1, $DefinitionData['count']);
$backLinksMarkup = ''; $backLinkElements = array();
foreach ($numbers as $number) foreach ($numbers as $number)
{ {
$backLinksMarkup .= ' <a href="#fnref'.$number.':'.$definitionId.'" rev="footnote" class="footnote-backref">&#8617;</a>'; $backLinkElements[] = array('text' => ' ');
$backLinkElements[] = array(
'name' => 'a',
'attributes' => array(
'href' => "#fnref$number:$definitionId",
'rev' => 'footnote',
'class' => 'footnote-backref',
),
'rawHtml' => '&#8617;',
'allowRawHtmlInSafeMode' => true,
'autobreak' => false,
);
} }
$backLinksMarkup = substr($backLinksMarkup, 1); unset($backLinkElements[0]);
if (substr($text, - 4) === '</p>') $n = count($textElements) -1;
if ($textElements[$n]['name'] === 'p')
{ {
$backLinksMarkup = '&#160;'.$backLinksMarkup; $backLinkElements = array_merge(
array(
array(
'rawHtml' => '&#160;',
'allowRawHtmlInSafeMode' => true,
),
),
$backLinkElements
);
$text = substr_replace($text, $backLinksMarkup.'</p>', - 4); unset($textElements[$n]['name']);
$textElements[$n] = array(
'name' => 'p',
'elements' => array_merge(
array($textElements[$n]),
$backLinkElements
),
);
} }
else else
{ {
$text .= "\n".'<p>'.$backLinksMarkup.'</p>'; $textElements[] = array(
'name' => 'p',
'elements' => $backLinkElements
);
} }
$Element['text'][1]['text'] []= array( $Element['elements'][1]['elements'] []= array(
'name' => 'li', 'name' => 'li',
'attributes' => array('id' => 'fn:'.$definitionId), 'attributes' => array('id' => 'fn:'.$definitionId),
'text' => "\n".$text."\n", 'elements' => array_merge(
$textElements
),
); );
} }
@@ -503,10 +663,10 @@ class ParsedownExtra extends Parsedown
} }
# because we don't want for markup to get encoded # because we don't want for markup to get encoded
$DOMDocument->documentElement->nodeValue = 'placeholder'; $DOMDocument->documentElement->nodeValue = 'placeholder\x1A';
$markup = $DOMDocument->saveHTML($DOMDocument->documentElement); $markup = $DOMDocument->saveHTML($DOMDocument->documentElement);
$markup = str_replace('placeholder', $elementText, $markup); $markup = str_replace('placeholder\x1A', $elementText, $markup);
return $markup; return $markup;
} }

View File

@@ -1,8 +1,12 @@
> You might also like [Caret](http://caret.io?ref=parsedown) - our Markdown editor for the Desktop.
## Parsedown Extra ## Parsedown Extra
[![Build Status](https://img.shields.io/travis/erusev/parsedown-extra/master.svg?style=flat-square)](https://travis-ci.org/erusev/parsedown-extra)
An extension of [Parsedown](http://parsedown.org) that adds support for [Markdown Extra](https://michelf.ca/projects/php-markdown/extra/). An extension of [Parsedown](http://parsedown.org) that adds support for [Markdown Extra](https://michelf.ca/projects/php-markdown/extra/).
[[ demo ]](http://parsedown.org/extra/) [See Demo](http://parsedown.org/extra/)
### Installation ### Installation

View File

@@ -1,6 +1,6 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2013 Emanuil Rusev, erusev.com Copyright (c) 2013-2018 Emanuil Rusev, erusev.com
Permission is hereby granted, free of charge, to any person obtaining a copy of Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in this software and associated documentation files (the "Software"), to deal in
@@ -17,4 +17,4 @@ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -1,37 +1,88 @@
## Parsedown <!-- ![Parsedown](https://i.imgur.com/yE8afYV.png) -->
Better Markdown Parser in PHP <p align="center"><img alt="Parsedown" src="https://i.imgur.com/fKVY6Kz.png" width="240" /></p>
[[ demo ]](http://parsedown.org/demo) <h1>Parsedown</h1>
### Features [![Build Status](https://travis-ci.org/erusev/parsedown.svg)](https://travis-ci.org/erusev/parsedown)
[![Total Downloads](https://poser.pugx.org/erusev/parsedown/d/total.svg)](https://packagist.org/packages/erusev/parsedown)
[![Version](https://poser.pugx.org/erusev/parsedown/v/stable.svg)](https://packagist.org/packages/erusev/parsedown)
[![License](https://poser.pugx.org/erusev/parsedown/license.svg)](https://packagist.org/packages/erusev/parsedown)
* [Fast](http://parsedown.org/speed) Better Markdown Parser in PHP - <a href="http://parsedown.org/demo">Demo</a>.
* [Consistent](http://parsedown.org/consistency)
* [GitHub flavored](https://help.github.com/articles/github-flavored-markdown) ## Features
* [Tested](http://parsedown.org/tests/) in PHP 5.2, 5.3, 5.4, 5.5, 5.6 and [hhvm](http://www.hhvm.com/)
* [Extensible](https://github.com/erusev/parsedown/wiki/Writing-Extensions) * One File
* No Dependencies
* [Super Fast](http://parsedown.org/speed)
* Extensible
* [GitHub flavored](https://github.github.com/gfm)
* [Tested](http://parsedown.org/tests/) in 5.3 to 7.3
* [Markdown Extra extension](https://github.com/erusev/parsedown-extra) * [Markdown Extra extension](https://github.com/erusev/parsedown-extra)
### Installation ## Installation
Include `Parsedown.php` or install [the composer package](https://packagist.org/packages/erusev/parsedown). Install the [composer package]:
### Example composer require erusev/parsedown
``` php Or download the [latest release] and include `Parsedown.php`
[composer package]: https://packagist.org/packages/erusev/parsedown "The Parsedown package on packagist.org"
[latest release]: https://github.com/erusev/parsedown/releases/latest "The latest release of Parsedown"
## Example
```php
$Parsedown = new Parsedown(); $Parsedown = new Parsedown();
echo $Parsedown->text('Hello _Parsedown_!'); # prints: <p>Hello <em>Parsedown</em>!</p> echo $Parsedown->text('Hello _Parsedown_!'); # prints: <p>Hello <em>Parsedown</em>!</p>
``` ```
More examples in [the wiki](https://github.com/erusev/parsedown/wiki/Usage) and in [this video tutorial](http://youtu.be/wYZBY8DEikI). You can also parse inline markdown only:
### Questions ```php
echo $Parsedown->line('Hello _Parsedown_!'); # prints: Hello <em>Parsedown</em>!
```
More examples in [the wiki](https://github.com/erusev/parsedown/wiki/) and in [this video tutorial](http://youtu.be/wYZBY8DEikI).
## Security
Parsedown is capable of escaping user-input within the HTML that it generates. Additionally Parsedown will apply sanitisation to additional scripting vectors (such as scripting link destinations) that are introduced by the markdown syntax itself.
To tell Parsedown that it is processing untrusted user-input, use the following:
```php
$Parsedown->setSafeMode(true);
```
If instead, you wish to allow HTML within untrusted user-input, but still want output to be free from XSS it is recommended that you make use of a HTML sanitiser that allows HTML tags to be whitelisted, like [HTML Purifier](http://htmlpurifier.org/).
In both cases you should strongly consider employing defence-in-depth measures, like [deploying a Content-Security-Policy](https://scotthelme.co.uk/content-security-policy-an-introduction/) (a browser security feature) so that your page is likely to be safe even if an attacker finds a vulnerability in one of the first lines of defence above.
#### Security of Parsedown Extensions
Safe mode does not necessarily yield safe results when using extensions to Parsedown. Extensions should be evaluated on their own to determine their specific safety against XSS.
## Escaping HTML
> **WARNING:** This method isn't safe from XSS!
If you wish to escape HTML **in trusted input**, you can use the following:
```php
$Parsedown->setMarkupEscaped(true);
```
Beware that this still allows users to insert unsafe scripting vectors, such as links like `[xss](javascript:alert%281%29)`.
## Questions
**How does Parsedown work?** **How does Parsedown work?**
It tries to read Markdown like a human. First, it looks at the lines. Its interested in how the lines start. This helps it recognise blocks. It knows, for example, that if a line start with a `-` then it perhaps belong to a list. Once it recognises the blocks, it continues to the content. As it reads, it watches out for special characters. This helps it recognise inline elements (or inlines). It tries to read Markdown like a human. First, it looks at the lines. Its interested in how the lines start. This helps it recognise blocks. It knows, for example, that if a line starts with a `-` then perhaps it belongs to a list. Once it recognises the blocks, it continues to the content. As it reads, it watches out for special characters. This helps it recognise inline elements (or inlines).
We call this approach "line based". We believe that Parsedown is the first Markdown parser to use it. Since the release of Parsedown, other developers have used the same approach to develop other Markdown parsers in PHP and in other languages. We call this approach "line based". We believe that Parsedown is the first Markdown parser to use it. Since the release of Parsedown, other developers have used the same approach to develop other Markdown parsers in PHP and in other languages.
@@ -41,8 +92,12 @@ It passes most of the CommonMark tests. Most of the tests that don't pass deal w
**Who uses it?** **Who uses it?**
[phpDocumentor](http://www.phpdoc.org/), [October CMS](http://octobercms.com/), [Bolt CMS](http://bolt.cm/), [Kirby CMS](http://getkirby.com/), [Grav CMS](http://getgrav.org/), [Statamic CMS](http://www.statamic.com/), [RaspberryPi.org](http://www.raspberrypi.org/) and [more](https://www.versioneye.com/php/erusev:parsedown/references). [Laravel Framework](https://laravel.com/), [Bolt CMS](http://bolt.cm/), [Grav CMS](http://getgrav.org/), [Herbie CMS](http://www.getherbie.org/), [Kirby CMS](http://getkirby.com/), [October CMS](http://octobercms.com/), [Pico CMS](http://picocms.org), [Statamic CMS](http://www.statamic.com/), [phpDocumentor](http://www.phpdoc.org/), [RaspberryPi.org](http://www.raspberrypi.org/), [Symfony Demo](https://github.com/symfony/demo) and [more](https://packagist.org/packages/erusev/parsedown/dependents).
**How can I help?** **How can I help?**
Use it, star it, share it and if you feel generous, [donate some money](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=528P3NZQMP8N2). Use it, star it, share it and if you feel generous, [donate](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=528P3NZQMP8N2).
**What else should I know?**
I also make [Nota](https://nota.md/) — a writing app designed for Markdown files :)