Example #1
0
 * @see  http://shiflett.org/blog/2007/mar/allowing-html-and-preventing-xss
 *
 * @param  Field  $field  The calling Kirby Field instance.
 * @param  array  $tags   List of html tags to allow.
 *
 * @return Field
 */
field::$methods['safeMarkdown'] = function ($field, $tags = null) {
    // Sensible default for user generated contents
    if (!is_array($tags)) {
        $tags = array('a', 'p', 'em', 'strong', 'ul', 'ol', 'li', 'code', 'pre', 'blockquote');
    }
    // Ensure the string is utf-8 encoded to protect against XSS exploits using
    // different encodings.
    $text = $field->value();
    $encoding = str::encoding($text);
    if (strtolower($encoding) !== 'utf-8') {
        $text = str::convert($text, 'UTF-8//IGNORE', $encoding);
    }
    // Strip all raw html tags from the input, but allow them in code blocks
    if (in_array('code', $tags)) {
        $text = preg_replace_callback('/`[^`]+`|`{3}[^`]+`{3}|~{3}[^~]+~{3}/', function ($m) {
            return str_replace(array('<', '>'), array('&lt;', '&gt;'), $m[0]);
        }, $text);
    }
    $text = strip_tags($text);
    // Setup markdown parser
    $parsedown = new Parsedown();
    $parsedown->setBreaksEnabled(true);
    // Parse markdown and escape output. Now it is safe by default.
    $html = $parsedown->text($text);