Beispiel #1
0
 def link(self, text=None, structure=False, title=None, css_class=None,
          icon=0, preview=0, **args):
     """ Returns an HTML link tag for the file or image.
         The 'text' argument is subject to HTML-quoting. To pass a
         structure (e.g. an <img /> tag), set the 'structure' keyword
         argument to True.
     """
     href = self._static_url(icon=icon, preview=preview)
     if text is None:
         text = html_quote(self.title_or_id())
     elif not structure:
         text = html_quote(text)
     if title is None:
         title = getattr(self, 'title', '')
     title = html_quote(title)
     return self._link(href, text, title, css_class, **args)
Beispiel #2
0
 def link(self, text='', **args):
     """ Return an HTML link tag to the file or image.
         Assumes all arguments are properly quoted.
     """
     if not text:
         text = html_quote(self.title_or_id())
     return self._link(self._static_url(), text, **args)
Beispiel #3
0
 def link(self, text='', **args):
     """ Return an HTML link tag to the file or image.
         Assumes all arguments are properly quoted.
     """
     if not text:
         text = html_quote(self.title_or_id())
     return self._link(self._static_url(), text, **args)
Beispiel #4
0
 def testSkipQuote(self):
     methods = "html_quote",
     a = '\0he>llo'
     for method in methods:
         html = self.doc_class('<dtml-var a %s>' % method)
         expected = html_quote(a)
         res = html(a=a)
         self.assertEqual(res, expected)
Beispiel #5
0
    def testSkipQuote(self):
        methods = "html_quote",
        a = '\0he>llo'
        for method in methods:
            expected = html_quote(a)

            html = self.doc_class('<dtml-var a %s>' % method)
            self.assertEqual(html(a=a), expected)

            html = self.doc_class('&dtml.%s-a;' % method)
            self.assertEqual(html(a=a), expected)
    def testSkipQuote(self):
        methods = "html_quote",
        a = '\0he>llo'
        for method in methods:
            expected = html_quote(a)

            html = self.doc_class('<dtml-var a %s>' % method)
            self.assertEqual(html(a=a), expected)

            html = self.doc_class('&dtml.%s-a;' % method)
            self.assertEqual(html(a=a), expected)
def getImageFor(latexCode, charheightpx):    
    preamble, postamble = '', ''
    width, height = '', '' 
    imageFile = fileNameFor(latexCode, charheightpx, '.png')
    imageUrl = imagesPath + imageFile
    width, height = getPngSize(os.path.join(workingDir, imageFile))
    src = html_quote(re.match(latexRemoveDelim, latexCode, re.MULTILINE|re.DOTALL).group(2))
    src = re.sub(r'\n\n+', '\n', src) # FIXME collapse blank lines or they will
    # be interpreted as stx paragraphs -- this is an stx bug since they are
    # inside a tag.
    return '%s<img alt="%s" class="equation" src="%s" width="%s" height="%s"/>%s' %(preamble,
                                                            src,
                                                            imageUrl,
                                                            width,
                                                            height,
                                                            postamble)
    def manage_test(self, REQUEST):
        """Test an SQL method."""
        # Try to render the query template first so that the rendered
        # source will be available for the error message in case some
        # error occurs...
        try:
            src = self(REQUEST, src__=1)
        except Exception:
            src = 'Could not render the query template!'

        result = ()
        t = v = tb = None
        try:
            try:
                src, result = self(REQUEST, test__=1)
                if src.find('\0'):
                    src = ('\n' + '-' * 60 + '\n').join(src.split('\0'))
                if result._searchable_result_columns():
                    r = custom_default_report(self.id, result)
                else:
                    r = 'This statement returned no results.'
            except Exception:
                t, v, tb = sys.exc_info()
                r = '<strong>Error, <em>%s</em>:</strong> %s' % (t, v)

            report = HTML(
                '<html>\n'
                '<BODY BGCOLOR="#FFFFFF" LINK="#000099" VLINK="#555555">\n'
                '<dtml-var manage_tabs>\n<hr>\n%s\n\n'
                '<hr><strong>SQL used:</strong><br>\n<pre>\n%s\n</pre>\n<hr>\n'
                '</body></html>'
                % (r, html_quote(src)))

            report = report(*(self, REQUEST), **{self.id: result})

            if tb is not None:
                self.raise_standardErrorMessage(
                    None, REQUEST, t, v, tb, None, report)

            return report

        finally:
            tb = None
Beispiel #9
0
    def manage_test(self, REQUEST):
        """Test an SQL method."""
        # Try to render the query template first so that the rendered
        # source will be available for the error message in case some
        # error occurs...
        try:
            src = self(REQUEST, src__=1)
        except Exception:
            src = 'Could not render the query template!'

        result = ()
        t = v = tb = None
        try:
            try:
                src, result = self(REQUEST, test__=1)
                if src.find('\0'):
                    src = ('\n' + '-' * 60 + '\n').join(src.split('\0'))
                if result._searchable_result_columns():
                    r = custom_default_report(self.id, result)
                else:
                    r = 'This statement returned no results.'
            except Exception:
                t, v, tb = sys.exc_info()
                r = '<strong>Error, <em>%s</em>:</strong> %s' % (t, v)

            report = HTML(
                '<html>\n'
                '<BODY BGCOLOR="#FFFFFF" LINK="#000099" VLINK="#555555">\n'
                '<dtml-var manage_tabs>\n<hr>\n%s\n\n'
                '<hr><strong>SQL used:</strong><br>\n<pre>\n%s\n</pre>\n<hr>\n'
                '</body></html>' % (r, html_quote(src)))

            report = report(*(self, REQUEST), **{self.id: result})

            if tb is not None:
                self.raise_standardErrorMessage(None, REQUEST, t, v, tb, None,
                                                report)

            return report

        finally:
            tb = None
Beispiel #10
0
    def manage_test(self, REQUEST):
        """Test an SQL method."""
        # Try to render the query template first so that the rendered
        # source will be available for the error message in case some
        # error occurs...
        try:
            src = self(REQUEST, src__=1)
        except:
            src = "Could not render the query template!"
        result = ()
        t = v = tb = None
        try:
            try:
                src, result = self(REQUEST, test__=1)
                if find(src, "\0"):
                    src = join(split(src, "\0"), "\n" + "-" * 60 + "\n")
                if result._searchable_result_columns():
                    r = custom_default_report(self.id, result)
                else:
                    r = "This statement returned no results."
            except:
                t, v, tb = sys.exc_info()
                r = "<strong>Error, <em>%s</em>:</strong> %s" % (t, v)

            report = DocumentTemplate.HTML(
                "<html>\n"
                '<BODY BGCOLOR="#FFFFFF" LINK="#000099" VLINK="#555555">\n'
                "<dtml-var manage_tabs>\n<hr>\n%s\n\n"
                "<hr><strong>SQL used:</strong><br>\n<pre>\n%s\n</pre>\n<hr>\n"
                "</body></html>" % (r, html_quote(src))
            )

            report = apply(report, (self, REQUEST), {self.id: result})

            if tb is not None:
                self.raise_standardErrorMessage(None, REQUEST, t, v, tb, None, report)

            return report

        finally:
            tb = None
def replaceInlineLatex(body, charheightpx, alignfudge, resfudge, latexTemplate=None):
    from latexWrapper import renderNonexistingImages

    renumbered   = re.compile(r'[ \t]*\\begin{ *(math|equation|eqnarray) *}')
    reunnumbered = re.compile(r'[ \t]*(\\begin{ *((math|equation|eqnarray)\*|table|tabular|displaymath|array|latex) *}|\\\[)')
    body = strip(body)
    latexCodeList = findLatexCode(body)
    newlatexCodeList = []
    eqnum = 0
    for code in latexCodeList:
        if code[0]=='!': 
# We need to identify if we're inside a '' block or an example:: block here.
            newcode = re.compile('^!', re.MULTILINE).sub('', code)
            # change the dollar sign so that the replace below does not hit
            # this code again (in the case of the same code appearing twice,
            # once escaped, once not)
            #newcode = re.compile('\$', re.MULTILINE).sub('&#36;', newcode, 2)
            # prevent stx from mangling asterisks
            #newcode = re.compile('\*', re.MULTILINE).sub('&#42;', newcode) 
            # and this will hide \(\), \[\], \begin...\end, including any
            # equations that may be hiding inside a \begin{latex}..\end{latex}
            newcode = re.compile(r'\\\[', re.MULTILINE).sub('\\![', newcode)
            #newcode = re.compile(r'\\', re.MULTILINE).sub('&#92;', newcode)
            body = replace(body, code, newcode, 1)
            continue
        else:
            newlatexCodeList.append(code)
        oldcode = code
        renummatch = renumbered.match(code)
        if renummatch:
            eqnum = eqnum + 1
            code = renumbered.sub('\\\\begin{\\1*}\n\\label{eq%d}' %(eqnum), code, 1)
            kind = renummatch.group(1)
            code = re.compile('\\\\end{ *%s *}' %(kind)).sub('\\\\end{%s*}' %(kind), code, 1)
            code = renumbered.sub('\\\\begin{\\1*}\n\\label{eq%d}' %(eqnum), code, 1)
# FIXME we really shouldn't do this...it will recreate block equations with different numbers.
            newlatexCodeList[newlatexCodeList.index(oldcode)] = code
# FIXME This will also replace any escaped code :(
            body = replace(body, oldcode, code, 1)
    errors = renderNonexistingImages(newlatexCodeList, charheightpx, alignfudge, resfudge,
                                     latexTemplate=latexTemplate)
    
    if not errors:
        for code in newlatexCodeList:
            labelmatch = re.compile('\\\\label{eq(\\d+)}').search(code, 1)
            commentedcode = re.compile('^', re.MULTILINE).sub('!', html_quote(code))
# "--" inside a comment screws up browsers.  But in LaTeX math mode "--" and "- -" are equivalent.
            commentedcode = re.compile('--', re.MULTILINE).sub('- -', commentedcode)
            if labelmatch:
                eqnum = labelmatch.group(1)
                imageTag = '<a name="eq%s">' %(eqnum)                                 \
                    + '<table width="100%"><tr><td align="center" width="95%">'       \
                    + getImageFor(code, charheightpx)                                 \
                    + '</td><td align="right">(%s)</td></tr></table></a>' %(eqnum)
            elif reunnumbered.match(code):
                imageTag = '<a name="unnumbered">'                                    \
                    + '<table width="100%"><tr><td align="center" width="95%">'       \
                    + getImageFor(code, charheightpx)                                 \
                    + '</td><td width="5%" align="right">&nbsp;</td></tr></table></a>'
            else:
                imageTag = getImageFor(code, charheightpx)
            body = replace(body, code, imageTag, 1)

# We try to match the > and < (or ^/$) from the preceeding and trailing tags,
# so as not to catch the alt="..." from a latex equation
# FIXME this is slow.  Use something like perl's m/\G/g to iterate over (n)
        for i in range(1,int(eqnum)+1):
            body = re.compile(r'((?:>|^)(?:[^<]*\s|))\( *(?:[Ee][Qq]\.)?\s*(%d) *\)([^>]*(?:<|$))' %(i)).sub(r'\1<a href="#eq\2">(\2)</a>\3', body)

    else:
        body = "<pre>" + body + "</pre>" + errorMessage %(errors)

    # Handle escaping of latex
    body = re.compile(r'(?<!\\)((?:\\\\)*)\\\$', re.MULTILINE).sub(r'\1$', body)
    body = re.compile(r'\\\\', re.MULTILINE).sub(r'\\', body)
    return body
Beispiel #12
0
    def raise_standardErrorMessage(self,
                                   client=None,
                                   REQUEST={},
                                   error_type=None,
                                   error_value=None,
                                   tb=None,
                                   error_tb=None,
                                   error_message='',
                                   tagSearch=re.compile(r'[a-zA-Z]>').search,
                                   error_log_url=''):

        try:
            if error_type is None: error_type = sys.exc_info()[0]
            if error_value is None: error_value = sys.exc_info()[1]

            # allow for a few different traceback options
            if tb is None and error_tb is None:
                tb = sys.exc_info()[2]
            if type(tb) is not str and (error_tb is None):
                error_tb = pretty_tb(error_type, error_value, tb)
            elif type(tb) is str and not error_tb:
                error_tb = tb

            if hasattr(self, '_v_eek'):
                # Stop if there is recursion.
                raise error_type, error_value, tb
            self._v_eek = 1

            if hasattr(error_type, '__name__'):
                error_name = error_type.__name__
            else:
                error_name = 'Unknown'

            if not error_message:
                try:
                    s = ustr(error_value)
                except:
                    s = error_value
                try:
                    match = tagSearch(s)
                except TypeError:
                    match = None
                if match is not None:
                    error_message = error_value

            if client is None:
                client = self

            if not REQUEST:
                REQUEST = aq_acquire(self, 'REQUEST')

            try:
                s = aq_acquire(client, 'standard_error_message')

                # For backward compatibility, we pass 'error_name' as
                # 'error_type' here as historically this has always
                # been a string.
                kwargs = {
                    'error_type': error_name,
                    'error_value': error_value,
                    'error_tb': error_tb,
                    'error_traceback': error_tb,
                    'error_message': xml_escape(str(error_message)),
                    'error_log_url': error_log_url
                }

                if getattr(aq_base(s), 'isDocTemp', 0):
                    v = s(client, REQUEST, **kwargs)
                elif callable(s):
                    v = s(**kwargs)
                else:
                    v = HTML.__call__(s, client, REQUEST, **kwargs)
            except:
                logger.error('Exception while rendering an error message',
                             exc_info=True)
                try:
                    strv = repr(error_value)  # quotes tainted strings
                except:
                    strv = ('<unprintable %s object>' %
                            str(type(error_value).__name__))
                v = strv + (
                    (" (Also, the following error occurred while attempting "
                     "to render the standard error message, please see the "
                     "event log for full details: %s)") %
                    (html_quote(sys.exc_info()[1]), ))

            # If we've been asked to handle errors, just return the rendered
            # exception and let the ZPublisher Exception Hook deal with it.
            return error_type, v, tb
        finally:
            if hasattr(self, '_v_eek'): del self._v_eek
            tb = None
Beispiel #13
0
    def raise_standardErrorMessage(
        self, client=None, REQUEST={},
        error_type=None, error_value=None, tb=None,
        error_tb=None, error_message='',
        tagSearch=re.compile(r'[a-zA-Z]>').search,
        error_log_url=''):

        try:
            if error_type  is None: error_type =sys.exc_info()[0]
            if error_value is None: error_value=sys.exc_info()[1]

            # allow for a few different traceback options
            if tb is None and error_tb is None:
                tb=sys.exc_info()[2]
            if type(tb) is not type('') and (error_tb is None):
                error_tb = pretty_tb(error_type, error_value, tb)
            elif type(tb) is type('') and not error_tb:
                error_tb = tb

            # turn error_type into a string
            if hasattr(error_type, '__name__'):
                error_type=error_type.__name__

            if hasattr(self, '_v_eek'):
                # Stop if there is recursion.
                raise error_type, error_value, tb
            self._v_eek=1

            if str(error_type).lower() in ('redirect',):
                raise error_type, error_value, tb

            if not error_message:
                try:
                    s = ustr(error_value)
                except:
                    s = error_value
                try:
                    match = tagSearch(s)
                except TypeError:
                    match = None
                if match is not None:
                    error_message=error_value

            if client is None: client=self
            if not REQUEST: REQUEST=self.aq_acquire('REQUEST')

            try:
                if hasattr(client, 'standard_error_message'):
                    s=getattr(client, 'standard_error_message')
                else:
                    client = client.aq_parent
                    s=getattr(client, 'standard_error_message')
                kwargs = {'error_type': error_type,
                          'error_value': error_value,
                          'error_tb': error_tb,
                          'error_traceback': error_tb,
                          'error_message': error_message,
                          'error_log_url': error_log_url}

                if getattr(aq_base(s),'isDocTemp',0):
                    v = s(client, REQUEST, **kwargs)
                elif callable(s):
                    v = s(**kwargs)
                else:
                    v = HTML.__call__(s, client, REQUEST, **kwargs)
            except:
                logger.error(
                    'Exception while rendering an error message',
                    exc_info=True
                    )
                try:
                    strv = repr(error_value) # quotes tainted strings
                except:
                    strv = ('<unprintable %s object>' %
                            str(type(error_value).__name__))
                v = strv + (
                    (" (Also, the following error occurred while attempting "
                     "to render the standard error message, please see the "
                     "event log for full details: %s)")%(
                    html_quote(sys.exc_info()[1]),
                    ))
            raise error_type, v, tb
        finally:
            if hasattr(self, '_v_eek'): del self._v_eek
            tb=None
Beispiel #14
0
    def raise_standardErrorMessage(
        self, client=None, REQUEST={},
        error_type=None, error_value=None, tb=None,
        error_tb=None, error_message='',
        tagSearch=re.compile(r'[a-zA-Z]>').search,
        error_log_url=''):

        try:
            if error_type  is None: error_type =sys.exc_info()[0]
            if error_value is None: error_value=sys.exc_info()[1]

            # allow for a few different traceback options
            if tb is None and error_tb is None:
                tb=sys.exc_info()[2]
            if type(tb) is not type('') and (error_tb is None):
                error_tb = pretty_tb(error_type, error_value, tb)
            elif type(tb) is type('') and not error_tb:
                error_tb = tb

            if hasattr(self, '_v_eek'):
                # Stop if there is recursion.
                raise error_type, error_value, tb
            self._v_eek = 1

            if hasattr(error_type, '__name__'):
                error_name = error_type.__name__
            else:
                error_name = 'Unknown'

            if not error_message:
                try:
                    s = ustr(error_value)
                except:
                    s = error_value
                try:
                    match = tagSearch(s)
                except TypeError:
                    match = None
                if match is not None:
                    error_message=error_value

            if client is None:
                client = self

            if not REQUEST:
                REQUEST = aq_acquire(self, 'REQUEST')

            try:
                s = aq_acquire(client, 'standard_error_message')

                # For backward compatibility, we pass 'error_name' as
                # 'error_type' here as historically this has always
                # been a string.
                kwargs = {'error_type': error_name,
                          'error_value': error_value,
                          'error_tb': error_tb,
                          'error_traceback': error_tb,
                          'error_message': error_message,
                          'error_log_url': error_log_url}

                if getattr(aq_base(s), 'isDocTemp', 0):
                    v = s(client, REQUEST, **kwargs)
                elif callable(s):
                    v = s(**kwargs)
                else:
                    v = HTML.__call__(s, client, REQUEST, **kwargs)
            except:
                logger.error(
                    'Exception while rendering an error message',
                    exc_info=True
                    )
                try:
                    strv = repr(error_value) # quotes tainted strings
                except:
                    strv = ('<unprintable %s object>' % 
                            str(type(error_value).__name__))
                v = strv + (
                    (" (Also, the following error occurred while attempting "
                     "to render the standard error message, please see the "
                     "event log for full details: %s)")%(
                    html_quote(sys.exc_info()[1]),
                    ))

            # If we've been asked to handle errors, just return the rendered
            # exception and let the ZPublisher Exception Hook deal with it.
            return error_type, v, tb
        finally:
            if hasattr(self, '_v_eek'): del self._v_eek
            tb = None
Beispiel #15
0
    def raise_standardErrorMessage(self,
                                   client=None,
                                   REQUEST={},
                                   error_type=None,
                                   error_value=None,
                                   tb=None,
                                   error_tb=None,
                                   error_message='',
                                   tagSearch=re.compile(r'[a-zA-Z]>').search,
                                   error_log_url=''):

        try:
            if error_type is None: error_type = sys.exc_info()[0]
            if error_value is None: error_value = sys.exc_info()[1]

            # allow for a few different traceback options
            if tb is None and error_tb is None:
                tb = sys.exc_info()[2]
            if type(tb) is not type('') and (error_tb is None):
                error_tb = pretty_tb(error_type, error_value, tb)
            elif type(tb) is type('') and not error_tb:
                error_tb = tb

            # turn error_type into a string
            if hasattr(error_type, '__name__'):
                error_type = error_type.__name__

            if hasattr(self, '_v_eek'):
                # Stop if there is recursion.
                raise error_type, error_value, tb
            self._v_eek = 1

            if str(error_type).lower() in ('redirect', ):
                raise error_type, error_value, tb

            if not error_message:
                try:
                    s = ustr(error_value)
                except:
                    s = error_value
                try:
                    match = tagSearch(s)
                except TypeError:
                    match = None
                if match is not None:
                    error_message = error_value

            if client is None: client = self
            if not REQUEST: REQUEST = self.aq_acquire('REQUEST')

            try:
                if hasattr(client, 'standard_error_message'):
                    s = getattr(client, 'standard_error_message')
                else:
                    client = client.aq_parent
                    s = getattr(client, 'standard_error_message')
                kwargs = {
                    'error_type': error_type,
                    'error_value': error_value,
                    'error_tb': error_tb,
                    'error_traceback': error_tb,
                    'error_message': error_message,
                    'error_log_url': error_log_url
                }

                if getattr(aq_base(s), 'isDocTemp', 0):
                    v = s(client, REQUEST, **kwargs)
                elif callable(s):
                    v = s(**kwargs)
                else:
                    v = HTML.__call__(s, client, REQUEST, **kwargs)
            except:
                logger.error('Exception while rendering an error message',
                             exc_info=True)
                try:
                    strv = str(error_value)
                except:
                    strv = ('<unprintable %s object>' %
                            str(type(error_value).__name__))
                v = strv + (
                    (" (Also, the following error occurred while attempting "
                     "to render the standard error message, please see the "
                     "event log for full details: %s)") %
                    (html_quote(sys.exc_info()[1]), ))
            raise error_type, v, tb
        finally:
            if hasattr(self, '_v_eek'): del self._v_eek
            tb = None
def render_blocks_(blocks, rendered, md, encoding):
    for block in blocks:
        append = True

        if (isinstance(block, tuple) and
                len(block) > 1 and
                isinstance(block[0], six.string_types)):

            first_char = block[0][0]
            if first_char == 'v':  # var
                t = block[1]
                if isinstance(t, six.string_types):
                    t = md[t]
                else:
                    t = t(md)

                skip_html_quote = 0
                if not isinstance(t, (six.string_types, six.binary_type)):
                    # This might be a TaintedString object
                    untaintmethod = getattr(t, '__untaint__', None)
                    if untaintmethod is not None:
                        # Quote it
                        t = untaintmethod()
                        skip_html_quote = 1

                if not isinstance(t, (six.string_types, six.binary_type)):
                    t = ustr(t)

                if (skip_html_quote == 0 and len(block) == 3):
                    # html_quote
                    if isinstance(t, str):
                        if ('&' in t or '<' in t or '>' in t or '"' in t):
                            # string includes html problem characters,
                            # so we cant skip the quoting process
                            skip_html_quote = 0
                        else:
                            skip_html_quote = 1
                    else:
                        # never skip the quoting for unicode strings
                        skip_html_quote = 0

                    if not skip_html_quote:
                        t = html_quote(t, encoding=encoding)

                block = t

            elif first_char == 'i':  # if
                bs = len(block) - 1  # subtract code
                cache = {}
                md._push(cache)
                try:
                    append = False
                    m = bs - 1
                    icond = 0
                    while icond < m:
                        cond = block[icond + 1]
                        if isinstance(cond, str):
                            # We have to be careful to handle key errors here
                            n = cond
                            try:
                                cond = md[cond]
                            except KeyError as t:
                                if n != t.args[0]:
                                    raise
                                cond = None
                            else:
                                cache[n] = cond
                        else:
                            cond = cond(md)

                        if cond:
                            block = block[icond + 2]
                            if block:
                                render_blocks_(block, rendered, md, encoding)
                            m = -1
                            break

                        icond += 2

                    if icond == m:
                        block = block[icond + 1]
                        if block:
                            render_blocks_(block, rendered, md, encoding)
                finally:
                    md._pop()

            else:
                raise ValueError(
                    'Invalid DTML command code, %s', block[0])

        elif not isinstance(block, (six.string_types, six.binary_type)):
            block = block(md)

        if append and block:
            rendered.append(block)
Beispiel #17
0
    def tag(
        self,
        preview=0,
        icon=0,
        height=None,
        width=None,
        alt=None,
        scale=0,
        xscale=0,
        yscale=0,
        border="0",
        REQUEST=None,
        title=None,
        css_class=None,
        **args
    ):
        """ Generate an HTML IMG tag for this image, with customization.
            Arguments to self.tag() can be any valid attributes of an IMG tag.
            'src' will always be an absolute pathname, to prevent redundant
            downloading of images. Defaults are applied intelligently for
            'height', 'width', and 'alt'. If specified, the 'scale', 'xscale',
            and 'yscale' keyword arguments will be used to automatically adjust
            the output height and width values of the image tag.
            Adopted and adapted from OFS/Image.py
        """
        if not self.is_webviewable():
            preview = 1
        if not self._access_permitted():
            preview = 1
        if preview and not self.has_preview:
            icon = 1
        if icon:
            url = self._static_url(icon=1)
            img_width, img_height = (32, 32)
        elif preview:
            url = self._static_url(preview=1)
            img_width, img_height = self._getImageSize(self.prev_filename)
        else:
            url = self._static_url()
            img_width, img_height = self._getImageSize(self.filename)
        height = height or img_height
        width = width or img_width

        # Auto-scaling support
        xdelta = xscale or scale
        ydelta = yscale or scale
        if xdelta and width != None:
            width = str(int(int(width) * xdelta))
        if ydelta and height != None:
            height = str(int(int(height) * ydelta))

        result = '<img src="%s"' % (url,)
        if alt is None:
            alt = getattr(self, "alt", "")
        result = '%s alt="%s"' % (result, html_quote(alt))
        if title is None:
            title = getattr(self, "title", "")
        result = '%s title="%s"' % (result, html_quote(title))
        if height:
            result = '%s height="%s"' % (result, height)
        if width:
            result = '%s width="%s"' % (result, width)
        # Omitting 'border' attribute (Collector #1557)
        if css_class is not None:
            result = '%s class="%s"' % (result, css_class)
        for key in args.keys():
            value = args.get(key)
            if value:
                result = '%s %s="%s"' % (result, key, value)
        return "%s />" % result
Beispiel #18
0
def render_blocks_(blocks, rendered, md, encoding):
    for block in blocks:
        append = True

        if (isinstance(block, tuple) and len(block) > 1
                and isinstance(block[0], six.string_types)):

            first_char = block[0][0]
            if first_char == 'v':  # var
                t = block[1]
                if isinstance(t, six.string_types):
                    t = md[t]
                else:
                    t = t(md)

                skip_html_quote = 0
                if not isinstance(t, (six.string_types, six.binary_type)):
                    # This might be a TaintedString object
                    untaintmethod = getattr(t, '__untaint__', None)
                    if untaintmethod is not None:
                        # Quote it
                        t = untaintmethod()
                        skip_html_quote = 1

                if not isinstance(t, (six.string_types, six.binary_type)):
                    t = ustr(t)

                if (skip_html_quote == 0 and len(block) == 3):
                    # html_quote
                    if isinstance(t, str):
                        if ('&' in t or '<' in t or '>' in t or '"' in t):
                            # string includes html problem characters,
                            # so we cant skip the quoting process
                            skip_html_quote = 0
                        else:
                            skip_html_quote = 1
                    else:
                        # never skip the quoting for unicode strings
                        skip_html_quote = 0

                    if not skip_html_quote:
                        t = html_quote(t, encoding=encoding)

                block = t

            elif first_char == 'i':  # if
                bs = len(block) - 1  # subtract code
                cache = {}
                md._push(cache)
                try:
                    append = False
                    m = bs - 1
                    icond = 0
                    while icond < m:
                        cond = block[icond + 1]
                        if isinstance(cond, str):
                            # We have to be careful to handle key errors here
                            n = cond
                            try:
                                cond = md[cond]
                            except KeyError as t:
                                if n != t.args[0]:
                                    raise
                                cond = None
                            else:
                                cache[n] = cond
                        else:
                            cond = cond(md)

                        if cond:
                            block = block[icond + 2]
                            if block:
                                render_blocks_(block, rendered, md, encoding)
                            m = -1
                            break

                        icond += 2

                    if icond == m:
                        block = block[icond + 1]
                        if block:
                            render_blocks_(block, rendered, md, encoding)
                finally:
                    md._pop()

            else:
                raise ValueError('Invalid DTML command code, %s', block[0])

        elif not isinstance(block, (six.string_types, six.binary_type)):
            block = block(md)

        if append and block:
            rendered.append(block)