Exemple #1
0
    def manage_doCustomize(self, folder_path, RESPONSE=None):
        """Makes a ZODB Based clone with the same data.

        Calls _createZODBClone for the actual work.
        """

        obj = self._createZODBClone()
        
        id = obj.getId()
        fpath = tuple(split(folder_path, '/'))
        portal_skins = getToolByName(self,'portal_skins') 
        folder = portal_skins.restrictedTraverse(fpath)

        if id in folder.objectIds():
            # we cant catch the badrequest so
            # we'll that to check before hand, which makes
            # sense anyway...
            obj = folder._getOb(id)
            if RESPONSE is not None:
                RESPONSE.redirect('%s/manage_main?manage_tabs_message=%s' % (
                    obj.absolute_url(), html_quote("An object with this id already exists")
                    ))
        else:
            folder._verifyObjectPaste(obj, validate_src=0)
            folder._setObject(id, obj)

            if RESPONSE is not None:
                RESPONSE.redirect('%s/%s/manage_main' % (
                folder.absolute_url(), id))
Exemple #2
0
    def write_results(self, results):
        self.write('''<ul class="LSTable">''')
        for result in results[:self.limit]:
            icon = self.getIcon(result)
            itemUrl = result.getURL()
            if result.portal_type in self.useViewAction:
                itemUrl += '/view'
            itemUrl = itemUrl + self.searchterm_query

            self.write('''<li class="LSRow">''')
            self.write(icon.html_tag() or '')
            full_title = safe_unicode(self.pretty_title_or_id(result))
            if len(full_title) > self.settings.max_title:
                display_title = ''.join((full_title[:self.settings.max_title], '...'))
            else:
                display_title = full_title
            full_title = full_title.replace('"', '&quot;')
            klass = 'contenttype-%s' % self.normalizeString(result.portal_type)
            self.write('''<a href="%s" title="%s" class="%s">%s</a>''' % (itemUrl, full_title, klass, display_title))
            display_description = safe_unicode(result.Description)
            if len(display_description) > self.settings.max_description:
                display_description = ''.join((display_description[:self.settings.max_description], '...'))
            # need to quote it, to avoid injection of html containing javascript and other evil stuff
            display_description = html_quote(display_description)
            self.write('''<div class="LSDescr">%s</div>''' % (display_description))
            self.write('''</li>''')
            full_title, display_title, display_description = None, None, None

        if len(results) > self.limit:
            # add a more... row
            self.write('''<li class="LSRow">''')
            self.write(self.get_show_more_link())
            self.write('''</li>''')
        self.write('''</ul>''')
Exemple #3
0
    def manage_doCustomize(self, folder_path, RESPONSE=None):
        """Makes a ZODB Based clone with the same data.

        Calls _createZODBClone for the actual work.
        """

        obj = self._createZODBClone()
        parent = aq_parent(aq_inner(self))

        # Preserve cache manager associations
        cachemgr_id = self.ZCacheable_getManagerId()
        if ( cachemgr_id and
             getattr(obj, 'ZCacheable_setManagerId', None) is not None ):
            obj.ZCacheable_setManagerId(cachemgr_id)

        # If there are proxy roles we preserve them
        proxy_roles = getattr(aq_base(self), '_proxy_roles', None)
        if proxy_roles is not None and isinstance(proxy_roles, tuple):
            obj._proxy_roles = tuple(self._proxy_roles)

        # Also, preserve any permission settings that might have come
        # from a metadata file or from fiddling in the ZMI
        old_info = [x[:2] for x in self.ac_inherited_permissions(1)]
        for old_perm, value in old_info:
            p = Permission(old_perm, value, self)
            acquired = int(isinstance(p.getRoles(default=[]), list))
            rop_info = self.rolesOfPermission(old_perm)
            roles = [x['name'] for x in rop_info if x['selected'] != '']
            try:
                # if obj is based on OFS.ObjectManager an acquisition context is
                # required for _subobject_permissions()
                obj.__of__(parent).manage_permission(old_perm, roles=roles,
                                                     acquire=acquired)
            except ValueError:
                # The permission was invalid, never mind
                pass

        id = obj.getId()
        fpath = tuple( folder_path.split('/') )
        portal_skins = getUtility(ISkinsTool)
        folder = portal_skins.restrictedTraverse(fpath)
        if id in folder.objectIds():
            # we cant catch the badrequest so
            # we'll that to check before hand
            obj = folder._getOb(id)
            if RESPONSE is not None:
                RESPONSE.redirect('%s/manage_main?manage_tabs_message=%s' % (
                    obj.absolute_url(), html_quote("An object with this id already exists")
                    ))
        else:
            folder._verifyObjectPaste(obj, validate_src=0)
            folder._setObject(id, obj)

            if RESPONSE is not None:
                RESPONSE.redirect('%s/%s/manage_main' % (
                folder.absolute_url(), id))

        if RESPONSE is not None:
            RESPONSE.redirect('%s/%s/manage_main' % (
                folder.absolute_url(), id))
Exemple #4
0
    def exttag(self, prefix, display=None, height=None, width=None, cookie=0,
               alt=None, css_class=None, **kw):
        """Return HTML img tag for serving outside Zope."""

        # Get cookie if display is not specified.
        if display is None:
            display = self.REQUEST.cookies.get('display', None)

        # display may be set from a cookie.
        if display is not None and self._displays.has_key(display):
            if not self._isGenerated(display):
                # Generate photo on-the-fly
                self._makeDisplayPhoto(display, 1)
            image = self._photos[display]
            width, height = (image._width(), image._height())
            # Set cookie for chosen size
            if cookie:
                self.REQUEST.RESPONSE.setCookie('display', display, path="/")

        if prefix[-1] != '/':
            prefix = prefix + '/'

        if display:
            
            filename = self._photos[display].filename
        else:
            filename = self._original.filename

        if type(filename) == type([]):
            filename = prefix + string.join(filename, '/')
        else:
            filename = prefix + filename

        result = '<img src="%s"' % (filename)

        if alt is None:
            alt = getattr(self, 'title', '')
        if alt == '':
            alt = self.getId()
        result = '%s alt="%s"' % (result, html_quote(alt))

        if height:
            result = '%s height="%s"' % (result, height)

        if width:
            result = '%s width="%s"' % (result, width)

        if not 'border' in map(string.lower, kw.keys()):
            result = '%s border="0"' % (result)

        if css_class is not None:
            result = '%s class="%s"' % (result, css_class)

        for key in kw.keys():
            value = kw.get(key)
            result = '%s %s="%s"' % (result, key, value)

        result = '%s />' % (result)

        return result
 def _trasform_value(self, field, value):
     if field.meta_type == "DateTimeField":
         format = "%Y-%m-%d %X"
         if value.hour() + value.minute() == 0:
             format = "%Y-%m-%d"
         return makeUnicode(value.strftime(format))
     elif field.meta_type in numerical:
         return value
     elif field.meta_type == "CheckBoxField":
         return value
     elif field.meta_type == "MultiCheckBoxField":
         return u", ".join([html_quote(makeUnicode(item)) for item in value])
     else:
         if type(value) == type([]):
             return u", ".join([html_quote(makeUnicode(item)) for item in value])
         else:
             return html_quote(makeUnicode(value))
     return value
 def _prepare_feed(self, s):
     """ prepare the text for XML usage """
     _replace = _replace_special_chars
     s = html_quote(s)
     return s
     s = s.replace('\xa3','&#163;')
     if _replace is not None:
         s = _replace(s, html_encoding=1)
     s = s.replace('&','&amp;')
     return s
Exemple #7
0
    def tag(self, display=None, height=None, width=None, cookie=0,
            alt=None, css_class=None, **kw):
        """Return HTML img tag."""

        # Get cookie if display is not specified.
        if display is None:
            display = self.REQUEST.cookies.get('display', None)

        # display may be set from a cookie.
        if display is not None and self._displays.has_key(display):
            if not self._isGenerated(display):
                # Generate photo on-the-fly
                self._makeDisplayPhoto(display, 1)
            image = self._photos[display]
            width, height = (image._width(), image._height())
            # Set cookie for chosen size
            if cookie:
                self.REQUEST.RESPONSE.setCookie('display', display, path="/")
        else:
            # TODO: Add support for on-the-fly resize?
            height = self._original._height()
            width = self._original._width()
            
        if display:
            result = '<img src="%s?display=%s"' % (self.absolute_url(), display)
        else:
            result = '<img src="%s"' % (self.absolute_url())

        if alt is None:
            alt = getattr(self, 'title', '')
        if alt == '':
            alt = self.getId()
        result = '%s alt="%s"' % (result, html_quote(alt))

        if height:
            result = '%s height="%s"' % (result, height)

        if width:
            result = '%s width="%s"' % (result, width)

        if not 'border' in map(string.lower, kw.keys()):
            result = '%s border="0"' % (result)

        if css_class is not None:
            result = '%s class="%s"' % (result, css_class)

        for key in kw.keys():
            value = kw.get(key)
            result = '%s %s="%s"' % (result, key, value)

        result = '%s />' % (result)

        return result
 def getViewFor(self, instance, idx, subfield, joinWith=', '):
     """
     formatted value of the subfield for display
     """
     raw = self.getRaw(instance)[idx].get(subfield,'')
     if type(raw) in (type(()), type([])):
         raw = joinWith.join(raw)
     # Prevent XSS attacks by quoting all user input
     raw = html_quote(str(raw))
     # this is now very specific
     if subfield == 'email':
         return self.hideEmail(raw,instance)
     if subfield == 'homepage':
         return '<a href="%s">%s</a>' % (raw, raw)
     return raw.strip()
Exemple #9
0
    def _niceSourceFormat(self, code):
        if SC_XML is not None:
            generator = SC_XML.XMLHTMLGenerator()
            file = StringIO.StringIO()
            generator.generate_html(file, code)
            code = file.getvalue()
            file.close()
            del generator
            css = '<style type="text/css">%s</style>\n\n'%SC_stylesheet
            code = '<div class="code_default">%s</div>'%code
            return css + code

        else:
            code = html_quote(code)
            code = newline_to_br(code)
            code = code.replace('\t','&nbsp;'*4)
            return "<code>%s</code>"%code
Exemple #10
0
    def test_allMetaTypes(self):
        """
        Test that everything returned by allMetaTypes can be
        traversed to.
        """
        tool = self.ttool
        meta_types = {}
        # Seems we get NullResource if the method couldn't be traverse to
        # so we check for that. If we've got it, something is b0rked.
        for factype in tool.all_meta_types():
            meta_types[factype['name']] = 1
            # The html_quote below is necessary 'cos of the one in
            # main.dtml. Could be removed once that is gone.
            act = tool.unrestrictedTraverse(html_quote(factype['action']))
            self.failIf(type(aq_base(act)) is NullResource)

        # Check the ones we're expecting are there
        self.failUnless(meta_types.has_key('Scriptable Type Information'))
        self.failUnless(meta_types.has_key('Factory-based Type Information'))
 def getViewFor(self, instance, subfield, joinWith=', '):
     """
     formatted value of the subfield for display
     """
     raw = self.getRaw(instance).get(subfield, '')
     if type(raw) in (type(()), type([])):
         raw = joinWith.join(raw)
     # Prevent XSS attacks by quoting all user input
     raw = html_quote(str(raw))
     # this is now very specific
     if subfield == 'email':
         return self.hideEmail(raw, instance)
     if subfield == 'phone':
         return self.labelPhone(raw)
     if subfield == 'fax':
         return self.labelFax(raw)
     if subfield == 'homepage':
         return '<a href="%s">%s</a>' % (raw, raw)
     return raw
Exemple #12
0
    def test_allMetaTypes(self):
        """
        Test that everything returned by allMetaTypes can be
        traversed to.
        """
        tool = self.ttool
        meta_types={}
        # Seems we get NullResource if the method couldn't be traverse to
        # so we check for that. If we've got it, something is b0rked.
        for factype in tool.all_meta_types():
            meta_types[factype['name']]=1
            # The html_quote below is necessary 'cos of the one in
            # main.dtml. Could be removed once that is gone.
            act = tool.unrestrictedTraverse(html_quote(factype['action']))
            self.failIf(type(aq_base(act)) is NullResource)

        # Check the ones we're expecting are there
        self.failUnless(meta_types.has_key('Scriptable Type Information'))
        self.failUnless(meta_types.has_key('Factory-based Type Information'))
Exemple #13
0
    def test_allMetaTypes(self):
        # everything returned by allMetaTypes can be traversed to.
        from Acquisition import aq_base
        from Products.PythonScripts.standard import html_quote
        from webdav.NullResource import NullResource
        site = self._makeSite().__of__(self.root)
        tool = self._makeOne().__of__(site)
        meta_types = {}
        # Seems we get NullResource if the method couldn't be traverse to
        # so we check for that. If we've got it, something is b0rked.
        for factype in tool.all_meta_types():
            meta_types[factype['name']]=1
            # The html_quote below is necessary 'cos of the one in
            # main.dtml. Could be removed once that is gone.
            act = tool.unrestrictedTraverse(html_quote(factype['action']))
            self.failIf(type(aq_base(act)) is NullResource)

        # Check the ones we're expecting are there
        self.failUnless(meta_types.has_key('Scriptable Type Information'))
        self.failUnless(meta_types.has_key('Factory-based Type Information'))
Exemple #14
0
    def test_allMetaTypes(self):
        # everything returned by allMetaTypes can be traversed to.
        from Acquisition import aq_base
        from Products.PythonScripts.standard import html_quote
        from webdav.NullResource import NullResource
        site = self._makeSite().__of__(self.root)
        tool = self._makeOne().__of__(site)
        meta_types = {}
        # Seems we get NullResource if the method couldn't be traverse to
        # so we check for that. If we've got it, something is b0rked.
        for factype in tool.all_meta_types():
            meta_types[factype['name']]=1
            # The html_quote below is necessary 'cos of the one in
            # main.dtml. Could be removed once that is gone.
            act = tool.unrestrictedTraverse(html_quote(factype['action']))
            self.failIf(type(aq_base(act)) is NullResource)

        # Check the ones we're expecting are there
        self.failUnless(meta_types.has_key('Scriptable Type Information'))
        self.failUnless(meta_types.has_key('Factory-based Type Information'))
Exemple #15
0
    def write_grouped_results(self, grouped_results, group_by_types):
        show_more = False
        self.write('''<dl class="LSTable">''')
        for ptype in group_by_types:
            results = grouped_results[ptype]
            if results:
                self.write('''<dt class="LSGroup">%s</dt>''' % translate(ptype, domain="plone", context=self.request))
                for result in results[:self.settings.group_limit]:
                    icon = self.getIcon(result)
                    itemUrl = result.getURL()
                    if result.portal_type in self.useViewAction:
                        itemUrl += '/view'
                    itemUrl = itemUrl + self.searchterm_query

                    self.write('''<dd class="LSRow">''')
                    self.write(icon.html_tag() or '')
                    full_title = safe_unicode(self.pretty_title_or_id(result))
                    if len(full_title) > self.settings.max_title:
                        display_title = ''.join((full_title[:self.settings.max_title], '...'))
                    else:
                        display_title = full_title
                    full_title = full_title.replace('"', '&quot;')
                    klass = 'contenttype-%s' % self.normalizeString(result.portal_type)
                    self.write('''<a href="%s" title="%s" class="%s">%s</a>''' % (itemUrl, full_title, klass, display_title))
                    display_description = safe_unicode(result.Description)
                    if len(display_description) > self.settings.max_description:
                        display_description = ''.join((display_description[:self.settings.max_description], '...'))
                    # need to quote it, to avoid injection of html containing javascript and other evil stuff
                    display_description = html_quote(display_description)
                    self.write('''<div class="LSDescr">%s</div>''' % (display_description))
                    self.write('''</dd>''')
                if len(results) > self.settings.group_limit:
                    show_more = True

        if show_more:
            # add a more... row
            self.write('''<dd class="LSRow LSShowMore">''')
            self.write(self.get_show_more_link())
            self.write('''</dd>''')

        self.write('''</dl>''')
Exemple #16
0
    def showNameAndEmail(self):
        """ return an html version of name and email """
        name = self.getName()
        email = self.getEmail()
        hide_email = self.hideEmail()

        if name != '' and email != '':
            if hide_email:
                return html_quote(name)
            else:
                return self.encodeEmailString(email, name)
        elif name != '':
            return name
            #return html_quote(name)
        elif email != '':
            if hide_email:
                return "<em>Email hidden</em>"
            else:
                return self.encodeEmailString(email)
        else:
            return "<em>Anonymous</em>"
Exemple #17
0
    def showNameAndEmail(self):
        """ return an html version of name and email """
        name = self.getName()
        email = self.getEmail()
        hide_email = self.hideEmail()

        if name != '' and email != '':
            if hide_email:
                return html_quote(name)
            else:
                return self.encodeEmailString(email, name)
        elif name != '':
            return name
            #return html_quote(name)
        elif email != '':
            if hide_email:
                return "<em>Email hidden</em>"
            else:
                return self.encodeEmailString(email)
        else:
            return "<em>Anonymous</em>"
Exemple #18
0
    def write_results(self, results):
        self.write('''<ul class="LSTable">''')
        for result in results[:self.limit]:
            icon = self.getIcon(result)
            itemUrl = result.getURL()
            if result.portal_type in self.useViewAction:
                itemUrl += '/view'
            itemUrl = itemUrl + self.searchterm_query

            self.write('''<li class="LSRow">''')
            self.write(icon.html_tag() or '')
            full_title = safe_unicode(self.pretty_title_or_id(result))
            if len(full_title) > self.settings.max_title:
                display_title = ''.join(
                    (full_title[:self.settings.max_title], '...'))
            else:
                display_title = full_title
            full_title = full_title.replace('"', '&quot;')
            klass = 'contenttype-%s' % self.normalizeString(result.portal_type)
            self.write('''<a href="%s" title="%s" class="%s">%s</a>''' %
                       (itemUrl, full_title, klass, display_title))
            display_description = safe_unicode(result.Description)
            if len(display_description) > self.settings.max_description:
                display_description = ''.join(
                    (display_description[:self.settings.max_description],
                     '...'))
            # need to quote it, to avoid injection of html containing javascript and other evil stuff
            display_description = html_quote(display_description)
            self.write('''<div class="LSDescr">%s</div>''' %
                       (display_description))
            self.write('''</li>''')
            full_title, display_title, display_description = None, None, None

        if len(results) > self.limit:
            # add a more... row
            self.write('''<li class="LSRow">''')
            self.write(self.get_show_more_link())
            self.write('''</li>''')
        self.write('''</ul>''')
Exemple #19
0
    def manage_doCustomize(self, folder_path, RESPONSE=None):
        """Makes a ZODB Based clone with the same data.

        Calls _createZODBClone for the actual work.
        """

        obj = self._createZODBClone()

        # Preserve cache manager associations
        cachemgr_id = self.ZCacheable_getManagerId()
        if (cachemgr_id
                and getattr(obj, 'ZCacheable_setManagerId', None) is not None):
            obj.ZCacheable_setManagerId(cachemgr_id)

        id = obj.getId()
        fpath = tuple(folder_path.split('/'))
        portal_skins = getToolByName(self, 'portal_skins')
        folder = portal_skins.restrictedTraverse(fpath)
        if id in folder.objectIds():
            # we cant catch the badrequest so
            # we'll that to check before hand
            obj = folder._getOb(id)
            if RESPONSE is not None:
                RESPONSE.redirect(
                    '%s/manage_main?manage_tabs_message=%s' %
                    (obj.absolute_url(),
                     html_quote("An object with this id already exists")))
        else:
            folder._verifyObjectPaste(obj, validate_src=0)
            folder._setObject(id, obj)

            if RESPONSE is not None:
                RESPONSE.redirect('%s/%s/manage_main' %
                                  (folder.absolute_url(), id))

        if RESPONSE is not None:
            RESPONSE.redirect('%s/%s/manage_main' %
                              (folder.absolute_url(), id))
Exemple #20
0
def ShowDescription(text, display_format=''):
    """
    Display text, using harmless HTML
    """

    if display_format == 'structuredtext':
        #st=_replace_special_chars(text)
        st=text

        for k,v in {'<':'&lt;', '>':'&gt;',
                    '[':'|[|'}.items():
            st = st.replace(k,v)

        st = html_entity_fixer(st, skipchars=('"',))

        st = structured_text(st)
        

        for k,v in {'&amp;lt;':'&lt;', '&amp;gt;':'&gt;',
                    '|[|':'['}.items():
            st = st.replace(k,v)

        # BUG in structured_text in Zope 2.4.0
        # it appends these annoying tags.
        #for tag in ['<html>','<body>','</body>','</html>']:
        #    st = st.replace(tag, '')
        
        st = addhrefs(st)
        return st
    elif display_format == 'html':
        return text
    else:
        t = '<p>%s</p>'%html_quote(text)
        t = t.replace('&amp;lt;','&lt;').replace('&amp;gt;','&gt;')
        t = addhrefs(t)
        t = newline_to_br(t)
        return t
Exemple #21
0
doc_localiser = doc.getPortalObject().Localizer
doc_rendering_fix = doc.WebPage_getPdfOutputRenderingFix() or blank
doc_report = getattr(doc, doc_report_name)
doc_aggregate_list = []
doc_revision = "1"
doc_modification_date = DateTime()
doc_language = doc.getLanguage() if getattr(doc, 'getLanguage', None) else None
doc_translated_title = translateText(
    doc_report_title) if doc_report_title else blank

# fallback in case language is still None
if doc_language is None or doc_language == "":
    doc_language = doc_localiser.get_selected_language(
    ) or doc_localiser.get_default_language() or "en"

doc_language = html_quote(
    override_document_language) if override_document_language else doc_language

if doc_language is not None:
    doc.REQUEST['AcceptLanguage'].set(doc_language, 10)
else:
    doc_language = blank

# custom header
doc_header = None
doc_report_header = kw.get('report_header', None)
if doc_report_header:
    doc_report_header = getattr(doc, doc_report_header)
    doc_header = doc_report_header(language=doc_language)

doc_footer = None
doc_report_footer = kw.get('report_footer', None)
if leaflet_language and leaflet_language != blank:
    leaflet.REQUEST['AcceptLanguage'].set(leaflet_language, 10)
else:
    leaflet_language = blank
if leaflet_reference is None:
    leaflet_reference = leaflet_prefix + leaflet_title.replace(" ", ".")
leaflet_full_reference = '-'.join(
    [leaflet_reference, leaflet_version, leaflet_language])

# ---------------------------- Theme Parameters --------------------------------
leaflet_theme = leaflet.Base_getThemeDict(doc_format=leaflet_format,
                                          css_path="template_css/leaflet",
                                          skin="Leaflet")

if override_leaflet_header_title and override_leaflet_header_title != blank:
    leaflet_theme["theme_logo_description"] = html_quote(
        override_leaflet_header_title)
if leaflet_theme.get("theme").lower() == leaflet_theme.get(
        "theme_logo_description").lower():
    leaflet_theme["theme_logo_description"] = blank
leaflet_recycle_url = "template_images/recycle.png"
leaflet_css = ''.join([
    'html .ci-leaflet #left-summary:before {',
    'background: url("%s") center no-repeat;' %
    (leaflet_theme.get("theme_logo_url")), 'background-size: contain;', '}'
])

# ---------------------------------- Source ------------------------------------
leaflet_source = leaflet.Base_getSourceDict(
    override_source_person_title=override_source_person_title,
    override_source_organisation_title=override_source_organisation_title,
    theme_logo_url=leaflet_theme.get("theme_logo_url", None))
Exemple #23
0
import re
from Products.PythonScripts.standard import html_quote

document = context
document_content = content
websection = document.getWebSectionValue()
document_url = html_quote(websection.getPermanentURL(context))

# table of content
# XXX we are back to adding TOC to all documents, which we don't want
# XXX fix this to be applied only if a page is viewed as chapter
document_header_list = re.findall("<h[1-6].*?</h[1-6]>", document_content
                                  or "")

if len(document_header_list) > 0:
    header_current = 1
    header_initial = None
    table_of_content = ''

    for header in document_header_list:
        header_level = header[2]
        header_initial = header_initial or header_level
        header_reference = re.findall(">(.*)<", header)[0]
        header_lowercase = header_reference.lower()
        header_reference_prefix = header_lowercase.replace(" ", "-")

        if header_level == header_current:
            table_of_content += '</li>'

        # start of a list
        if header_level > header_current:
Exemple #24
0
 def utHtmlEncode(self, p_string):
     """Encode a string using html_quote"""
     return html_quote(p_string)
Exemple #25
0
# Example code:

# Import a standard function, and get the HTML request and response objects.
from Products.PythonScripts.standard import html_quote
request = container.REQUEST
RESPONSE = request.RESPONSE

# Return a string identifying this script.
print "This is the", script.meta_type, '"%s"' % script.getId(),
if script.title:
    print "(%s)" % html_quote(script.title),
print "in", container.absolute_url()
return printed
from Products.PythonScripts.standard import html_quote

result = ''
error_message = None
try:
    result = context.asStrippedHTML()
    if result:
        return result
    if not context.hasBaseData():
        error_message = context.Base_translateString(
            "This document is not converted yet.")
except Exception, e:
    from Products.ERP5Type.Log import log
    log("asStrippedHTML", str(e))
    error_message = "%s %s" % (context.Base_translateString("Preview Error:"),
                               str(e))

if error_message is not None:
    return '<div class="error">%s</div>' % html_quote(error_message)

return result
        report_item_list.append(
            (attachment.get('title',
                            document.getStandardFilename(format=format)),
             document.getRelativeUrl()))
        # pre-convert document before sending notification
        if format:
            document.activate(tag=pre_convert_tag).convert(format=format)

    url_base = portal.ERP5Site_getAbsoluteUrl()
    attachment_link_list = [{
        'download_link':
        '%s/%s?format=%s' % (url_base, report_url, format),
        'name':
        report_name
    } for (report_name, report_url) in report_item_list]
    message_html = newline_to_br(html_quote(message))

    message_text_format = "text/html"
    attachment_list = []
    notification_message_reference = prefs.getPreferredDeferredReportNotificationMessageReference(
    )
    if notification_message_reference:
        notification_message = portal.portal_notifications.getDocumentValue(
            reference=notification_message_reference)
        if notification_message is None:
            raise ValueError(
                'Notification message not found by %r' %
                prefs.getPreferredDeferredReportNotificationMessageReference())
        notification_mapping_dict = {
            'report_link_list':
            portal.ERP5Site_viewReportCompleteNotificationMessage(
        l_encountered = 0
        for l_item in query_string.split('&'):
            l_param, l_value = l_item.split('=')
            if l_param == p_parameter:
                l_ret = query_string.replace(p_parameter + '=' + l_value, p_parameter +'=' + str(p_value))
                l_encountered = 1
        if l_encountered == 0:
            l_ret = query_string + '&' + p_parameter + '=' + p_value
    except:
        l_ret = p_parameter + '=' + str(p_value)
    return l_ret


for th in headers:
    qs = changeQueryString(request['QUERY_STRING'],'sort_on',th['id'])
    title = html_quote(th['title'])
    if th['sortable']:
        if sort_on == th['id']:
            if sort_order == '':
                qs = changeQueryString(qs,'sort_order','reverse')
                print """<th scope="col" class="sorted" title="Sorted A..Z"><a
                 href="%s?%s" rel="nofollow">%s<img
                 src="/styles/sortup.gif" width="12" height="12" alt=""/></a></th>""" % \
                 ( request['URL'], html_quote(qs), title)
            else:
                qs = changeQueryString(qs,'sort_order','')
                print """<th scope="col" class="sorted" title="Sorted Z..A"><a
                  href="%s?%s" rel="nofollow">%s<img
                 src="/styles/sortdown.gif" width="12" height="12" alt=""/></a></th>""" % \
                 ( request['URL'], html_quote(qs), title)
        else:
Exemple #29
0
    def info(self, brain, allowLink=True):
        '''Get information from a brain'''
        __traceback_info__ = (brain, allowLink)
        id = brain.getId
        url = brain.getURL()
        portal_type = brain.portal_type
        collection = portal_type in self.coll_types
        tool = self.tool
        preview = tool.getPreviewUrl(portal_type, url)

        # Path for the uid catalog doesn't have the leading '/'
        path = brain.getPath()
        UID = None
        if path and self.uid_catalog:
            try:
                metadata = self.uid_catalog.getMetadataForUID(
                    path[self.prefix_length:])
            except KeyError:
                metadata = None
            if metadata:
                UID = metadata.get('UID', None)

        if UID:
            id = UID

        if collection and self.resource_type.allow_browse:
            src = brain.getURL()
            if not src.endswith('/'): src += '/'
            src += self.srctail
        else:
            src = None

        if UID and self.linkbyuid:
            url = self.base + '/resolveuid/%s' % UID

        if self.showimagesize:
            normal = tool.getNormalUrl(portal_type, url)
        else:
            normal = url

        sizes = self.get_image_sizes(brain, portal_type, url)
        defscale = self.tool.getDefaultScaleForType(portal_type)
        media = self.media(portal_type)
        classes = self.classes(portal_type)

        icon = self.icon(portal_type)
        size, width, height = self.sizes(brain)

        title = filterControlChars(brain.Title or brain.getId)
        description = newline_to_br(html_quote(brain.Description))
        linkable = None
        if allowLink:
            linkable = True
            collection = False

        anchor = portal_type in self.anchor_types
        review_state, className = self.getState(brain.review_state)

        return {
            'id': id,
            'url': normal,
            'portal_type': portal_type,
            'collection': collection,
            'icon': icon,
            'size': size,
            'width': width,
            'height': height,
            'preview': preview,
            'sizes': sizes,
            'defscale': defscale,
            'media': media,
            'classes': classes,
            'title': title,
            'description': description,
            'linkable': linkable,
            'src': src,
            'anchor': anchor,
            'state': review_state,
            'class': className,
        }
Exemple #30
0
    def calculate(self, uid=None):
        analysis = self.analyses[uid]
        form_result = self.current_results[uid]['result']
        service = analysis.getService()
        calculation = service.getCalculation()
        if analysis.portal_type == 'ReferenceAnalysis':
            deps = {}
        else:
            deps = {}
            for dep in analysis.getDependencies():
                deps[dep.UID()] = dep
        path = '++resource++bika.lims.images'
        mapping = {}

        # values to be returned to form for this UID
        Result = {'uid': uid, 'result': form_result}
        try:
            Result['result'] = float(form_result)
        except:
            if form_result == "0/0":
                Result['result'] = ""

        if calculation:

            '''
             We need first to create the map of available parameters
             acording to the interims, analyses and wildcards:
             params = {
                    <as-1-keyword>              : <analysis_result>,
                    <as-1-keyword>.<wildcard-1> : <wildcard_1_value>,
                    <as-1-keyword>.<wildcard-2> : <wildcard_2_value>,
                    <interim-1>                 : <interim_result>,
                    ...
                    }
            '''

            # Get dependent analyses results and wildcard values to the
            # mapping. If dependent analysis without result found,
            # break and abort calculation
            unsatisfied = False
            for dependency_uid, dependency in deps.items():
                if dependency_uid in self.ignore_uids:
                    unsatisfied = True
                    break

                # LIMS-1769. Allow to use LDL and UDL in calculations.
                # https://jira.bikalabs.com/browse/LIMS-1769
                analysisvalues = {}
                if dependency_uid in self.current_results:
                    analysisvalues = self.current_results[dependency_uid]
                else:
                    # Retrieve the result and DLs from the analysis
                    analysisvalues = {
                        'keyword':  dependency.getKeyword(),
                        'result':   dependency.getResult(),
                        'ldl':      dependency.getLowerDetectionLimit(),
                        'udl':      dependency.getUpperDetectionLimit(),
                        'belowldl': dependency.isBelowLowerDetectionLimit(),
                        'aboveudl': dependency.isAboveUpperDetectionLimit(),
                    }
                if analysisvalues['result']=='':
                    unsatisfied = True
                    break;
                key = analysisvalues.get('keyword',dependency.getService().getKeyword())

                # Analysis result
                # All result mappings must be float, or they are ignored.
                try:
                    mapping[key] = float(analysisvalues.get('result'))
                    mapping['%s.%s' % (key, 'RESULT')] = float(analysisvalues.get('result'))
                    mapping['%s.%s' % (key, 'LDL')] = float(analysisvalues.get('ldl'))
                    mapping['%s.%s' % (key, 'UDL')] = float(analysisvalues.get('udl'))
                    mapping['%s.%s' % (key, 'BELOWLDL')] = int(analysisvalues.get('belowldl'))
                    mapping['%s.%s' % (key, 'ABOVEUDL')] = int(analysisvalues.get('aboveudl'))
                except:
                    # If not floatable, then abort!
                    unsatisfied = True
                    break

            if unsatisfied:
                # unsatisfied means that one or more result on which we depend
                # is blank or unavailable, so we set blank result and abort.
                self.results.append({'uid': uid,
                                     'result': '',
                                     'formatted_result': ''})
                return None

            # Add all interims to mapping
            for i_uid, i_data in self.item_data.items():
                for i in i_data:
                    # if this interim belongs to current analysis and is blank,
                    # return an empty result for this analysis.
                    if i_uid == uid and i['value'] == '':
                        self.results.append({'uid': uid,
                                             'result': '',
                                             'formatted_result': ''})
                        return None
                    # All interims must be float, or they are ignored.
                    try:
                        i['value'] = float(i['value'])
                    except:
                        pass

                    # all interims are ServiceKeyword.InterimKeyword
                    if i_uid in deps:
                        key = "%s.%s" % (deps[i_uid].getService().getKeyword(),
                                         i['keyword'])
                        mapping[key] = i['value']
                    # this analysis' interims get extra reference
                    # without service keyword prefix
                    if uid == i_uid:
                        mapping[i['keyword']] = i['value']

            # Grab values for hidden InterimFields for only for current calculation
            # we can't allow non-floats through here till we change the eval's
            # interpolation
            hidden_fields = []
            c_fields = calculation.getInterimFields()
            s_fields = service.getInterimFields()
            for field in c_fields:
                if field.get('hidden', False):
                    hidden_fields.append(field['keyword'])
                    try:
                        mapping[field['keyword']] = float(field['value'])
                    except ValueError:
                        pass
            # also grab stickier defaults from AnalysisService
            for field in s_fields:
                if field['keyword'] in hidden_fields:
                    try:
                        mapping[field['keyword']] = float(field['value'])
                    except ValueError:
                        pass

            # convert formula to a valid python string, ready for interpolation
            formula = calculation.getMinifiedFormula()
            formula = formula.replace('[', '%(').replace(']', ')f')
            try:
                formula = eval("'%s'%%mapping" % formula,
                               {"__builtins__": None,
                                'math': math,
                                'context': self.context},
                               {'mapping': mapping})
                # calculate
                result = eval(formula)
                Result['result'] = result
                self.current_results[uid]['result'] = result
            except TypeError as e:
                # non-numeric arguments in interim mapping?
                alert = {'field': 'Result',
                         'icon': path + '/exclamation.png',
                         'msg': "{0}: {1} ({2}) ".format(
                             t(_("Type Error")),
                             html_quote(str(e.args[0])),
                             formula)}
                if uid in self.alerts:
                    self.alerts[uid].append(alert)
                else:
                    self.alerts[uid] = [alert, ]
            except ZeroDivisionError as e:
                Result['result'] = '0/0'
                Result['formatted_result'] = '0/0'
                self.current_results[uid]['result'] = '0/0'
                self.results.append(Result)
                alert = {'field': 'Result',
                         'icon': path + '/exclamation.png',
                         'msg': "{0}: {1} ({2}) ".format(
                             t(_("Division by zero")),
                             html_quote(str(e.args[0])),
                             formula)}
                if uid in self.alerts:
                    self.alerts[uid].append(alert)
                else:
                    self.alerts[uid] = [alert, ]
                return None
            except KeyError as e:
                alert = {'field': 'Result',
                         'icon': path + '/exclamation.png',
                         'msg': "{0}: {1} ({2}) ".format(
                             t(_("Key Error")),
                             html_quote(str(e.args[0])),
                             formula)}
                if uid in self.alerts:
                    self.alerts[uid].append(alert)
                else:
                    self.alerts[uid] = [alert, ]

        if analysis.portal_type == 'ReferenceAnalysis':
            # The analysis is a Control or Blank. We might use the
            # reference results instead other specs
            _uid = analysis.getServiceUID()
            specs = analysis.aq_parent.getResultsRangeDict().get(_uid, {})

        else:
            # Get the specs directly from the analysis. The getResultsRange
            # function already takes care about which are the specs to be used:
            # AR, client or lab.
            specs = analysis.getResultsRange()

        # format result
        try:
            Result['formatted_result'] = format_numeric_result(analysis,
                                                               Result['result'])
        except ValueError:
            # non-float
            Result['formatted_result'] = Result['result']
        # calculate Dry Matter result
        # if parent is not an AR, it's never going to be calculable
        dm = hasattr(analysis.aq_parent, 'getReportDryMatter') and \
            analysis.aq_parent.getReportDryMatter() and \
            analysis.getService().getReportDryMatter()
        if dm:
            dry_service = self.context.bika_setup.getDryMatterService()
            # get the UID of the DryMatter Analysis from our parent AR
            dry_analysis = [a for a in
                            analysis.aq_parent.getAnalyses(full_objects=True)
                            if a.getService().UID() == dry_service.UID()]
            if dry_analysis:
                dry_analysis = dry_analysis[0]
                dry_uid = dry_analysis.UID()
                # get the current DryMatter analysis result from the form
                if dry_uid in self.current_results:
                    try:
                        dry_result = float(self.current_results[dry_uid])
                    except:
                        dm = False
                else:
                    try:
                        dry_result = float(dry_analysis.getResult())
                    except:
                        dm = False
            else:
                dm = False
        Result['dry_result'] = dm and dry_result and \
            '%.2f' % ((Result['result'] / dry_result) * 100) or ''

        self.results.append(Result)

        # if App.config.getConfiguration().debug_mode:
        #     logger.info("calc.py: %s->%s %s" % (analysis.aq_parent.id,
        #                                         analysis.id,
        #                                         Result))

        # LIMS-1808 Uncertainty calculation on DL
        # https://jira.bikalabs.com/browse/LIMS-1808
        flres = Result.get('result', None)
        if flres and isnumber(flres):
            flres = float(flres)
            anvals = self.current_results[uid]
            isldl = anvals.get('isldl', False)
            isudl = anvals.get('isudl', False)
            ldl = anvals.get('ldl',0)
            udl = anvals.get('udl',0)
            ldl = float(ldl) if isnumber(ldl) else 0
            udl = float(udl) if isnumber(udl) else 10000000
            belowldl = (isldl or flres < ldl)
            aboveudl = (isudl or flres > udl)
            unc = '' if (belowldl or aboveudl) else analysis.getUncertainty(Result.get('result'))
            if not (belowldl or aboveudl):
                self.uncertainties.append({'uid': uid, 'uncertainty': unc})

        # maybe a service who depends on us must be recalculated.
        if analysis.portal_type == 'ReferenceAnalysis':
            dependents = []
        else:
            dependents = analysis.getDependents()
        if dependents:
            for dependent in dependents:
                dependent_uid = dependent.UID()
                # ignore analyses that no longer exist.
                if dependent_uid in self.ignore_uids or \
                   dependent_uid not in self.analyses:
                    continue
                self.calculate(dependent_uid)

        # These self.alerts are just for the json return.
        # we're placing the entire form's results in kwargs.
        adapters = getAdapters((analysis, ), IFieldIcons)
        for name, adapter in adapters:
            alerts = adapter(result=Result['result'], form_results=self.current_results)
            if alerts:
                if analysis.UID() in self.alerts:
                    self.alerts[analysis.UID()].extend(alerts[analysis.UID()])
                else:
                    self.alerts[analysis.UID()] = alerts[analysis.UID()]
<rdf:RDF
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  xmlns:dc="http://purl.org/dc/elements/1.1/"
  xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
  xmlns:rod="http://rod.eionet.europa.eu/schema.rdf#">"""

RESPONSE.setHeader('content-type', 'application/rdf+xml;charset=utf-8')
print """<rdf:Description rdf:about="">
   <rdfs:label>Deliveries from %s</rdfs:label>
</rdf:Description>""" % request.SERVER_URL
dow = context.ZopeTime().dow()
for item in container.Catalog(meta_type='Report Envelope', released=1,
                  reportingdate=context.ZopeTime() - 360 - dow, reportingdate_usage='range:max'):
  try:
    ob = item.getObject()
    print """<rod:Delivery rdf:about="%s">""" % html_quote(ob.absolute_url())
    print """  <dc:title>%s</dc:title>""" % html_quote(ob.title_or_id())
    if ob.descr:
        print """  <dc:description>%s</dc:description>""" % html_quote(ob.descr)

    print """  <dc:date>%s</dc:date>""" % ob.reportingdate.HTML4()
    print """  <dc:identifier>%s</dc:identifier>""" % html_quote(ob.absolute_url())
    if ob.country:
        print """  <rod:locality rdf:resource="%s" />""" % ob.country

    for year in ob.years():
        print """  <dc:coverage>%s</dc:coverage>""" % year

    for flow in ob.dataflow_uris:
        print """  <rod:obligation rdf:resource="%s" />""" % html_quote(flow)
Exemple #32
0
    def calculate(self, uid=None):

        translate = self.context.translation_service.translate

        analysis = self.analyses[uid]
        form_result = self.current_results[uid]
        service = analysis.getService()
        precision = service.getPrecision()
        calculation = service.getCalculation()
        if analysis.portal_type == 'ReferenceAnalysis':
            deps = {}
        else:
            deps = {}
            for dep in analysis.getDependencies():
                deps[dep.UID()] = dep

        mapping = {}

        # values to be returned to form for this UID
        Result = {'uid': uid}
        try:
            Result['result'] = float(form_result)
        except:
            if form_result.startswith("<") or \
               form_result.startswith(">"):
                # Indeterminate results
                Indet = translate(_("Indeterminate result"))
                self.alerts.append({
                    'uid': uid,
                    'field': 'Result',
                    'icon': 'exclamation',
                    'msg': Indet
                })
                Result['result'] = form_result
                # Don't try calculate this result
                calculation = False
            elif form_result == "":
                # empty result returns "" value to set form result empty
                Result['result'] = form_result
            else:
                # other un-floatable results get forced to 0.
                Result['result'] = 0.0

        # This gets set if <> is detected in interim values, so that
        # TypeErrors during calculation can set the correct alert message
        indeterminate = False

        if calculation:
            # add all our dependent analyses results to the mapping.
            # Retrieve value from database if it's not in the current_results.
            unsatisfied = False
            for dependency_uid, dependency in deps.items():
                if dependency_uid in self.ignore_uids:
                    unsatisfied = True
                    break
                if dependency_uid in self.current_results:
                    result = self.current_results[dependency_uid]
                else:
                    result = dependency.getResult()
                if result == '':
                    unsatisfied = True
                    break
                key = dependency.getService().getKeyword()
                # All mappings must be float, or error alert is returned
                try:
                    mapping[key] = float(self.current_results[dependency_uid])
                except:
                    # indeterminate interim values (<x, >x, invalid)
                    # set 'indeterminate' flag on this analyses' result
                    indeterminate = True
            if unsatisfied:
                # unsatisfied means that one or more result on which we depend
                # is blank or unavailable, so we set blank result and abort.
                self.results.append({
                    'uid': uid,
                    'result': '',
                    'formatted_result': ''
                })
                return None

            # Add all interims to mapping
            for i_uid, i_data in self.item_data.items():
                for i in i_data:
                    # if this interim belongs to current analysis and is blank,
                    # return an empty result for this analysis.
                    if i_uid == uid and i['value'] == '':
                        self.results.append({
                            'uid': uid,
                            'result': '',
                            'formatted_result': ''
                        })
                        return None
                    # All interims must be float, or error alert is returned
                    try:
                        i['value'] = float(i['value'])
                    except:
                        # indeterminate interim values (<x, >x, invald)
                        # set 'indeterminate' flag on this analyses' result
                        indeterminate = True

                    # all interims are ServiceKeyword.InterimKeyword
                    if i_uid in deps:
                        key = "%s.%s" % (deps[i_uid].getService().getKeyword(),
                                         i['keyword'])
                        mapping[key] = i['value']
                    # this analysis' interims get extra reference
                    # without service keyword prefix
                    if uid == i_uid:
                        mapping[i['keyword']] = i['value']

            # convert formula to a valid python string, ready for interpolation
            formula = calculation.getFormula()
            formula = formula.replace('[', '%(').replace(']', ')f')

            try:
                formula = eval("'%s'%%mapping" % formula, {
                    "__builtins__": None,
                    'math': math,
                    'context': self.context
                }, {'mapping': mapping})
                # calculate
                result = eval(formula)

                Result['result'] = result

                self.current_results[uid] = result

            except TypeError:
                # non-numeric arguments in interim mapping?
                if indeterminate:
                    indet = translate(_('Indet'))
                    Indet = translate(_("Indeterminate result"))
                    Result['result'] = indet
                    self.alerts.append({
                        'uid': uid,
                        'field': 'Result',
                        'icon': 'exclamation',
                        'msg': Indet
                    })
                else:
                    inval = translate(_("Invalid result"))
                    self.alerts.append({
                        'uid': uid,
                        'field': 'Result',
                        'icon': 'exclamation',
                        'msg': inval
                    })

            except ZeroDivisionError, e:
                return None
            except KeyError, e:
                self.alerts.append({
                    'uid':
                    uid,
                    'field':
                    'Result',
                    'icon':
                    'exclamation',
                    'msg':
                    "Key Error: " + html_quote(str(e.args[0]))
                })
                return None
    write('''</fieldset>''')
else:
    write('''<fieldset class="livesearchContainer">''')
    write('''<legend id="livesearchLegend">%s</legend>''' %
          ts.translate(legend_livesearch, context=REQUEST))
    write('''<div class="LSIEFix">''')
    write('''<ul class="dropdown-list LSTable">''')
    for result in results[:limit]:

        itemUrl = result.getURL()
        if result.portal_type in useViewAction:
            itemUrl += '/view'

        itemUrl = itemUrl + searchterm_query

        title = html_quote(safe_unicode(pretty_title_or_id(result)))

        css_klass = 'contenttype-%s' % ploneUtils.normalizeString(
            result.portal_type)
        mime_type_klass = get_mimetype_icon_klass(result)
        if mime_type_klass:
            css_klass = mime_type_klass

        write('''<a href="%s" title="%s" class="dropdown-list-item LSRow">''' %
              (itemUrl, title))
        write(
            '''<span class="%s"/><span class="dropdown-list-item-content">''' %
            (css_klass))
        write('''<div class="LSTitle">%s</div>''' % (title))

        description = html_quote(safe_unicode(result.Description))
                                                                            icon.description,
                                                                            icon.width,
                                                                            icon.height))
        full_title = safe_unicode(pretty_title_or_id(result))
        if len(full_title) > MAX_TITLE:
            display_title = ''.join((full_title[:MAX_TITLE],'...'))
        else:
            display_title = full_title
        full_title = full_title.replace('"', '&quot;')
        write('''<a href="%s" title="%s">%s</a>''' % (itemUrl, full_title, display_title))
        write('''<span class="discreet">[%s%%]</span>''' % result.data_record_normalized_score_)
        display_description = safe_unicode(result.Description)
        if len(display_description) > MAX_DESCRIPTION:
            display_description = ''.join((display_description[:MAX_DESCRIPTION],'...'))
        # need to quote it, to avoid injection of html containing javascript and other evil stuff
        display_description = html_quote(display_description)
        write('''<div class="discreet" style="margin-left: 2.5em;">%s</div>''' % (display_description))
        write('''</li>''')
        full_title, display_title, display_description = None, None, None

    write('''<li class="LSRow">''')
    write( '<a href="search_form" style="font-weight:normal">%s</a>' % ts.translate(label_advanced_search))
    write('''</li>''')

    if len(results)>limit:
        # add a more... row
        write('''<li class="LSRow">''')
        if name == 'Title':
            write( '<a href="%s" style="font-weight:normal">%s</a>' % ('search?Title=' + searchterms+'&path='+path, ts.translate(label_show_all)))
        else:
            write( '<a href="%s" style="font-weight:normal">%s</a>' % ('search?SearchableText=' + searchterms+'&path='+path, ts.translate(label_show_all)))
from Products.PythonScripts.standard import html_quote

# even if we have several divergence testers, the first
# one is enough for displaying the title.
tester = context.getCausalityValue()
return '<div>%s</div><div><em>(%s)</em></div>' % (
    html_quote(tester.getTranslatedTitle()),
    context.getExplanationMessage())
Exemple #36
0
from Products.PythonScripts.standard import html_quote

# even if we have several divergence testers, the first
# one is enough for displaying the title.
tester = context.getCausalityValue()
return '<div>%s</div><div><em>%s</em></div>' % (html_quote(
    tester.getTranslatedTitle()), context.getExplanationMessage())
import re
from Products.PythonScripts.standard import html_quote

document = context
document_content = content
websection = document.getWebSectionValue()
document_url = html_quote(websection.getPermanentURL(context))

# table of content
# XXX we are back to adding TOC to all documents, which we don't want
# XXX fix this to be applied only if a page is viewed as chapter
document_header_list = re.findall("<h[1-6].*?</h[1-6]>", document_content or "")

if len(document_header_list) > 0:
  header_current = 1
  header_initial = None
  table_of_content = ''
  
  for header in document_header_list:
    header_level = header[2]
    header_initial = header_initial or header_level
    header_reference = re.findall(">(.*)<", header)[0]
    header_lowercase = header_reference.lower()
    header_reference_prefix = header_lowercase.replace(" ", "-")

    if header_level == header_current:
      table_of_content += '</li>'

    # start of a list
    if header_level > header_current:
      header_current = header_level
from Products.PythonScripts.standard import html_quote

key = brain.object_id

portal_absolute_url = context.getPortalObject().absolute_url()

if brain.choice == '1_create_form':
  return None
else:
  return html_quote('%s/portal_skins/%s/manage_main' % (portal_absolute_url, key))
Exemple #39
0
    def info_object(self, obj, allowLink=True):
        '''Get information from a content object'''

        # Parent folder might not be accessible if we came here from a
        # search.
        if not self.security.checkPermission('View', obj):
            return None

        __traceback_info__ = (obj, allowLink)
        id = None
        UID = None
        try:
            if self.portal_interface.objectImplements(
                    obj,
                    'Products.Archetypes.interfaces.referenceable.IReferenceable'
            ):
                UID = getattr(obj.aq_explicit, 'UID', None)
                if UID:
                    UID = UID()
                    id = UID

            if not id:
                id = obj.absolute_url(relative=1)

            portal_type = getattr(obj, 'portal_type', '')
            collection = portal_type in self.coll_types
            tool = self.tool
            url = obj.absolute_url()
            preview = tool.getPreviewUrl(portal_type, url)

            if collection and self.resource_type.allow_browse:
                src = obj.absolute_url()
                if not src.endswith('/'): src += '/'
                src += self.srctail
            else:
                src = None

            if UID and self.linkbyuid:
                url = self.base + '/resolveuid/%s' % UID

            if self.showimagesize:
                normal = tool.getNormalUrl(portal_type, url)
            else:
                normal = url

            sizes = self.get_image_sizes(obj, portal_type, url)
            defscale = self.tool.getDefaultScaleForType(portal_type)

            media = self.media(portal_type)
            classes = self.classes(portal_type)

            icon = self.icon(portal_type)
            size, width, height = self.sizes(obj)

            title = filterControlChars(obj.Title() or obj.getId())
            description = newline_to_br(html_quote(obj.Description()))

            linkable = None
            if allowLink:
                linkable = True
                collection = False

            anchor = portal_type in self.anchor_types
            review_state, className = self.getState(
                self.workflow_tool.getInfoFor(obj, 'review_state', None))

            return {
                'id': id,
                'url': normal,
                'portal_type': portal_type,
                'collection': collection,
                'icon': icon,
                'size': size,
                'width': width,
                'height': height,
                'preview': preview,
                'sizes': sizes,
                'defscale': defscale,
                'media': media,
                'classes': classes,
                'title': title,
                'description': description,
                'linkable': linkable,
                'src': src,
                'anchor': anchor,
                'state': review_state,
                'class': className,
            }
        except Unauthorized:
            return None
Exemple #40
0
def _newlineToBr(s):
    return html_quote(s).replace('\n', '<br />')
Exemple #41
0
    def calculate(self, uid=None):
        # TODO Move this function to api.analysis.calculate
        analysis = self.analyses[uid]
        form_result = self.current_results[uid]['result']
        calculation = analysis.getCalculation()
        if analysis.portal_type == 'ReferenceAnalysis':
            deps = {}
        else:
            deps = {}
            for dep in analysis.getDependencies():
                deps[dep.UID()] = dep
        path = '++resource++bika.lims.images'
        mapping = {}

        # values to be returned to form for this UID
        Result = {'uid': uid, 'result': form_result}
        try:
            Result['result'] = float(form_result)
        except:
            if form_result == "0/0":
                Result['result'] = ""

        if calculation:
            """We need first to create the map of available parameters
               acording to the interims, analyses and wildcards:

             params = {
                    <as-1-keyword>              : <analysis_result>,
                    <as-1-keyword>.<wildcard-1> : <wildcard_1_value>,
                    <as-1-keyword>.<wildcard-2> : <wildcard_2_value>,
                    <interim-1>                 : <interim_result>,
                    ...
                    }
            """

            # Get dependent analyses results and wildcard values to the
            # mapping. If dependent analysis without result found,
            # break and abort calculation
            unsatisfied = False
            for dependency_uid, dependency in deps.items():
                if dependency_uid in self.ignore_uids:
                    unsatisfied = True
                    break

                # LIMS-1769. Allow to use LDL and UDL in calculations.
                # https://jira.bikalabs.com/browse/LIMS-1769
                analysisvalues = {}
                if dependency_uid in self.current_results:
                    analysisvalues = self.current_results[dependency_uid]
                else:
                    # Retrieve the result and DLs from the analysis
                    analysisvalues = {
                        'keyword': dependency.getKeyword(),
                        'result': dependency.getResult(),
                        'ldl': dependency.getLowerDetectionLimit(),
                        'udl': dependency.getUpperDetectionLimit(),
                        'belowldl': dependency.isBelowLowerDetectionLimit(),
                        'aboveudl': dependency.isAboveUpperDetectionLimit(),
                    }
                if analysisvalues['result'] == '':
                    unsatisfied = True
                    break
                key = analysisvalues.get('keyword', dependency.getKeyword())

                # Analysis result
                # All result mappings must be float, or they are ignored.
                try:
                    mapping[key] = float(analysisvalues.get('result'))
                    mapping['%s.%s' % (key, 'RESULT')] = float(analysisvalues.get('result'))
                    mapping['%s.%s' % (key, 'LDL')] = float(analysisvalues.get('ldl'))
                    mapping['%s.%s' % (key, 'UDL')] = float(analysisvalues.get('udl'))
                    mapping['%s.%s' % (key, 'BELOWLDL')] = int(analysisvalues.get('belowldl'))
                    mapping['%s.%s' % (key, 'ABOVEUDL')] = int(analysisvalues.get('aboveudl'))
                except:
                    # If not floatable, then abort!
                    unsatisfied = True
                    break

            if unsatisfied:
                # unsatisfied means that one or more result on which we depend
                # is blank or unavailable, so we set blank result and abort.
                self.results.append({'uid': uid,
                                     'result': '',
                                     'formatted_result': ''})
                return None

            # Add all interims to mapping
            for i_uid, i_data in self.item_data.items():
                for i in i_data:
                    # if this interim belongs to current analysis and is blank,
                    # return an empty result for this analysis.
                    if i_uid == uid and i['value'] == '':
                        self.results.append({'uid': uid,
                                             'result': '',
                                             'formatted_result': ''})
                        return None
                    # All interims must be float, or they are ignored.
                    try:
                        i['value'] = float(i['value'])
                    except:
                        pass

                    # all interims are ServiceKeyword.InterimKeyword
                    if i_uid in deps:
                        key = "%s.%s" % (deps[i_uid].getKeyword(),
                                         i['keyword'])
                        mapping[key] = i['value']
                    # this analysis' interims get extra reference
                    # without service keyword prefix
                    if uid == i_uid:
                        mapping[i['keyword']] = i['value']

            # Grab values for hidden InterimFields for only for current calculation
            # we can't allow non-floats through here till we change the eval's
            # interpolation
            hidden_fields = []
            c_fields = calculation.getInterimFields()
            s_fields = analysis.getInterimFields()
            for field in c_fields:
                if field.get('hidden', False):
                    hidden_fields.append(field['keyword'])
                    try:
                        mapping[field['keyword']] = float(field['value'])
                    except ValueError:
                        pass
            # also grab stickier defaults from AnalysisService
            for field in s_fields:
                if field['keyword'] in hidden_fields:
                    try:
                        mapping[field['keyword']] = float(field['value'])
                    except ValueError:
                        pass

            # convert formula to a valid python string, ready for interpolation
            formula = calculation.getMinifiedFormula()
            formula = formula.replace('[', '%(').replace(']', ')f')
            try:
                formula = eval("'%s'%%mapping" % formula,
                               {"__builtins__": None,
                                'math': math,
                                'context': self.context},
                               {'mapping': mapping})
                # calculate
                result = eval(formula, calculation._getGlobals())
                Result['result'] = result
                self.current_results[uid]['result'] = result
            except TypeError as e:
                # non-numeric arguments in interim mapping?
                alert = {'field': 'Result',
                         'icon': path + '/exclamation.png',
                         'msg': "{0}: {1} ({2}) ".format(
                             t(_("Type Error")),
                             html_quote(str(e.args[0])),
                             formula)}
                if uid in self.alerts:
                    self.alerts[uid].append(alert)
                else:
                    self.alerts[uid] = [alert, ]
            except ZeroDivisionError as e:
                Result['result'] = '0/0'
                Result['formatted_result'] = '0/0'
                self.current_results[uid]['result'] = '0/0'
                self.results.append(Result)
                alert = {'field': 'Result',
                         'icon': path + '/exclamation.png',
                         'msg': "{0}: {1} ({2}) ".format(
                             t(_("Division by zero")),
                             html_quote(str(e.args[0])),
                             formula)}
                if uid in self.alerts:
                    self.alerts[uid].append(alert)
                else:
                    self.alerts[uid] = [alert, ]
                return None
            except KeyError as e:
                alert = {'field': 'Result',
                         'icon': path + '/exclamation.png',
                         'msg': "{0}: {1} ({2}) ".format(
                             t(_("Key Error")),
                             html_quote(str(e.args[0])),
                             formula)}
                if uid in self.alerts:
                    self.alerts[uid].append(alert)
                else:
                    self.alerts[uid] = [alert, ]

        # format result
        try:
            Result['formatted_result'] = format_numeric_result(analysis,
                                                               Result['result'])
        except ValueError:
            # non-float
            Result['formatted_result'] = Result['result']

        self.results.append(Result)

        # if App.config.getConfiguration().debug_mode:
        #     logger.info("calc.py: %s->%s %s" % (analysis.aq_parent.id,
        #                                         analysis.id,
        #                                         Result))

        # LIMS-1808 Uncertainty calculation on DL
        # https://jira.bikalabs.com/browse/LIMS-1808
        flres = Result.get('result', None)
        if flres and isnumber(flres):
            flres = float(flres)
            anvals = self.current_results[uid]
            isldl = anvals.get('isldl', False)
            isudl = anvals.get('isudl', False)
            ldl = anvals.get('ldl', 0)
            udl = anvals.get('udl', 0)
            ldl = float(ldl) if isnumber(ldl) else 0
            udl = float(udl) if isnumber(udl) else 10000000
            belowldl = (isldl or flres < ldl)
            aboveudl = (isudl or flres > udl)
            unc = '' if (belowldl or aboveudl) else analysis.getUncertainty(Result.get('result'))
            if not (belowldl or aboveudl):
                self.uncertainties.append({'uid': uid, 'uncertainty': unc})

        # maybe a service who depends on us must be recalculated.
        if analysis.portal_type == 'ReferenceAnalysis':
            dependents = []
        else:
            dependents = analysis.getDependents()
        if dependents:
            for dependent in dependents:
                dependent_uid = dependent.UID()
                # ignore analyses that no longer exist.
                if dependent_uid in self.ignore_uids or \
                   dependent_uid not in self.analyses:
                    continue
                self.calculate(dependent_uid)

        # Render out of range / in shoulder alert info
        self._render_range_alert(analysis, Result["result"])
Exemple #42
0
    def manage_doCustomize(self, folder_path, RESPONSE=None):
        """Makes a ZODB Based clone with the same data.

        Calls _createZODBClone for the actual work.
        """

        obj = self._createZODBClone()
        parent = aq_parent(aq_inner(self))

        # Preserve cache manager associations
        cachemgr_id = self.ZCacheable_getManagerId()
        if (cachemgr_id
                and getattr(obj, 'ZCacheable_setManagerId', None) is not None):
            obj.ZCacheable_setManagerId(cachemgr_id)

        # If there are proxy roles we preserve them
        proxy_roles = getattr(aq_base(self), '_proxy_roles', None)
        if proxy_roles is not None and isinstance(proxy_roles, tuple):
            obj._proxy_roles = tuple(self._proxy_roles)

        # Also, preserve any permission settings that might have come
        # from a metadata file or from fiddling in the ZMI
        old_info = [x[:2] for x in self.ac_inherited_permissions(1)]
        for old_perm, value in old_info:
            p = Permission(old_perm, value, self)
            acquired = int(isinstance(p.getRoles(default=[]), list))
            rop_info = self.rolesOfPermission(old_perm)
            roles = [x['name'] for x in rop_info if x['selected'] != '']
            try:
                # if obj is based on OFS.ObjectManager an acquisition context is
                # required for _subobject_permissions()
                obj.__of__(parent).manage_permission(old_perm,
                                                     roles=roles,
                                                     acquire=acquired)
            except ValueError:
                # The permission was invalid, never mind
                pass

        id = obj.getId()
        fpath = tuple(folder_path.split('/'))
        portal_skins = getUtility(ISkinsTool)
        folder = portal_skins.restrictedTraverse(fpath)
        if id in folder.objectIds():
            # we cant catch the badrequest so
            # we'll that to check before hand
            obj = folder._getOb(id)
            if RESPONSE is not None:
                RESPONSE.redirect(
                    '%s/manage_main?manage_tabs_message=%s' %
                    (obj.absolute_url(),
                     html_quote("An object with this id already exists")))
        else:
            folder._verifyObjectPaste(obj, validate_src=0)
            folder._setObject(id, obj)

            if RESPONSE is not None:
                RESPONSE.redirect('%s/%s/manage_main' %
                                  (folder.absolute_url(), id))

        if RESPONSE is not None:
            RESPONSE.redirect('%s/%s/manage_main' %
                              (folder.absolute_url(), id))
## Script (Python) "data.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=
##
# Example code:

# Import a standard function, and get the HTML request and response objects.
from Products.PythonScripts.standard import html_quote
request = container.REQUEST
response =  request.response

# Return a string identifying this script.
print "This is the", script.meta_type, '"%s"' % script.getId(),
if script.title:
    print "(%s)" % html_quote(script.title),
print "in", container.absolute_url()
return printed
Exemple #44
0
 def utHtmlEncode(self, p_string):
     """Encode a string using html_quote"""
     return html_quote(p_string)
Exemple #45
0
 def get_description(self, brain):
     display_description = safe_unicode(brain.Description)
     # need to quote it, to avoid injection of html containing javascript
     # and other evil stuff
     return html_quote(display_description)
def getRecentActivityHTML(self, since=None):
    res = getRecentActivity(self, since=since)
    res = '\n'.join(res)
    return "<html><body>%s</body></html>" % html_quote(res).replace('\n','<br/>\n')
Exemple #47
0
        )

# social capital currency and registered court fallbacks
if source.get("social_capital_currency") is blank:
    currency_short_title = None
    currency_relative_url = pref.getPreferredCorporateIdentityTemplateDefaultCurrencyRelativeUrl(
    )
    if currency_relative_url:
        currency_short_title = context.restrictedTraverse(
            currency_relative_url).getShortTitle()
    source["social_capital_currency"] = currency_short_title or ""
if source.get("corporate_registration_code") is blank:
    source[
        "corporate_registration_code"] = pref.getPreferredCorporateIdentityTemplateDefaultOrganisationRegisteredCourt(
        )

# XXX images stored on organisation (as do images in skin folders)
if override_logo_reference:
    source_logo_url = html_quote(override_logo_reference) + "?format=png"
    source_set = True
if source_logo_url is None:
    source_logo_url = source.get("logo_url", blank)
if source_logo_url != blank and source_set is None:
    # XXX: test environment fails if url with parameters are supplied
    source_logo_url = source_logo_url + "?format=png"
if source_logo_url == blank and theme_logo_url is not None:
    source_logo_url = theme_logo_url
source["enhanced_logo_url"] = source_logo_url

return source
 def newlineToBr(self, p_string):
     return html_quote(p_string).replace('\n', '<br />')
        else:
            display_title = full_title

        full_title = full_title.replace('"', '&quot;')
        klass = 'contenttype-%s' \
                    % ploneUtils.normalizeString(result.portal_type)
        write('''<a href="%s" title="%s" class="%s">%s</a>'''
                % (itemUrl, full_title, klass, display_title))
        display_description = safe_unicode(result.Description)
        if display_description and len(display_description) > MAX_DESCRIPTION:
            display_description = ''.join(
                (display_description[:MAX_DESCRIPTION], '...'))

        # need to quote it, to avoid injection of html containing javascript
        # and other evil stuff
        display_description = html_quote(display_description)
        write('''<div class="LSDescr">%s</div>''' % (display_description))
        write('''</li>''')
        full_title, display_title, display_description = None, None, None

    write('''<li class="LSRow">''')
    write('<a href="%s" class="advancedsearchlink advanced-search">%s</a>' %
            (portal_url + '/search',
            ts.translate(label_advanced_search, context=REQUEST)))
    write('''</li>''')

    if len(results) > limit:
        # add a more... row
        write('''<li class="LSRow">''')
        searchquery = 'search?SearchableText=%s&path=%s' \
                        % (searchterms, params['path'])
Exemple #50
0
    def htmlContentsTree(self,
                         level=0,
                         node_chapter=None,
                         cookielist=_marker,
                         collection=None):
        """Generate HTML tree of content titles and urls. Done only as an optimization--all this recursion is
        absurdly slow in template, and slower in restricted code in general.

        The headings go from h4 to h6, based on the level param that increments at each recursion (it starts at 
        three because we only really start rendering contents one level in.)
        
        'cookielist' is list of UIDs of elements to expand; set to None to expand all.
           This really should be done in a template, but we don't have one yet.

        'collection' is the colID/version string to use for the URL collection parameter. 
           If None, will be colId/latest if published, or 'preview' if not.
        """
        result = u''
        nodes = self.objectValues([
            'Collection', 'SubCollection', 'ContentPointer',
            'PublishedContentPointer'
        ])
        if not (collection):
            collection = self.state == 'public' and (
                '%s/latest' % self.objectId) or 'preview'

        if level == 0 and not nodes:
            return "No contents."

        # chapter calculation. only for first level on textbooks (and skip v. small collections)
        numbering = level == 0 and len(nodes) > 0 and self.getCollectionType(
        ) == 'Textbook'
        chapter = None
        if numbering:
            types = set([x.portal_type for x in nodes])
            if 'SubCollection' not in types:  # collection consists of modules only
                chapter = 0
            elif types == set(['SubCollection']):  # ...subcollections only
                chapter = 0

        for node in nodes:
            title = node.Title()
            if type(title) != UnicodeType:
                title = title.decode('utf-8')
            if node.portal_type.find('ContentPointer') != -1:
                if numbering and chapter != None:
                    # if chapter is an int, use it...
                    chapter += 1
                    title = "%s. %s" % (chapter, title)
                result += u'<li id="%s"><a href="%s?collection=%s">%s</a></li>\n' % (
                    node.moduleId, node.moduleLocation(), collection,
                    html_quote(title))
            else:
                if numbering and chapter == None:
                    # ...if chapter is None, wait until we get a PCP, then become int.
                    chapter = 0
                if numbering and chapter != None:
                    chapter += 1
                result += node.htmlContentsTree(level + 1, chapter, cookielist,
                                                collection)

        if self.portal_type.find('SubCollection') != -1:
            title = self.Title()
            if type(title) != UnicodeType:
                title = title.decode('utf-8')
            if node_chapter != None:
                title = "%s. %s" % (node_chapter, title)
            header = level < 3 and level + 3 or 6
            uid = self.UID()
            display = not cookielist or "js%s" % uid in cookielist and 'block' or 'none'
            result = u"""
            <li class="cnx_null_li">
             <h%s class="cnx_chapter_header"
                  onclick="org.archomai.transMenus.toc.ExpandMenuHeader(event);">%s</h%s>
             <ul id="js%s" class="collapsibleMenu" style="display: %s">%s</ul>
            </li>""" % (header, html_quote(title), header, uid, display,
                        result)
        else:
            result = u'<ul id="collapsibleDemo">\n%s</ul>\n' % (result
                                                                )  # top level

        return result
 def htmlEncode(self, s):
     #encode a string using html_quote
     return html_quote(s)
Exemple #52
0
    def calculate(self, uid = None):

        analysis = self.analyses[uid]
        form_result = self.current_results[uid]
        service = analysis.getService()
        precision = service.getPrecision()
        calculation = service.getCalculation()
        if analysis.portal_type == 'ReferenceAnalysis':
            deps = {}
        else:
            deps = {}
            for dep in analysis.getDependencies():
                deps[dep.UID()] = dep

        mapping = {}

        # values to be returned to form for this UID
        Result = {'uid': uid}
        try:
            Result['result'] = float(form_result)
        except:
            if form_result.startswith("<") or \
               form_result.startswith(">"):
                # Indeterminate results
                Indet = translate(_("Indeterminate result"))
                self.alerts.append({'uid': uid,
                                    'field': 'Result',
                                    'icon': 'exclamation',
                                    'msg': Indet})
                Result['result'] = form_result
                # Don't try calculate this result
                calculation = False
            elif form_result == "":
                # empty result returns "" value to set form result empty
                Result['result'] = form_result
            elif form_result == "0/0":
                # 0/0 result means divbyzero: set result value to empty
                Result['result'] = ""
            else:
                # other un-floatable results get forced to 0.
                Result['result'] = 0.0

        # This gets set if <> is detected in interim values, so that
        # TypeErrors during calculation can set the correct alert message
        indeterminate = False

        if calculation:
            # add all our dependent analyses results to the mapping.
            # Retrieve value from database if it's not in the current_results.
            unsatisfied = False
            for dependency_uid, dependency in deps.items():
                if dependency_uid in self.ignore_uids:
                    unsatisfied = True
                    break
                if dependency_uid in self.current_results:
                    result = self.current_results[dependency_uid]
                else:
                    result = dependency.getResult()
                if result == '':
                    unsatisfied = True
                    break
                key = dependency.getService().getKeyword()
                # All mappings must be float, or error alert is returned
                try:
                    mapping[key] = float(self.current_results[dependency_uid])
                except:
                    # indeterminate interim values (<x, >x, invalid)
                    # set 'indeterminate' flag on this analyses' result
                    indeterminate = True
            if unsatisfied:
                # unsatisfied means that one or more result on which we depend
                # is blank or unavailable, so we set blank result and abort.
                self.results.append({'uid': uid,
                                     'result': '',
                                     'formatted_result': ''})
                return None

            # Add all interims to mapping
            for i_uid,i_data in self.item_data.items():
                for i in i_data:
                    # if this interim belongs to current analysis and is blank,
                    # return an empty result for this analysis.
                    if i_uid == uid and i['value'] == '':
                        self.results.append({'uid': uid,
                                             'result': '',
                                             'formatted_result': ''})
                        return None
                    # All interims must be float, or error alert is returned
                    try:
                        i['value'] = float(i['value'])
                    except:
                        # indeterminate interim values (<x, >x, invald)
                        # set 'indeterminate' flag on this analyses' result
                        indeterminate = True

                    # all interims are ServiceKeyword.InterimKeyword
                    if i_uid in deps:
                        key = "%s.%s"%(deps[i_uid].getService().getKeyword(),
                                       i['keyword'])
                        mapping[key] = i['value']
                    # this analysis' interims get extra reference
                    # without service keyword prefix
                    if uid == i_uid:
                        mapping[i['keyword']] = i['value']

            # convert formula to a valid python string, ready for interpolation
            formula = calculation.getFormula()
            formula = formula.replace('[', '%(').replace(']', ')f')

            try:
                formula = eval("'%s'%%mapping" % formula,
                               {"__builtins__":None,
                                'math':math,
                                'context':self.context},
                               {'mapping': mapping})
                # calculate
                result = eval(formula)

                Result['result'] = result

                self.current_results[uid] = result

            except TypeError:
                # non-numeric arguments in interim mapping?
                if indeterminate:
                    indet = self.context.translate(_('Indet'))
                    Indet = self.context.translate(_("Indeterminate result"))
                    Result['result'] = indet
                    self.alerts.append({'uid': uid,
                                        'field': 'Result',
                                        'icon': 'exclamation',
                                        'msg': Indet})
                else:
                    inval = self.context.translate(_("Invalid result"))
                    self.alerts.append({'uid': uid,
                                        'field': 'Result',
                                        'icon': 'exclamation',
                                        'msg': inval})

            except ZeroDivisionError, e:
                Result['result'] = '0/0'
                Result['formatted_result'] = '0/0'
                self.current_results[uid] = '0/0'
                self.alerts.append(
                    {'uid': uid,
                    'field': 'Result',
                    'icon': 'exclamation',
                    'msg': "Division by zero: " + html_quote(str(e.args[0])) + "("+formula+")"
                    })       
                self.results.append(Result)
                return None
            except KeyError, e:
                self.alerts.append(
                    {'uid': uid,
                     'field': 'Result',
                     'icon': 'exclamation',
                     'msg': "Key Error: " + html_quote(str(e.args[0]))
                     })
                return None
def print_as_elm(mydict):
    attrs=[]
    for elm,value in mydict.items():
        attrs.append('%s="%s"' % (elm,html_quote(str(value))))
    return "<file %s/>" % " ".join(attrs)
print '''<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="%s">\n'''  % langcode
print '''<head>\n'''
print '''<meta http-equiv="content-type" content="text/html; charset=utf-8" />\n'''
print '''<title>%s</title>\n''' % script.title
print '''<style type="text/css">'''
print '''table { border-collapse:collapse; margin: 1em 0; }\ntd,th {border: 1px solid black}\n'''
print '''</style>\n'''
print '''</head>\n<body>\n'''
print '''<table>'''
print '''<caption>Super groups</caption>'''
print '''<col style="width:4em"/><col style="width:6em"/><col style="width:4em"/><col style="width:30em"/>'''
print '''<thead><tr><th>Id</th><th>Type</th><th>SubGroupOf</th><th>Label</th></tr></thead><tbody>'''

#start generating HTML content
for sgroup in supergroups:
    print '<tr><td>%s</td><td>SuperGroup</td><td></td><td>%s</td></tr>' % (container.mp_group_id(sgroup),html_quote(container.mp_group_descr(sgroup)))
print '''</tbody></table>'''

print '''<table>'''
print '''<caption>Groups</caption>'''
print '''<col style="width:4em"/><col style="width:6em"/><col style="width:4em"/><col style="width:30em"/>'''
print '''<thead><tr><th>Id</th><th>Type</th><th>SubGroupOf</th><th>Label</th></tr></thead><tbody>'''
for group in groups:
    print '<tr><td>%s</td><td>Group</td>' % container.mp_group_id(group)
    print '<td>%s</td>' % container.mp_supergroup_id(group)
    print '<td>%s</td>' % html_quote(container.mp_group_descr(group))
    print '</tr>'
print '''</tbody></table>'''

print '''<table>'''
print '''<caption>Themes</caption>'''
Exemple #55
0
##parameters=record
##title=
##
request = container.REQUEST
RESPONSE =  request.RESPONSE

from Products.PythonScripts.standard import html_quote

class_names = ['center', 'section-border']
eu_country_code = record['eu_country_code'] or 'N/A'
title = ''
content = []

if record['complementary_other_information']!='':
    class_names.append('qa_error')
    content.append("""<div title="%s""" % html_quote(unicode(record['complementary_other_information'], 'utf-8')))
    if record['complementary_other_information_english'] is not None:
        content.append("""<br /><q>English automatic translation: </q>%s""" % html_quote(unicode(record['complementary_other_information_english'], 'utf-8')))
    if record['habitattype_type_asses'] == 0:
        errors = context.sql_methods.lookup_habitat_type(abbrev=record['habitattype_type'])
        if errors:
            content.append("""<br /><br />%s""" % errors[0]['SpeciesType'])
        else:
            content.append("""<br /><br />%s""" % record['habitattype_type'])
    content.append("""<br /><br /><em>Click to open original report in a new window</em>">%s</div>""" % eu_country_code)
elif record['habitattype_type_asses'] == 0:
    class_names.append('qa_error')
    errors = context.sql_methods.lookup_habitat_type(abbrev=record['habitattype_type'])
    if errors:
        title = errors[0]['SpeciesType']
    else:
def buildItem(item, drill_down_depth):
    return menu_item_template % (
        #html_quote(item.getRelativeUrl()),
        html_quote(item.getId()),
        html_quote(item.getTitle()),
        buildWebSectionMenu(getChildWebSectionList(item), drill_down_depth))
Exemple #57
0
    def calculate(self, uid=None):

        analysis = self.analyses[uid]
        form_result = self.current_results[uid]
        service = analysis.getService()
        precision = service.getPrecision()
        calculation = service.getCalculation()
        if analysis.portal_type == 'ReferenceAnalysis':
            deps = {}
        else:
            deps = {}
            for dep in analysis.getDependencies():
                deps[dep.UID()] = dep
        path = '++resource++bika.lims.images'
        mapping = {}

        # values to be returned to form for this UID
        Result = {'uid': uid, 'result': form_result}
        try:
            Result['result'] = float(form_result)
        except:
            if form_result == "0/0":
                Result['result'] = ""

        if calculation:
            # add all our dependent analyses results to the mapping.
            # Retrieve value from database if it's not in the current_results.
            unsatisfied = False
            for dependency_uid, dependency in deps.items():
                if dependency_uid in self.ignore_uids:
                    unsatisfied = True
                    break
                if dependency_uid in self.current_results:
                    result = self.current_results[dependency_uid]
                else:
                    result = dependency.getResult()
                if result == '':
                    unsatisfied = True
                    break
                key = dependency.getService().getKeyword()
                # All mappings must be float, or they are ignored.
                try:
                    mapping[key] = float(self.current_results[dependency_uid])
                except:
                    pass
            if unsatisfied:
                # unsatisfied means that one or more result on which we depend
                # is blank or unavailable, so we set blank result and abort.
                self.results.append({
                    'uid': uid,
                    'result': '',
                    'formatted_result': ''
                })
                return None

            # Add all interims to mapping
            for i_uid, i_data in self.item_data.items():
                for i in i_data:
                    # if this interim belongs to current analysis and is blank,
                    # return an empty result for this analysis.
                    if i_uid == uid and i['value'] == '':
                        self.results.append({
                            'uid': uid,
                            'result': '',
                            'formatted_result': ''
                        })
                        return None
                    # All interims must be float, or they are ignored.
                    try:
                        i['value'] = float(i['value'])
                    except:
                        pass

                    # all interims are ServiceKeyword.InterimKeyword
                    if i_uid in deps:
                        key = "%s.%s" % (deps[i_uid].getService().getKeyword(),
                                         i['keyword'])
                        mapping[key] = i['value']
                    # this analysis' interims get extra reference
                    # without service keyword prefix
                    if uid == i_uid:
                        mapping[i['keyword']] = i['value']

            # Grab values for hidden InterimFields for only for current calculation
            # we can't allow non-floats through here till we change the eval's
            # interpolation
            hidden_fields = []
            c_fields = calculation.getInterimFields()
            s_fields = service.getInterimFields()
            for field in c_fields:
                if field.get('hidden', False):
                    hidden_fields.append(field['keyword'])
                    try:
                        mapping[field['keyword']] = float(field['value'])
                    except ValueError:
                        pass
            # also grab stickier defaults from AnalysisService
            for field in s_fields:
                if field['keyword'] in hidden_fields:
                    try:
                        mapping[field['keyword']] = float(field['value'])
                    except ValueError:
                        pass

            # convert formula to a valid python string, ready for interpolation
            formula = calculation.getMinifiedFormula()
            formula = formula.replace('[', '%(').replace(']', ')f')
            try:
                formula = eval("'%s'%%mapping" % formula, {
                    "__builtins__": None,
                    'math': math,
                    'context': self.context
                }, {'mapping': mapping})
                # calculate
                result = eval(formula)
                Result['result'] = result
                self.current_results[uid] = result
            except TypeError as e:
                # non-numeric arguments in interim mapping?
                alert = {
                    'field':
                    'Result',
                    'icon':
                    path + '/exclamation.png',
                    'msg':
                    "{0}: {1} ({2}) ".format(t(_("Type Error")),
                                             html_quote(str(e.args[0])),
                                             formula)
                }
                if uid in self.alerts:
                    self.alerts[uid].append(alert)
                else:
                    self.alerts[uid] = [
                        alert,
                    ]
            except ZeroDivisionError as e:
                Result['result'] = '0/0'
                Result['formatted_result'] = '0/0'
                self.current_results[uid] = '0/0'
                self.results.append(Result)
                alert = {
                    'field':
                    'Result',
                    'icon':
                    path + '/exclamation.png',
                    'msg':
                    "{0}: {1} ({2}) ".format(t(_("Division by zero")),
                                             html_quote(str(e.args[0])),
                                             formula)
                }
                if uid in self.alerts:
                    self.alerts[uid].append(alert)
                else:
                    self.alerts[uid] = [
                        alert,
                    ]
                return None
            except KeyError as e:
                alert = {
                    'field':
                    'Result',
                    'icon':
                    path + '/exclamation.png',
                    'msg':
                    "{0}: {1} ({2}) ".format(t(_("Key Error")),
                                             html_quote(str(e.args[0])),
                                             formula)
                }
                if uid in self.alerts:
                    self.alerts[uid].append(alert)
                else:
                    self.alerts[uid] = [
                        alert,
                    ]

        # format result
        belowmin = False
        abovemax = False
        # Some analyses will not have AnalysisSpecs, eg, ReferenceAnalysis
        if hasattr(analysis, 'getAnalysisSpecs'):
            specs = analysis.getAnalysisSpecs()
            specs = specs.getResultsRangeDict() if specs is not None else {}
            specs = specs.get(analysis.getKeyword(), {})
            hidemin = specs.get('hidemin', '')
            hidemax = specs.get('hidemax', '')
            if Result.get('result', ''):
                fresult = Result['result']
                try:
                    belowmin = hidemin and fresult < float(hidemin) or False
                except ValueError:
                    belowmin = False
                    pass
                try:
                    abovemax = hidemax and fresult > float(hidemax) or False
                except ValueError:
                    abovemax = False
                    pass
        if belowmin is True:
            Result['formatted_result'] = '< %s' % hidemin
        elif abovemax is True:
            Result['formatted_result'] = '> %s' % hidemax
        else:
            try:
                Result['formatted_result'] = format_numeric_result(
                    analysis, Result['result'])
            except ValueError:
                # non-float
                Result['formatted_result'] = Result['result']

        # calculate Dry Matter result
        # if parent is not an AR, it's never going to be calculable
        dm = hasattr(analysis.aq_parent, 'getReportDryMatter') and \
            analysis.aq_parent.getReportDryMatter() and \
            analysis.getService().getReportDryMatter()
        if dm:
            dry_service = self.context.bika_setup.getDryMatterService()
            # get the UID of the DryMatter Analysis from our parent AR
            dry_analysis = [
                a for a in analysis.aq_parent.getAnalyses(full_objects=True)
                if a.getService().UID() == dry_service.UID()
            ]
            if dry_analysis:
                dry_analysis = dry_analysis[0]
                dry_uid = dry_analysis.UID()
                # get the current DryMatter analysis result from the form
                if dry_uid in self.current_results:
                    try:
                        dry_result = float(self.current_results[dry_uid])
                    except:
                        dm = False
                else:
                    try:
                        dry_result = float(dry_analysis.getResult())
                    except:
                        dm = False
            else:
                dm = False
        Result['dry_result'] = dm and dry_result and \
            '%.2f' % ((Result['result'] / dry_result) * 100) or ''

        self.results.append(Result)

        # if App.config.getConfiguration().debug_mode:
        #     logger.info("calc.py: %s->%s %s" % (analysis.aq_parent.id,
        #                                         analysis.id,
        #                                         Result))

        self.uncertainties.append({
            'uid':
            uid,
            'uncertainty':
            analysis.getUncertainty(Result['result'])
        })

        # maybe a service who depends on us must be recalculated.
        if analysis.portal_type == 'ReferenceAnalysis':
            dependents = []
        else:
            dependents = analysis.getDependents()
        if dependents:
            for dependent in dependents:
                dependent_uid = dependent.UID()
                # ignore analyses that no longer exist.
                if dependent_uid in self.ignore_uids or \
                   dependent_uid not in self.analyses:
                    continue
                self.calculate(dependent_uid)

        # These self.alerts are just for the json return.
        # we're placing the entire form's results in kwargs.
        adapters = getAdapters((analysis, ), IFieldIcons)
        for name, adapter in adapters:
            alerts = adapter(result=Result['result'],
                             form_results=self.current_results)
            if alerts:
                if analysis.UID() in self.alerts:
                    self.alerts[analysis.UID()].extend(alerts[analysis.UID()])
                else:
                    self.alerts[analysis.UID()] = alerts[analysis.UID()]
Exemple #58
0
def safe_html_quote(text):
    """ like html_quote but allow things like &#1234; """
    text = html_quote(text)
    text = destroyed_hex_entities.sub(r'&#\1;', text)
    return text
override_batch_mode = kw.get('batch_mode')

# -------------------------- Document Parameters  ------------------------------
book_relative_url = book.getRelativeUrl()
book_prefix = pref.getPreferredCorporateIdentityTemplateBookDocumentPrefix(
) or "Book."
book_rendering_fix = book.WebPage_getPdfOutputRenderingFix() or blank
book_content = book.getTextContent()
book_aggregate_list = []
book_revision = book.getRevision()
book_modification_date = book.getModificationDate()
book_language = book.getLanguage()

# XXX sigh for passing "" around
book_reference = html_quote(
    override_document_reference
) if override_document_reference else book.getReference()
book_short_title = html_quote(
    override_document_short_title
) if override_document_short_title else book.getShortTitle()
book_version = html_quote(
    override_document_version
) if override_document_version else book.getVersion() or "001"
book_description = html_quote(
    override_document_description
) if override_document_description else book.getDescription()
book_title = html_quote(
    override_document_title) if override_document_title else book.getTitle()

# unicode
if isinstance(book_content, unicode):
Exemple #60
0
def ShowDescription(text, display_format='', nofollow_rel=False):
    """
    Display text, using harmless HTML
    """

    text = SplitRegEx.sub('<!--split-->', text)

    codesyntax = ''
    if same_type(display_format, ()) or same_type(display_format, []):
        display_format, codesyntax = display_format

    if display_format == 'structuredtext':
        #st=_replace_special_chars(text)
        st = text

        for k, v in {  #'<':'&lt;', '>':'&gt;',
                '[': '|[|'
        }.items():
            st = st.replace(k, v)

        try:
            # my structured text
            st = nice_structured_text(st)
        except:
            st = structured_text(st)

        for k, v in {
                '&amp;lt;': '&lt;',
                '&amp;gt;': '&gt;',
                '|[|': '['
        }.items():
            st = st.replace(k, v)

        # BUG in structured_text in Zope 2.4.0
        # it appends these annoying tags.
        for tag in ['<html>', '<body>', '</body>', '</html>']:
            st = st.replace(tag, '')

        pre_whole_tags = re.compile(r'<pre>.*?</pre>', re.I | re.DOTALL)
        pre_tags = pre_whole_tags.findall(st)
        mem = {}
        for pre_tag in pre_tags:
            randstr = '__%s__' % getRandomString()
            mem[randstr] = pre_tag
            st = st.replace(pre_tag, randstr)

        ### NEEDS TO BE FIXED!
        #st = addhrefs(st, urllinkfunction=mylinker)

        for key, tag in mem.items():
            st = st.replace(key, tag)

        # preserve look of '<!--split-->'
        st = st.replace('<p><!--split--></p>', '<!--split-->')

        # syntax highlighting of code
        if str(codesyntax).lower() in ['c++', 'cpp']:
            st = SyntaxHighlight(st, CPP_SYNTAX)
        elif str(codesyntax).lower() in ['py', 'python']:
            st = SyntaxHighlight(st, PYTHON_SYNTAX)
        elif str(codesyntax).lower() in ['sql']:
            st = SyntaxHighlight(st, SQL_SYNTAX)
        elif str(codesyntax).lower() in ['xml/html', 'xml', 'html']:
            st = SyntaxHighlight(st, XML_SYNTAX)
        elif str(codesyntax).lower() in ['css', 'stylesheet']:
            st = SyntaxHighlight(st, CSS_SYNTAX)

        st = sole_ampersand_regex.sub('&amp;', st)

        return st
    elif display_format == 'html':
        return text
    elif display_format == 'texmix':
        texes = getTexes(text, 1)

        count = 1
        for tagused, texstring in texes:
            imageid = 'texjpeg-%s.jpg' % count
            imagepath = 'texcache/%s' % imageid
            imagetag = '<img src="%s" alt="%s" ' % (imagepath,
                                                    "*generated jpeg*")
            if tagused.lower().find('inline') > -1:
                imagetag += 'class="texmix-inline"'
            else:
                imagetag += 'class="texmix"'
            imagetag += ' />'
            text = text.replace(texstring, imagetag)
            count += 1

        text = text.replace('<texmix>', '<span class="texmix">')
        text = text.replace('<texmix inline="1">',
                            '<span class="texmix-inline">')
        text = text.replace('</texmix>', '</span>')
        format = 'structuredtext'
        if codesyntax:
            format = [format, codesyntax]
        return ShowDescription(text, format)

    else:
        t = html_quote(text)
        t = t.replace('&amp;lt;', '&lt;').replace('&amp;gt;', '&gt;')
        t = t.replace('&lt;!--split--&gt;', '<!--split-->')
        if nofollow_rel:

            def nofollower(url):
                template = '<a href="%s" rel="nofollow">%s</a>'
                return template % (url, url)

            t = addhrefs(t, urllinkfunction=nofollower)
        else:
            t = addhrefs(t)

        t = newline_to_br(t)
        return t