#!/usr/bin/env python3 # -*- coding: utf-8 -*- # SAT plugin for managing various text syntaxes # Copyright (C) 2009-2019 Jérôme Poisson (goffi@goffi.org) # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . import re from cgi import escape from functools import partial from sat.core.i18n import _, D_ from sat.core.constants import Const as C from sat.core.log import getLogger from twisted.internet import defer from twisted.internet.threads import deferToThread from sat.core import exceptions from sat.tools import xml_tools try: from lxml import html from lxml.html import clean from lxml import etree except ImportError: raise exceptions.MissingModule( "Missing module lxml, please download/install it from http://lxml.de/" ) log = getLogger(__name__) CATEGORY = D_("Composition") NAME = "Syntax" _SYNTAX_XHTML = "xhtml" # must be lower case _SYNTAX_CURRENT = "@CURRENT@" # TODO: check/adapt following list # list initialy based on feedparser list (http://pythonhosted.org/feedparser/html-sanitization.html) STYLES_WHITELIST = ( "azimuth", "background-color", "border-bottom-color", "border-collapse", "border-color", "border-left-color", "border-right-color", "border-top-color", "clear", "color", "cursor", "direction", "display", "elevation", "float", "font", "font-family", "font-size", "font-style", "font-variant", "font-weight", "height", "letter-spacing", "line-height", "overflow", "pause", "pause-after", "pause-before", "pitch", "pitch-range", "richness", "speak", "speak-header", "speak-numeral", "speak-punctuation", "speech-rate", "stress", "text-align", "text-decoration", "text-indent", "unicode-bidi", "vertical-align", "voice-family", "volume", "white-space", "width", ) # cf. https://www.w3.org/TR/html/syntax.html#void-elements VOID_ELEMENTS = ( "area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr") SAFE_ATTRS = html.defs.safe_attrs.union(("style", "poster", "controls")) STYLES_VALUES_REGEX = ( r"^(" + "|".join( [ "([a-z-]+)", # alphabetical names "(#[0-9a-f]+)", # hex value "(\d+(.\d+)? *(|%|em|ex|px|in|cm|mm|pt|pc))", # values with units (or not) "rgb\( *((\d+(.\d+)?), *){2}(\d+(.\d+)?) *\)", # rgb function "rgba\( *((\d+(.\d+)?), *){3}(\d+(.\d+)?) *\)", # rgba function ] ) + ") *(!important)?$" ) # we accept "!important" at the end STYLES_ACCEPTED_VALUE = re.compile(STYLES_VALUES_REGEX) PLUGIN_INFO = { C.PI_NAME: "Text syntaxes", C.PI_IMPORT_NAME: "TEXT_SYNTAXES", C.PI_TYPE: "MISC", C.PI_PROTOCOLS: [], C.PI_DEPENDENCIES: [], C.PI_MAIN: "TextSyntaxes", C.PI_HANDLER: "no", C.PI_DESCRIPTION: _( """Management of various text syntaxes (XHTML-IM, Markdown, etc)""" ), } class TextSyntaxes(object): """ Text conversion class XHTML utf-8 is used as intermediate language for conversions """ OPT_DEFAULT = "DEFAULT" OPT_HIDDEN = "HIDDEN" OPT_NO_THREAD = "NO_THREAD" SYNTAX_XHTML = _SYNTAX_XHTML SYNTAX_MARKDOWN = "markdown" SYNTAX_TEXT = "text" syntaxes = {} # default_syntax must be lower case default_syntax = SYNTAX_XHTML params = """ %(options)s """ params_data = { "category_name": CATEGORY, "category_label": _(CATEGORY), "name": NAME, "label": _(NAME), "syntaxes": syntaxes, } def __init__(self, host): log.info(_("Text syntaxes plugin initialization")) self.host = host self.addSyntax( self.SYNTAX_XHTML, lambda xhtml: defer.succeed(xhtml), lambda xhtml: defer.succeed(xhtml), TextSyntaxes.OPT_NO_THREAD, ) # TODO: text => XHTML should add to url like in frontends # it's probably best to move sat_frontends.tools.strings to sat.tools.common or similar self.addSyntax( self.SYNTAX_TEXT, lambda text: escape(text), lambda xhtml: self._removeMarkups(xhtml), [TextSyntaxes.OPT_HIDDEN], ) try: import markdown, html2text from markdown.extensions import Extension # XXX: we disable raw HTML parsing by default, to avoid parsing error # when the user is not aware of markdown and HTML class EscapeHTML(Extension): def extendMarkdown(self, md): md.preprocessors.deregister('html_block') md.inlinePatterns.deregister('html') def _html2text(html, baseurl=""): h = html2text.HTML2Text(baseurl=baseurl) h.body_width = 0 # do not truncate the lines, it breaks the long URLs return h.handle(html) self.addSyntax( self.SYNTAX_MARKDOWN, partial(markdown.markdown, extensions=[ EscapeHTML(), 'nl2br', 'codehilite', 'fenced_code', 'sane_lists', 'tables', ], extension_configs = { "codehilite": { "css_class": "highlight", } }), _html2text, [TextSyntaxes.OPT_DEFAULT], ) except ImportError: log.warning("markdown or html2text not found, can't use Markdown syntax") log.info( "You can download/install them from https://pythonhosted.org/Markdown/ and https://github.com/Alir3z4/html2text/" ) host.bridge.addMethod( "syntaxConvert", ".plugin", in_sign="sssbs", out_sign="s", async_=True, method=self.convert, ) host.bridge.addMethod( "syntaxGet", ".plugin", in_sign="s", out_sign="s", method=self.getSyntax ) if xml_tools.cleanXHTML is None: log.debug("Installing cleaning method") xml_tools.cleanXHTML = self.cleanXHTML def _updateParamOptions(self): data_synt = TextSyntaxes.syntaxes default_synt = TextSyntaxes.default_syntax syntaxes = [] for syntax in list(data_synt.keys()): flags = data_synt[syntax]["flags"] if TextSyntaxes.OPT_HIDDEN not in flags: syntaxes.append(syntax) syntaxes.sort(key=lambda synt: synt.lower()) options = [] for syntax in syntaxes: selected = 'selected="true"' if syntax == default_synt else "" options.append('