Example #1
0
    def __call__(self, stream):
        boolean_attrs = self._BOOLEAN_ATTRS
        empty_elems = self._EMPTY_ELEMS
        noescape_elems = self._NOESCAPE_ELEMS
        have_doctype = False
        noescape = False

        for filter_ in self.filters:
            stream = filter_(stream)
        for kind, data, pos in stream:

            if kind is START or kind is EMPTY:
                tag, attrib = data
                buf = ['<', tag]
                for attr, value in attrib:
                    if attr in boolean_attrs:
                        if value:
                            buf += [' ', attr]
                    elif ':' in attr:
                        if attr == 'xml:lang' and u'lang' not in attrib:
                            buf += [' lang="', escape(value), '"']
                    elif attr != 'xmlns':
                        buf += [' ', attr, '="', escape(value), '"']
                buf.append('>')
                if kind is EMPTY:
                    if tag not in empty_elems:
                        buf.append('</%s>' % tag)
                yield Markup(u''.join(buf))
                if tag in noescape_elems:
                    noescape = True

            elif kind is END:
                yield Markup('</%s>' % data)
                noescape = False

            elif kind is TEXT:
                if noescape:
                    yield data
                else:
                    yield escape(data, quotes=False)

            elif kind is COMMENT:
                yield Markup('<!--%s-->' % data)

            elif kind is DOCTYPE and not have_doctype:
                name, pubid, sysid = data
                buf = ['<!DOCTYPE %s']
                if pubid:
                    buf.append(' PUBLIC "%s"')
                elif sysid:
                    buf.append(' SYSTEM')
                if sysid:
                    buf.append(' "%s"')
                buf.append('>\n')
                yield Markup(u''.join(buf)) % filter(None, data)
                have_doctype = True

            elif kind is PI:
                yield Markup('<?%s %s?>' % data)
Example #2
0
    def __call__(self, stream):
        boolean_attrs = self._BOOLEAN_ATTRS
        empty_elems = self._EMPTY_ELEMS
        noescape_elems = self._NOESCAPE_ELEMS
        have_doctype = False
        noescape = False

        for filter_ in self.filters:
            stream = filter_(stream)
        for kind, data, pos in stream:

            if kind is START or kind is EMPTY:
                tag, attrib = data
                buf = ['<', tag]
                for attr, value in attrib:
                    if attr in boolean_attrs:
                        if value:
                            buf += [' ', attr]
                    elif ':' in attr:
                        if attr == 'xml:lang' and u'lang' not in attrib:
                            buf += [' lang="', escape(value), '"']
                    elif attr != 'xmlns':
                        buf += [' ', attr, '="', escape(value), '"']
                buf.append('>')
                if kind is EMPTY:
                    if tag not in empty_elems:
                        buf.append('</%s>' % tag)
                yield Markup(u''.join(buf))
                if tag in noescape_elems:
                    noescape = True

            elif kind is END:
                yield Markup('</%s>' % data)
                noescape = False

            elif kind is TEXT:
                if noescape:
                    yield data
                else:
                    yield escape(data, quotes=False)

            elif kind is COMMENT:
                yield Markup('<!--%s-->' % data)

            elif kind is DOCTYPE and not have_doctype:
                name, pubid, sysid = data
                buf = ['<!DOCTYPE %s']
                if pubid:
                    buf.append(' PUBLIC "%s"')
                elif sysid:
                    buf.append(' SYSTEM')
                if sysid:
                    buf.append(' "%s"')
                buf.append('>\n')
                yield Markup(u''.join(buf)) % filter(None, data)
                have_doctype = True

            elif kind is PI:
                yield Markup('<?%s %s?>' % data)
Example #3
0
    def __call__(self, stream):
        have_doctype = False
        in_cdata = False

        stream = chain(self.preamble, stream)
        for filter_ in self.filters:
            stream = filter_(stream)
        for kind, data, pos in stream:

            if kind is START or kind is EMPTY:
                tag, attrib = data
                buf = ['<', tag]
                for attr, value in attrib:
                    buf += [' ', attr, '="', escape(value), '"']
                buf.append(kind is EMPTY and '/>' or '>')
                yield Markup(u''.join(buf))

            elif kind is END:
                yield Markup('</%s>' % data)

            elif kind is TEXT:
                if in_cdata:
                    yield data
                else:
                    yield escape(data, quotes=False)

            elif kind is COMMENT:
                yield Markup('<!--%s-->' % data)

            elif kind is DOCTYPE and not have_doctype:
                name, pubid, sysid = data
                buf = ['<!DOCTYPE %s']
                if pubid:
                    buf.append(' PUBLIC "%s"')
                elif sysid:
                    buf.append(' SYSTEM')
                if sysid:
                    buf.append(' "%s"')
                buf.append('>\n')
                yield Markup(u''.join(buf), *filter(None, data))
                have_doctype = True

            elif kind is START_CDATA:
                yield Markup('<![CDATA[')
                in_cdata = True

            elif kind is END_CDATA:
                yield Markup(']]>')
                in_cdata = False

            elif kind is PI:
                yield Markup('<?%s %s?>' % data)
Example #4
0
File: shot.py Project: onetera/sp
	def view2(self, id):
		
		try:
			# 단순히 Get해서 레코드를 가져오기 보다는 MAttr까지 가져와야하니까~~ 좀더 신중하게	  
			viewColStr = "Shot.IDX,Shot.Code,Shot.ViewTemplate,Shot.Name,Shot.TypeCode,Shot.StatCode,Shot.Content," \
						 "Shot.Thumb,Shot.Preview,Shot.CreateDate,Shot.Parent1,Shot.Parent2,Project.Name,Project.Code,Seq.Name,Seq.Code"
			
			row = Archive(self.archiveName).View(id, viewColStr)
			
			if (row["Shot_ViewTemplate"] != None) and (row["Shot_ViewTemplate"] != ""):
				TemplateSkin = row["Shot_ViewTemplate"]
			elif gTable["Shot_Type"][row["Shot_TypeCode"]]["ViewTemplate"] != None:
				TemplateSkin = gTable["Shot_Type"][row["Shot_TypeCode"]]["ViewTemplate"]
			else:
				TemplateSkin = "%s_View.html" % self.archiveName			
			
			for (k,v) in row.items():
				if (type(v) == datetime.datetime) : v = v.strftime("%Y-%m-%d %H:%M")
				if (type(v) in (str, unicode)): v = escape(v)
				setattr(c, k.replace(".","_") , HTML(v) )
			
			c.IDX  = id
			
			return render(TemplateSkin)		   
		
		except Exception as err:		
			traceback.print_exc(file=sys.stdout)			
			return str(err)
Example #5
0
    def _gen_ticket_entry(self, t, a_class=''):
        id = str(t.get('id'))
        status = t.get('status')
        priority = t.get('priority')
        hours = t.get(self.hours_field_name)
        summary = to_unicode(t.get('summary'))
        owner = to_unicode(t.get('owner'))
        description = to_unicode(t.get('description')[:1024])
        url = t.get('href')

        if status == 'closed':
            a_class = a_class + 'closed'
        else:
            a_class = a_class + 'open'
        
        a_class += " ticket priority-" + priority            
        
        markup = format_to_html(self.env, self.ref.context, description)
        # Escape, if requested
        if self.sanitize is True:
            try:
                description = HTMLParser(StringIO(markup)
                                           ).parse() | HTMLSanitizer()
            except ParseError:
                description = escape(markup)
        else:
            description = markup

        # Replace tags that destruct tooltips too much
        desc = self.end_RE.sub(']', Markup(description))
        desc = self.del_RE.sub('', desc)
        # need 2nd run after purging newline in table cells in 1st run
        desc = self.del_RE.sub('', desc)
        desc = self.item_RE.sub('X', desc)
        desc = self.tab_RE.sub('[|||]', desc)
        description = self.open_RE.sub('[', desc)

        tip = tag.span(Markup(description))
        ticket = '#' + id
        ticket = tag.a(ticket, href=url)
        ticket(tip, class_='tip', target='_blank')
        ticket = tag.div(ticket)
        ticket(class_=a_class, align='left', **{"data-ticketid": id})
        # fix stripping of regular leading space in IE
        blank = '&nbsp;'
        ticket(Markup(blank), summary, ' (', owner, ')')
        ticket(tag.span(str(hours) + "h", class_="hours"))

        summary = tag(summary, ' (', owner, ')')
        ticket_short = '#' + id
        ticket_short = tag.a(ticket_short, href=url)
        ticket_short(target='_blank', title_=summary)
        ticket_short = tag.span(ticket_short)
        ticket_short(class_=a_class)

        return ticket,ticket_short
Example #6
0
    def _make_sublink(self, env, sublink, formatter, ns, target, label,
                      fullmatch, extra=''):
        parent_match = {'ns' : ns,
                        'target' : target,
                        'label': Markup(escape(unescape(label)
                                               if isinstance(label, Markup)
                                               else label)),
                        'fullmatch' : fullmatch,
                        }

        # Tweak nested context to work in target product/global scope
        subctx = formatter.context.child()
        subctx.href = resolve_product_href(to_env=env, at_env=self.env)
        try:
            req = formatter.context.req
        except AttributeError:
            pass
        else:
            # Authenticate in local context but use foreign permissions
            subctx.perm = self.FakePermClass() \
                            if isinstance(req.session, FakeSession) \
                            else PermissionCache(env, req.authname)
            subctx.req = req

        subformatter = EmbeddedLinkFormatter(env, subctx, parent_match)
        subformatter.auto_quote = True
        ctxtag = '[%s] ' % (env.product.prefix,) \
                    if isinstance(env, ProductEnvironment) \
                    else '<global> '
        subformatter.enhance_link = lambda link : (
                                link(title=ctxtag + link.attrib.get('title'))
                                if isinstance(link, Element)
                                    and 'title' in link.attrib
                                else link)
        link = subformatter.match(sublink + extra)
        if link:
            return link
        else:
            # Return outermost match unchanged like if it was !-escaped
            for itype, match in fullmatch.groupdict().items():
                if match and not itype in formatter.wikiparser.helper_patterns:
                    return escape(match)
Example #7
0
    def _make_sublink(self, env, sublink, formatter, ns, target, label,
                      fullmatch, extra=''):
        parent_match = {'ns' : ns,
                        'target' : target,
                        'label': Markup(escape(unescape(label)
                                               if isinstance(label, Markup)
                                               else label)),
                        'fullmatch' : fullmatch,
                        }

        # Tweak nested context to work in target product/global scope
        subctx = formatter.context.child()
        subctx.href = resolve_product_href(to_env=env, at_env=self.env)
        try:
            req = formatter.context.req
        except AttributeError:
            pass
        else:
            # Authenticate in local context but use foreign permissions
            subctx.perm = self.FakePermClass() \
                            if isinstance(req.session, FakeSession) \
                            else PermissionCache(env, req.authname)
            subctx.req = req

        subformatter = EmbeddedLinkFormatter(env, subctx, parent_match)
        subformatter.auto_quote = True
        ctxtag = '[%s] ' % (env.product.prefix,) \
                    if isinstance(env, ProductEnvironment) \
                    else '<global> '
        subformatter.enhance_link = lambda link : (
                                link(title=ctxtag + link.attrib.get('title'))
                                if isinstance(link, Element)
                                    and 'title' in link.attrib
                                else link)
        link = subformatter.match(sublink + extra)
        if link:
            return link
        else:
            # Return outermost match unchanged like if it was !-escaped
            for itype, match in fullmatch.groupdict().items():
                if match and not itype in formatter.wikiparser.helper_patterns:
                    return escape(match)
Example #8
0
    def __call__(self,
                 stream,
                 ctxt=None,
                 space=XML_NAMESPACE['space'],
                 trim_trailing_space=re.compile('[ \t]+(?=\n)').sub,
                 collapse_lines=re.compile('\n{2,}').sub):
        mjoin = Markup('').join
        preserve_elems = self.preserve
        preserve = 0
        noescape_elems = self.noescape
        noescape = False

        textbuf = []
        push_text = textbuf.append
        pop_text = textbuf.pop
        for kind, data, pos in chain(stream, [(None, None, None)]):

            if kind is TEXT:
                if noescape:
                    data = Markup(data)
                push_text(data)
            else:
                if textbuf:
                    if len(textbuf) > 1:
                        text = mjoin(textbuf, escape_quotes=False)
                        del textbuf[:]
                    else:
                        text = escape(pop_text(), quotes=False)
                    if not preserve:
                        text = collapse_lines('\n',
                                              trim_trailing_space('', text))
                    yield TEXT, Markup(text), pos

                if kind is START:
                    tag, attrs = data
                    if preserve or (tag in preserve_elems
                                    or attrs.get(space) == 'preserve'):
                        preserve += 1
                    if not noescape and tag in noescape_elems:
                        noescape = True

                elif kind is END:
                    noescape = False
                    if preserve:
                        preserve -= 1

                elif kind is START_CDATA:
                    noescape = True

                elif kind is END_CDATA:
                    noescape = False

                if kind:
                    yield kind, data, pos
Example #9
0
    def __call__(
        self,
        stream,
        ctxt=None,
        space=XML_NAMESPACE["space"],
        trim_trailing_space=re.compile("[ \t]+(?=\n)").sub,
        collapse_lines=re.compile("\n{2,}").sub,
    ):
        mjoin = Markup("").join
        preserve_elems = self.preserve
        preserve = 0
        noescape_elems = self.noescape
        noescape = False

        textbuf = []
        push_text = textbuf.append
        pop_text = textbuf.pop
        for kind, data, pos in chain(stream, [(None, None, None)]):

            if kind is TEXT:
                if noescape:
                    data = Markup(data)
                push_text(data)
            else:
                if textbuf:
                    if len(textbuf) > 1:
                        text = mjoin(textbuf, escape_quotes=False)
                        del textbuf[:]
                    else:
                        text = escape(pop_text(), quotes=False)
                    if not preserve:
                        text = collapse_lines("\n", trim_trailing_space("", text))
                    yield TEXT, Markup(text), pos

                if kind is START:
                    tag, attrs = data
                    if preserve or (tag in preserve_elems or attrs.get(space) == "preserve"):
                        preserve += 1
                    if not noescape and tag in noescape_elems:
                        noescape = True

                elif kind is END:
                    noescape = False
                    if preserve:
                        preserve -= 1

                elif kind is START_CDATA:
                    noescape = True

                elif kind is END_CDATA:
                    noescape = False

                if kind:
                    yield kind, data, pos
Example #10
0
 def visit_system_message(self, node):
     paragraph = node.children.pop(0)
     message = escape(paragraph.astext()) if paragraph else ''
     backrefs = node['backrefs']
     if backrefs:
         span = ('<span class="system-message">%s</span>' %
                 (''.join('<a href="#%s" title="%s">?</a>' %
                          (backref, message)
                          for backref in backrefs)))
     else:
         span = ('<span class="system-message" title="%s">?</span>' %
                 message)
     self.body.append(span)
Example #11
0
    def _gen_ticket_entry(self, t, a_class=''):
        id = str(t.get('id'))
        status = t.get('status')
        summary = to_unicode(t.get('summary'))
        owner = to_unicode(t.get('owner'))
        description = to_unicode(t.get('description')[:1024])
        url = t.get('href')

        if status == 'closed':
            a_class = a_class + 'closed'
        else:
            a_class = a_class + 'open'
        markup = format_to_html(self.env, self.ref.context, description)
        # Escape, if requested
        if self.sanitize is True:
            try:
                description = HTMLParser(StringIO(markup)
                                           ).parse() | HTMLSanitizer()
            except ParseError:
                description = escape(markup)
        else:
            description = markup

        # Replace tags that destruct tooltips too much
        desc = self.end_RE.sub(']', Markup(description))
        desc = self.del_RE.sub('', desc)
        # need 2nd run after purging newline in table cells in 1st run
        desc = self.del_RE.sub('', desc)
        desc = self.item_RE.sub('X', desc)
        desc = self.tab_RE.sub('[|||]', desc)
        description = self.open_RE.sub('[', desc)

        tip = tag.span(Markup(description))
        ticket = '#' + id
        ticket = tag.a(ticket, href=url)
        ticket(tip, class_='tip', target='_blank')
        ticket = tag.div(ticket)
        ticket(class_=a_class, align='left')
        # fix stripping of regular leading space in IE
        blank = '&nbsp;'
        ticket(Markup(blank), summary, ' (', owner, ')')

        summary = tag(summary, ' (', owner, ')')
        ticket_short = '#' + id
        ticket_short = tag.a(ticket_short, href=url)
        ticket_short(target='_blank', title_=summary)
        ticket_short = tag.span(ticket_short)
        ticket_short(class_=a_class)

        return ticket,ticket_short
Example #12
0
    def expand_macro(self, formatter, macro, args):

        args, kw = parse_args(args)

        try:
            source = args.pop(0).strip()
        except NameError:
            return system_message('%s: Missing HTML source argument.' % macro)

        try:
            stream = Stream(HTMLParser(StringIO(source)))
            return (stream | TracHTMLSanitizer()).render('xhtml', encoding=None)
        except ParseError, e:
            self.env.log.warn(e)
            return system_message('%s: HTML parse error: %s.' % (macro, escape(e.msg)))
Example #13
0
    def expand_macro(self, formatter, macro, args):

        args, kw = parse_args(args)

        try:
            source = args.pop(0).strip()
        except NameError:
            return system_message('%s: Missing HTML source argument.' % macro)

        try:
            stream = Stream(HTMLParser(StringIO(source)))
            return (stream | TracHTMLSanitizer()).render('xhtml',
                                                         encoding=None)
        except ParseError, e:
            self.env.log.warn(e)
            return system_message('%s: HTML parse error: %s.' %
                                  (macro, escape(e.msg)))
Example #14
0
    def view2(self, id, id2=None):
        from genshi.core import escape  # [SH] Added

        try:
            row = Archive(self.archiveName).View(id, self.viewColStr)
            for (k, v) in row.items():
                if type(v) == datetime.datetime:
                    v = v.strftime("%Y-%m-%d %H:%M")
                if type(v) in (str, unicode):
                    v = escape(v)  # [SH] Added
                setattr(c, k.replace(".", "_"), HTML(v))

            c.PNID = "PN_%s_%s" % (self.archiveName, id)  # 다른 페이지에서 아직 쓴다.
            c.IDX = id

            return render("%s_View.html" % self.archiveName)

        except Exception as err:
            traceback.print_exc(file=sys.stdout)
            return str(err)
Example #15
0
 def handle_match(self, fullmatch):
     for itype, match in fullmatch.groupdict().items():
         if match:
             # ignore non-wiki references
             if (itype in ['lns', 'sns']) and (match != 'wiki'):
                 return ''
             # ignore Inter-Trac references and
             # references to tickets, changesets, etc.
             if (itype.startswith( 'it_')) or \
                 (itype in ['i3', 'i4', 'i5', 'i6']):
                 return ''
         if match and not itype in self.wikiparser.helper_patterns:
             # Check for preceding escape character '!'
             if match[0] == '!':
                 return escape(match[1:])
             if itype in self.wikiparser.external_handlers:
                 external_handler = self.wikiparser.external_handlers[itype]
                 return external_handler(self, match, fullmatch)
             else:
                 internal_handler = getattr(self, '_%s_formatter' % itype)
                 return internal_handler(match, fullmatch)
Example #16
0
 def test_escape_noquotes(self):
     markup = escape('<b>"&"</b>', quotes=False)
     assert type(markup) is Markup
     self.assertEquals('&lt;b&gt;"&amp;"&lt;/b&gt;', markup)
Example #17
0
 def test_escape(self):
     markup = escape('<b>"&"</b>')
     assert type(markup) is Markup
     self.assertEquals('&lt;b&gt;&#34;&amp;&#34;&lt;/b&gt;', markup)
Example #18
0
                res = re.search(r'FRAGMENT\(([^)]*)\)', line)
                if res:
                    current_fragment_name = res.groups()[0]
                else:
                    if current_fragment_name == fragment_name:
                        fragment.append(line)
            out = '\n'.join(fragment)
            
        # If we have a preview format, use it
        if dest_format:
            # We can trust the output and do not need to call the HTML sanitizer
            # below.  The HTML sanitization leads to whitespace being stripped.
            safe_content = True
            out = Mimeview(self.env).render(ctxt, dest_format, out, force_source=True)
        
        # Escape if needed
        if not safe_content and not self.config.getbool('wiki', 'render_unsafe_content', False):
            try:
                out = HTMLParser(StringIO(out)).parse() | HTMLSanitizer()
            except ParseError:
                out = escape(out)
        
        return out
            
    # IPermissionRequestor methods
    def get_permission_actions(self):
        yield 'INCLUDE_URL'
            
        
        
Example #19
0
    def __call__(self, stream):
        boolean_attrs = self._BOOLEAN_ATTRS
        empty_elems = self._EMPTY_ELEMS
        noescape_elems = self._NOESCAPE_ELEMS
        have_doctype = False
        noescape = False

        cache = {}
        cache_get = cache.get
        if self.cache:
            def _emit(kind, input, output):
                cache[kind, input] = output
                return output
        else:
            def _emit(kind, input, output):
                return output

        for filter_ in self.filters:
            stream = filter_(stream)
        for kind, data, _ in stream:
            output = cache_get((kind, data))
            if output is not None:
                yield output
                if (kind is START or kind is EMPTY) \
                        and data[0] in noescape_elems:
                    noescape = True
                elif kind is END:
                    noescape = False

            elif kind is START or kind is EMPTY:
                tag, attrib = data
                buf = ['<', tag]
                for attr, value in attrib:
                    if attr in boolean_attrs:
                        if value:
                            buf += [' ', attr]
                    elif ':' in attr:
                        if attr == 'xml:lang' and 'lang' not in attrib:
                            buf += [' lang="', escape(value), '"']
                    elif attr != 'xmlns':
                        buf += [' ', attr, '="', escape(value), '"']
                buf.append('>')
                if kind is EMPTY:
                    if tag not in empty_elems:
                        buf.append('</%s>' % tag)
                yield _emit(kind, data, Markup(''.join(buf)))
                if tag in noescape_elems:
                    noescape = True

            elif kind is END:
                yield _emit(kind, data, Markup('</%s>' % data))
                noescape = False

            elif kind is TEXT:
                if noescape:
                    yield _emit(kind, data, data)
                else:
                    yield _emit(kind, data, escape(data, quotes=False))

            elif kind is COMMENT:
                yield _emit(kind, data, Markup('<!--%s-->' % data))

            elif kind is DOCTYPE and not have_doctype:
                name, pubid, sysid = data
                buf = ['<!DOCTYPE %s']
                if pubid:
                    buf.append(' PUBLIC "%s"')
                elif sysid:
                    buf.append(' SYSTEM')
                if sysid:
                    buf.append(' "%s"')
                buf.append('>\n')
                yield Markup(''.join(buf)) % tuple([p for p in data if p])
                have_doctype = True

            elif kind is PI:
                yield _emit(kind, data, Markup('<?%s %s?>' % data))
Example #20
0
    def __call__(self, stream):
        boolean_attrs = self._BOOLEAN_ATTRS
        empty_elems = self._EMPTY_ELEMS
        drop_xml_decl = self.drop_xml_decl
        have_decl = have_doctype = False
        in_cdata = False

        cache = {}
        cache_get = cache.get
        if self.cache:
            def _emit(kind, input, output):
                cache[kind, input] = output
                return output
        else:
            def _emit(kind, input, output):
                return output

        for filter_ in self.filters:
            stream = filter_(stream)
        for kind, data, pos in stream:
            cached = cache_get((kind, data))
            if cached is not None:
                yield cached

            elif kind is START or kind is EMPTY:
                tag, attrib = data
                buf = ['<', tag]
                for attr, value in attrib:
                    if attr in boolean_attrs:
                        value = attr
                    elif attr == 'xml:lang' and 'lang' not in attrib:
                        buf += [' lang="', escape(value), '"']
                    elif attr == 'xml:space':
                        continue
                    buf += [' ', attr, '="', escape(value), '"']
                if kind is EMPTY:
                    if tag in empty_elems:
                        buf.append(' />')
                    else:
                        buf.append('></%s>' % tag)
                else:
                    buf.append('>')
                yield _emit(kind, data, Markup(''.join(buf)))

            elif kind is END:
                yield _emit(kind, data, Markup('</%s>' % data))

            elif kind is TEXT:
                if in_cdata:
                    yield _emit(kind, data, data)
                else:
                    yield _emit(kind, data, escape(data, quotes=False))

            elif kind is COMMENT:
                yield _emit(kind, data, Markup('<!--%s-->' % data))

            elif kind is DOCTYPE and not have_doctype:
                name, pubid, sysid = data
                buf = ['<!DOCTYPE %s']
                if pubid:
                    buf.append(' PUBLIC "%s"')
                elif sysid:
                    buf.append(' SYSTEM')
                if sysid:
                    buf.append(' "%s"')
                buf.append('>\n')
                yield Markup(''.join(buf)) % tuple([p for p in data if p])
                have_doctype = True

            elif kind is XML_DECL and not have_decl and not drop_xml_decl:
                version, encoding, standalone = data
                buf = ['<?xml version="%s"' % version]
                if encoding:
                    buf.append(' encoding="%s"' % encoding)
                if standalone != -1:
                    standalone = standalone and 'yes' or 'no'
                    buf.append(' standalone="%s"' % standalone)
                buf.append('?>\n')
                yield Markup(''.join(buf))
                have_decl = True

            elif kind is START_CDATA:
                yield Markup('<![CDATA[')
                in_cdata = True

            elif kind is END_CDATA:
                yield Markup(']]>')
                in_cdata = False

            elif kind is PI:
                yield _emit(kind, data, Markup('<?%s %s?>' % data))
Example #21
0
    def __call__(self, stream):
        boolean_attrs = self._BOOLEAN_ATTRS
        empty_elems = self._EMPTY_ELEMS
        drop_xml_decl = self.drop_xml_decl
        have_decl = have_doctype = False
        in_cdata = False
        _emit, _get = self._prepare_cache()

        for filter_ in self.filters:
            stream = filter_(stream)
        for kind, data, pos in stream:
            if kind is TEXT and isinstance(data, Markup):
                yield data
                continue
            cached = _get((kind, data))
            if cached is not None:
                yield cached

            elif kind is START or kind is EMPTY:
                tag, attrib = data
                buf = ["<", tag]
                for attr, value in attrib:
                    if attr in boolean_attrs:
                        value = attr
                    elif attr == "xml:lang" and "lang" not in attrib:
                        buf += [' lang="', escape(value), '"']
                    elif attr == "xml:space":
                        continue
                    buf += [" ", attr, '="', escape(value), '"']
                if kind is EMPTY:
                    if tag in empty_elems:
                        buf.append(" />")
                    else:
                        buf.append("></%s>" % tag)
                else:
                    buf.append(">")
                yield _emit(kind, data, Markup("".join(buf)))

            elif kind is END:
                yield _emit(kind, data, Markup("</%s>" % data))

            elif kind is TEXT:
                if in_cdata:
                    yield _emit(kind, data, data)
                else:
                    yield _emit(kind, data, escape(data, quotes=False))

            elif kind is COMMENT:
                yield _emit(kind, data, Markup("<!--%s-->" % data))

            elif kind is DOCTYPE and not have_doctype:
                name, pubid, sysid = data
                buf = ["<!DOCTYPE %s"]
                if pubid:
                    buf.append(' PUBLIC "%s"')
                elif sysid:
                    buf.append(" SYSTEM")
                if sysid:
                    buf.append(' "%s"')
                buf.append(">\n")
                yield Markup("".join(buf)) % tuple([p for p in data if p])
                have_doctype = True

            elif kind is XML_DECL and not have_decl and not drop_xml_decl:
                version, encoding, standalone = data
                buf = ['<?xml version="%s"' % version]
                if encoding:
                    buf.append(' encoding="%s"' % encoding)
                if standalone != -1:
                    standalone = standalone and "yes" or "no"
                    buf.append(' standalone="%s"' % standalone)
                buf.append("?>\n")
                yield Markup("".join(buf))
                have_decl = True

            elif kind is START_CDATA:
                yield Markup("<![CDATA[")
                in_cdata = True

            elif kind is END_CDATA:
                yield Markup("]]>")
                in_cdata = False

            elif kind is PI:
                yield _emit(kind, data, Markup("<?%s %s?>" % data))
Example #22
0
File: core.py Project: alon/polinax
 def test_escape_noquotes(self):
     markup = escape('<b>"&"</b>', quotes=False)
     assert type(markup) is Markup
     self.assertEquals('&lt;b&gt;"&amp;"&lt;/b&gt;', markup)
Example #23
0
File: core.py Project: alon/polinax
 def test_escape(self):
     markup = escape('<b>"&"</b>')
     assert type(markup) is Markup
     self.assertEquals('&lt;b&gt;&#34;&amp;&#34;&lt;/b&gt;', markup)
Example #24
0
    def __call__(self, stream):
        have_decl = have_doctype = False
        in_cdata = False

        for filter_ in self.filters:
            stream = filter_(stream)
        for kind, data, pos in stream:

            if kind is START or kind is EMPTY:
                tag, attrib = data
                buf = ['<', tag]
                for attr, value in attrib:
                    buf += [' ', attr, '="', escape(value), '"']
                buf.append(kind is EMPTY and '/>' or '>')
                yield Markup(u''.join(buf))

            elif kind is END:
                yield Markup('</%s>' % data)

            elif kind is TEXT:
                if in_cdata:
                    yield data
                else:
                    yield escape(data, quotes=False)

            elif kind is COMMENT:
                yield Markup('<!--%s-->' % data)

            elif kind is XML_DECL and not have_decl:
                version, encoding, standalone = data
                buf = ['<?xml version="%s"' % version]
                if encoding:
                    buf.append(' encoding="%s"' % encoding)
                if standalone != -1:
                    standalone = standalone and 'yes' or 'no'
                    buf.append(' standalone="%s"' % standalone)
                buf.append('?>\n')
                yield Markup(u''.join(buf))
                have_decl = True

            elif kind is DOCTYPE and not have_doctype:
                name, pubid, sysid = data
                buf = ['<!DOCTYPE %s']
                if pubid:
                    buf.append(' PUBLIC "%s"')
                elif sysid:
                    buf.append(' SYSTEM')
                if sysid:
                    buf.append(' "%s"')
                buf.append('>\n')
                yield Markup(u''.join(buf)) % filter(None, data)
                have_doctype = True

            elif kind is START_CDATA:
                yield Markup('<![CDATA[')
                in_cdata = True

            elif kind is END_CDATA:
                yield Markup(']]>')
                in_cdata = False

            elif kind is PI:
                yield Markup('<?%s %s?>' % data)
Example #25
0
    def __call__(self, stream):
        have_decl = have_doctype = False
        in_cdata = False

        cache = {}
        cache_get = cache.get
        if self.cache:

            def _emit(kind, input, output):
                cache[kind, input] = output
                return output
        else:

            def _emit(kind, input, output):
                return output

        for filter_ in self.filters:
            stream = filter_(stream)
        for kind, data, pos in stream:
            cached = cache_get((kind, data))
            if cached is not None:
                yield cached

            elif kind is START or kind is EMPTY:
                tag, attrib = data
                buf = ['<', tag]
                for attr, value in attrib:
                    buf += [' ', attr, '="', escape(value), '"']
                buf.append(kind is EMPTY and '/>' or '>')
                yield _emit(kind, data, Markup(''.join(buf)))

            elif kind is END:
                yield _emit(kind, data, Markup('</%s>' % data))

            elif kind is TEXT:
                if in_cdata:
                    yield _emit(kind, data, data)
                else:
                    yield _emit(kind, data, escape(data, quotes=False))

            elif kind is COMMENT:
                yield _emit(kind, data, Markup('<!--%s-->' % data))

            elif kind is XML_DECL and not have_decl:
                version, encoding, standalone = data
                buf = ['<?xml version="%s"' % version]
                if encoding:
                    buf.append(' encoding="%s"' % encoding)
                if standalone != -1:
                    standalone = standalone and 'yes' or 'no'
                    buf.append(' standalone="%s"' % standalone)
                buf.append('?>\n')
                yield Markup(''.join(buf))
                have_decl = True

            elif kind is DOCTYPE and not have_doctype:
                name, pubid, sysid = data
                buf = ['<!DOCTYPE %s']
                if pubid:
                    buf.append(' PUBLIC "%s"')
                elif sysid:
                    buf.append(' SYSTEM')
                if sysid:
                    buf.append(' "%s"')
                buf.append('>\n')
                yield Markup(''.join(buf)) % tuple([p for p in data if p])
                have_doctype = True

            elif kind is START_CDATA:
                yield Markup('<![CDATA[')
                in_cdata = True

            elif kind is END_CDATA:
                yield Markup(']]>')
                in_cdata = False

            elif kind is PI:
                yield _emit(kind, data, Markup('<?%s %s?>' % data))
Example #26
0
    def __call__(self, stream):
        boolean_attrs = self._BOOLEAN_ATTRS
        empty_elems = self._EMPTY_ELEMS
        noescape_elems = self._NOESCAPE_ELEMS
        have_doctype = False
        noescape = False
        _emit, _get = self._prepare_cache()

        for filter_ in self.filters:
            stream = filter_(stream)
        for kind, data, _ in stream:
            if kind is TEXT and isinstance(data, Markup):
                yield data
                continue
            output = _get((kind, data))
            if output is not None:
                yield output
                if (kind is START or kind is EMPTY) and data[0] in noescape_elems:
                    noescape = True
                elif kind is END:
                    noescape = False

            elif kind is START or kind is EMPTY:
                tag, attrib = data
                buf = ["<", tag]
                for attr, value in attrib:
                    if attr in boolean_attrs:
                        if value:
                            buf += [" ", attr]
                    elif ":" in attr:
                        if attr == "xml:lang" and "lang" not in attrib:
                            buf += [' lang="', escape(value), '"']
                    elif attr != "xmlns":
                        buf += [" ", attr, '="', escape(value), '"']
                buf.append(">")
                if kind is EMPTY:
                    if tag not in empty_elems:
                        buf.append("</%s>" % tag)
                yield _emit(kind, data, Markup("".join(buf)))
                if tag in noescape_elems:
                    noescape = True

            elif kind is END:
                yield _emit(kind, data, Markup("</%s>" % data))
                noescape = False

            elif kind is TEXT:
                if noescape:
                    yield _emit(kind, data, data)
                else:
                    yield _emit(kind, data, escape(data, quotes=False))

            elif kind is COMMENT:
                yield _emit(kind, data, Markup("<!--%s-->" % data))

            elif kind is DOCTYPE and not have_doctype:
                name, pubid, sysid = data
                buf = ["<!DOCTYPE %s"]
                if pubid:
                    buf.append(' PUBLIC "%s"')
                elif sysid:
                    buf.append(" SYSTEM")
                if sysid:
                    buf.append(' "%s"')
                buf.append(">\n")
                yield Markup("".join(buf)) % tuple([p for p in data if p])
                have_doctype = True

            elif kind is PI:
                yield _emit(kind, data, Markup("<?%s %s?>" % data))
Example #27
0
    def __call__(self, stream):
        boolean_attrs = self._BOOLEAN_ATTRS
        empty_elems = self._EMPTY_ELEMS
        drop_xml_decl = self.drop_xml_decl
        have_decl = have_doctype = False
        in_cdata = False
        _emit, _get = self._prepare_cache()

        for filter_ in self.filters:
            stream = filter_(stream)
        for kind, data, pos in stream:
            if kind is TEXT and isinstance(data, Markup):
                yield data
                continue
            cached = _get((kind, data))
            if cached is not None:
                yield cached

            elif kind is START or kind is EMPTY:
                tag, attrib = data
                buf = ['<', tag]
                for attr, value in attrib:
                    if attr in boolean_attrs:
                        value = attr
                    elif attr == 'xml:lang' and 'lang' not in attrib:
                        buf += [' lang="', escape(value), '"']
                    elif attr == 'xml:space':
                        continue
                    buf += [' ', attr, '="', escape(value), '"']
                if kind is EMPTY:
                    if tag in empty_elems:
                        buf.append(' />')
                    else:
                        buf.append('></%s>' % tag)
                else:
                    buf.append('>')
                yield _emit(kind, data, Markup(''.join(buf)))

            elif kind is END:
                yield _emit(kind, data, Markup('</%s>' % data))

            elif kind is TEXT:
                if in_cdata:
                    yield _emit(kind, data, data)
                else:
                    yield _emit(kind, data, escape(data, quotes=False))

            elif kind is COMMENT:
                yield _emit(kind, data, Markup('<!--%s-->' % data))

            elif kind is DOCTYPE and not have_doctype:
                name, pubid, sysid = data
                buf = ['<!DOCTYPE %s']
                if pubid:
                    buf.append(' PUBLIC "%s"')
                elif sysid:
                    buf.append(' SYSTEM')
                if sysid:
                    buf.append(' "%s"')
                buf.append('>\n')
                yield Markup(''.join(buf)) % tuple([p for p in data if p])
                have_doctype = True

            elif kind is XML_DECL and not have_decl and not drop_xml_decl:
                version, encoding, standalone = data
                buf = ['<?xml version="%s"' % version]
                if encoding:
                    buf.append(' encoding="%s"' % encoding)
                if standalone != -1:
                    standalone = standalone and 'yes' or 'no'
                    buf.append(' standalone="%s"' % standalone)
                buf.append('?>\n')
                yield Markup(''.join(buf))
                have_decl = True

            elif kind is START_CDATA:
                yield Markup('<![CDATA[')
                in_cdata = True

            elif kind is END_CDATA:
                yield Markup(']]>')
                in_cdata = False

            elif kind is PI:
                yield _emit(kind, data, Markup('<?%s %s?>' % data))
Example #28
0
    def __call__(self, stream):
        boolean_attrs = self._BOOLEAN_ATTRS
        empty_elems = self._EMPTY_ELEMS
        noescape_elems = self._NOESCAPE_ELEMS
        have_doctype = False
        noescape = False
        _emit, _get = self._prepare_cache()

        for filter_ in self.filters:
            stream = filter_(stream)
        for kind, data, _ in stream:
            if kind is TEXT and isinstance(data, Markup):
                yield data
                continue
            output = _get((kind, data))
            if output is not None:
                yield output
                if (kind is START or kind is EMPTY) \
                        and data[0] in noescape_elems:
                    noescape = True
                elif kind is END:
                    noescape = False

            elif kind is START or kind is EMPTY:
                tag, attrib = data
                buf = ['<', tag]
                for attr, value in attrib:
                    if attr in boolean_attrs:
                        if value:
                            buf += [' ', attr]
                    elif ':' in attr:
                        if attr == 'xml:lang' and 'lang' not in attrib:
                            buf += [' lang="', escape(value), '"']
                    elif attr != 'xmlns':
                        buf += [' ', attr, '="', escape(value), '"']
                buf.append('>')
                if kind is EMPTY:
                    if tag not in empty_elems:
                        buf.append('</%s>' % tag)
                yield _emit(kind, data, Markup(''.join(buf)))
                if tag in noescape_elems:
                    noescape = True

            elif kind is END:
                yield _emit(kind, data, Markup('</%s>' % data))
                noescape = False

            elif kind is TEXT:
                if noescape:
                    yield _emit(kind, data, data)
                else:
                    yield _emit(kind, data, escape(data, quotes=False))

            elif kind is COMMENT:
                yield _emit(kind, data, Markup('<!--%s-->' % data))

            elif kind is DOCTYPE and not have_doctype:
                name, pubid, sysid = data
                buf = ['<!DOCTYPE %s']
                if pubid:
                    buf.append(' PUBLIC "%s"')
                elif sysid:
                    buf.append(' SYSTEM')
                if sysid:
                    buf.append(' "%s"')
                buf.append('>\n')
                yield Markup(''.join(buf)) % tuple([p for p in data if p])
                have_doctype = True

            elif kind is PI:
                yield _emit(kind, data, Markup('<?%s %s?>' % data))
Example #29
0
    {
        'tc_title_prefix': 'short product syntax unicode prefix',
        'link_prefix': u'xü' + PRODUCT_SYNTAX_DELIMITER,
        'link_prefix_quote': u'xü%s"' % PRODUCT_SYNTAX_DELIMITER,
        'path_prefix': '/products/x%C3%BC',
        'main_product': 'tp2',
        'setup_product': u'xü',
        'link_title_prefix': u'[xü] ',
    },
]

for ctxlst in (TEST_PRODUCT_CONTEXTS, TEST_PRODUCT_CONTEXTS_COMPACT):
    for _ctx in ctxlst:
        _product_extras = {}
        for k, v in _ctx.iteritems():
            _product_extras[k + '_escaped'] = escape(v)
            if k.endswith('_product'):
                if v in MultiproductTestCase.PRODUCT_DATA:
                    _product_extras[
                        k +
                        '_name'] = MultiproductTestCase.PRODUCT_DATA[v]['name']
                else:
                    _product_extras[k + '_name'] = ''
                _product_extras[k + '_name_escaped'] = escape(
                    _product_extras[k + '_name'])
        _ctx.update(_product_extras)

del _ctx, k, v, _product_extras


def test_suite():
Example #30
0
    def __call__(self, stream):
        have_decl = have_doctype = False
        in_cdata = False
        _emit, _get = self._prepare_cache()

        for filter_ in self.filters:
            stream = filter_(stream)
        for kind, data, pos in stream:
            if kind is TEXT and isinstance(data, Markup):
                yield data
                continue
            cached = _get((kind, data))
            if cached is not None:
                yield cached
            elif kind is START or kind is EMPTY:
                tag, attrib = data
                buf = ['<', tag]
                for attr, value in attrib:
                    buf += [' ', attr, '="', escape(value), '"']
                buf.append(kind is EMPTY and '/>' or '>')
                yield _emit(kind, data, Markup(''.join(buf)))

            elif kind is END:
                yield _emit(kind, data, Markup('</%s>' % data))

            elif kind is TEXT:
                if in_cdata:
                    yield _emit(kind, data, data)
                else:
                    yield _emit(kind, data, escape(data, quotes=False))

            elif kind is COMMENT:
                yield _emit(kind, data, Markup('<!--%s-->' % data))

            elif kind is XML_DECL and not have_decl:
                version, encoding, standalone = data
                buf = ['<?xml version="%s"' % version]
                if encoding:
                    buf.append(' encoding="%s"' % encoding)
                if standalone != -1:
                    standalone = standalone and 'yes' or 'no'
                    buf.append(' standalone="%s"' % standalone)
                buf.append('?>\n')
                yield Markup(''.join(buf))
                have_decl = True

            elif kind is DOCTYPE and not have_doctype:
                name, pubid, sysid = data
                buf = ['<!DOCTYPE %s']
                if pubid:
                    buf.append(' PUBLIC "%s"')
                elif sysid:
                    buf.append(' SYSTEM')
                if sysid:
                    buf.append(' "%s"')
                buf.append('>\n')
                yield Markup(''.join(buf)) % tuple([p for p in data if p])
                have_doctype = True

            elif kind is START_CDATA:
                yield Markup('<![CDATA[')
                in_cdata = True

            elif kind is END_CDATA:
                yield Markup(']]>')
                in_cdata = False

            elif kind is PI:
                yield _emit(kind, data, Markup('<?%s %s?>' % data))
Example #31
0
                          },
                         {'tc_title_prefix' : 'short product syntax unicode prefix',
                          'link_prefix' : u'xü' + PRODUCT_SYNTAX_DELIMITER,
                          'link_prefix_quote' : u'xü%s"' % PRODUCT_SYNTAX_DELIMITER,
                          'path_prefix' : '/products/x%C3%BC',
                          'main_product' : 'tp2',
                          'setup_product' : u'xü',
                          'link_title_prefix' : u'[xü] ',
                          },
                        ]

for ctxlst in (TEST_PRODUCT_CONTEXTS, TEST_PRODUCT_CONTEXTS_COMPACT):
    for _ctx in ctxlst:
        _product_extras = {}
        for k,v in _ctx.iteritems():
            _product_extras[k + '_escaped'] = escape(v)
            if k.endswith('_product'):
                if v in MultiproductTestCase.PRODUCT_DATA:
                    _product_extras[k + '_name'] = MultiproductTestCase.PRODUCT_DATA[v]['name']
                else:
                    _product_extras[k + '_name'] = ''
                _product_extras[k + '_name_escaped'] = escape(_product_extras[k + '_name'])
        _ctx.update(_product_extras)

del _ctx, k, v, _product_extras

def test_suite():
    suite = unittest.TestSuite()

    # Legacy test cases
    suite.addTest(formatter.test_suite(wikisyntax.SEARCH_TEST_CASES,