erusev / parsedown

Better Markdown Parser in PHP
https://parsedown.org
MIT License
14.76k stars 1.12k forks source link

Can't use a highlighter because of the safe mode. #790

Closed themustafaomar closed 3 years ago

themustafaomar commented 3 years ago

Hi, I have a problem using a highlighter because parsedown always escapes the HTML tags of the highlighted text. It's always shown like that even if the setSafeMode and setMarkupEscaped are set to false

image

I made an extension for this, here is the code:

class Markdown extends \Parsedown
{
    protected function blockFencedCodeComplete($Block)
    {
        $highligh = new \Highlight\Highlighter();

        $highlighted = $highligh->highlight('html', $Block['element']['text']['text'])->value;

        $Block['element']['text']['text'] = $highlighted;

        return $Block;
    }
}

After some digging, it turns out that the escape method is responsible for this issue.

image

I tried to overwrite the escape method, but you guys are using self::escape I can't overwrite it, it should be static I think!

protected static function escape($text, $allowQuotes = false)
{
    return $text;

    // return htmlspecialchars($text, $allowQuotes ? ENT_NOQUOTES : ENT_QUOTES, 'UTF-8');
}

I would like to know if there is a better way or anything I can do to solve this problem!

Thanks.

themustafaomar commented 3 years ago

Well, I solved my issue.

class Markdown extends \Parsedown
{
    protected function blockFencedCodeComplete($Block)
    {
        $highlighter = new \Highlight\Highlighter();

        $element = $Block['element']['text'];

        $snippet = $highlighter->highlight(
            $this->resolveLang($element), $element['text']
        )->value;

        $Block['element']['text']['rawHtml'] = $snippet;

        unset($Block['element']['text']['text']);

        return $Block;
    }

    public function resolveLang(array $element)
    {
        return ltrim($element['attributes']['class'], 'language-');
    }
}

By unsetting the text key and create a new one called rawHtml the second condition is going to work. hence the $premitRawHtml variable can be overwritten with true if safeMode is set to false

https://github.com/erusev/parsedown/blob/6598f3860c2698fe2f0f1bc98212fc01d0a1893c/Parsedown.php#L1721-L1735