##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=
##

from Products.Silva.mangle import entities
from Products.SilvaDocument.i18n import translate as _

node = context.REQUEST.node
image = context.content()

if not image:
    return '<div class="error">[' + unicode(_('image reference is broken')) + ']</div>'

alignment = node.getAttribute('alignment')
link = node.getAttribute('link')
link_title = node.getAttribute('title')
target = node.getAttribute('target')
link_to_hires = node.getAttribute('link_to_hires')

if not alignment:
    alignment = 'default'

if not link_title:
    link_title = image.get_title()

tag_template = '%s'
if alignment.startswith('image-'):
from Products.SilvaDocument.i18n import translate as _

request = context.REQUEST
source = context.get_source()
uparameters = context.get_parameters()

parameters = {}
for key, value in uparameters.items():
    parameters[key.encode('ascii')] = value

try:
    html = source.to_html(request, **parameters)
except (Exception), err:
    #only log traceback if ExternalSources version has the function
    if source and hasattr(source,'log_traceback'):
            source.log_traceback()
    html = """<div class="warning"><strong>[""" + \
    unicode(_("external source element is broken")) + \
    "]</strong><br /> " + unicode(_("error message:")) + " " + str(err) + "</div>"
except:
    # Ugh, bare except to catch *all* cases...
    html = """<div class="warning"><strong>[""" + \
    unicode(_("external source element is broken")) + "]</strong><br />" + \
    unicode(_("Unfortunately however, there no error message available...")) + \
    "</div>"

return html
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=
##
from Products.SilvaDocument.i18n import translate as _

request = context.REQUEST
row = request.node
editorsupport = context.service_editorsupport
node = row.firstChild

model = node.get_content()

while node is not None:
    field = node
    node = node.nextSibling
    if field.nodeName != 'field':
        continue
    if not context.is_field_simple(field):
        continue
    p_node = field.firstChild
    while (p_node and p_node.nodeName != 'p'):
        # basictly this ignores text nodes.
        p_node = p_node.nextSibling
    if not p_node:
        raise ValueError, _("The stored xml is invalid.")
    data = request[p_node.getNodePath('widget')]
    supp = editorsupport.getMixedContentSupport(model, p_node)
    supp.parse(data)
    node.removeAttribute('id')
    return

if node.getAttribute('id') != id:
    # is changed, so remove all attrs.
    node.setAttribute('id', ustr(id))

# Use Document's context. If not, the complete widgets hierarchy comes
# in play and weird acquisition magic may cause 'source' to be a widget
# whenever the source object has a widget's id.
doc = node.get_silva_object()
source = getSourceForId(doc, id)
if source is None:
    # should not happen since id was selected from a list...
    # or should we silently ignore this?
    raise ValueError, _('Source is a NoneType - is it not available anymore?')

form = source.form()
try:
    result = form.validate_all_to_request(request)
except (FormValidationError, ValidationError), errs:
    pass
else:
    removeParameterElements(node)
    for field in form.get_fields():
        param = node.createElement('parameter')
        param.setAttribute('key', ustr(field.id))
        node.appendChild(param)
        vtype = 'string'
        value = result[field.id]
        if same_type(value, []):
Ejemplo n.º 5
0
from Products.SilvaDocument.i18n import translate as _

code = context.get_code_object()

if not code:
    return '<span class="warning">[' + unicode(
        _('Code element is broken')) + ']</span>'

ret = code()
if not same_type(ret, u''):
    encoding = context.service_old_codesource_charset.charset()
    ret = unicode(ret, encoding, 'replace')

return ret
Ejemplo n.º 6
0
from Products.SilvaDocument.i18n import translate as _

request = context.REQUEST
source = context.get_source()
uparameters = context.get_parameters()

parameters = {}
for key, value in uparameters.items():
    parameters[key.encode('ascii')] = value

try:
    html = source.to_html(request, **parameters)
except (Exception), err:
    #only log traceback if ExternalSources version has the function
    if source and hasattr(source, 'log_traceback'):
        source.log_traceback()
    html = """<div class="warning"><strong>[""" + \
    unicode(_("external source element is broken")) + \
    "]</strong><br /> " + unicode(_("error message:")) + " " + str(err) + "</div>"
except:
    # Ugh, bare except to catch *all* cases...
    html = """<div class="warning"><strong>[""" + \
    unicode(_("external source element is broken")) + "]</strong><br />" + \
    unicode(_("Unfortunately however, there no error message available...")) + \
    "</div>"

return html
Ejemplo n.º 7
0
    def sax_img(self, node):
        """Unfortunately <image> is a special case, since height and width
        are not stored in the document but in the Image object itself, and
        need to be retrieved here.
        """
        attributes = {}
        options = self.getOptions()
        request = self.getExported().request
        if node.attributes:
            attributes = get_dict(node.attributes)

        if options.external_rendering:
            rewritten_path = None
            if 'reference' in attributes:
                service = getUtility(IReferenceService)
                reference = service.get_reference(
                    self.context, name=attributes['reference'])
                image = reference.target
                if options.upgrade30:
                    attributes['data-silva-target'] = str(reference.target_id)
                    attributes['data-silva-reference'] = reference.tags[1]
                    reference.tags[0] = u"body image"
                    reference._p_changed = True
                elif image is not None:
                    rewritten_path = absoluteURL(image, request)
            else:
                document = self.context.get_content()
                image = document.unrestrictedTraverse(
                    attributes['path'].split('/'), None)
                if options.upgrade30:
                    attributes['data-silva-url'] = attributes['path']
                elif image is not None:
                    path = IPath(document)
                    rewritten_path = path.pathToUrlPath(attributes['path'])
            if not options.upgrade30:
                if not rewritten_path:
                    site = IVirtualSite(request)
                    rewritten_path = site.get_root_url() + \
                        "/++resource++Products.SilvaDocument/broken-link.jpg"
                    attributes['title'] = _(u'Referenced image is missing')
                attributes['rewritten_path'] = rewritten_path

            if image is not None:
                if IImage.providedBy(image):
                    resolution = options.image_res
                    attributes['title'] = image.get_title()
                    if resolution and not options.upgrade30:
                        attributes['rewritten_path'] += '?%s' % resolution
                        if resolution == 'hires':
                            width, height = image.get_dimensions()
                        attributes['width'] = str(width)
                        attributes['height'] = str(height)

        else:
            if 'reference' in attributes:
                attributes['reference'] = self.get_reference(
                    attributes['reference'])

        if attributes.has_key('alignment'):
            if not attributes['alignment']:
                attributes['alignment'] = 'default'
        else:
            attributes['alignment'] = 'default'
        self.startElementNS(NS_DOCUMENT_URI, node.nodeName, attributes)
        self.endElementNS(NS_DOCUMENT_URI, node.nodeName)
from Products.SilvaDocument.i18n import translate as _

code = context.get_code_object()

if not code:
    return '<span class="warning">[' + unicode(_('Code element is broken')) + ']</span>'

ret = code()
if not same_type(ret, u''):
    encoding = context.service_old_codesource_charset.charset()
    ret = unicode(ret, encoding, 'replace')

return ret
Ejemplo n.º 9
0
class Document(VersionedContent):
    __doc__ = _(
    """A Document is the basic unit of information in Silva. A document
        can &#8211; much like word processor documents &#8211; contain text,
        lists, tables, headers, subheads, images, etc. Documents can have
        two accessible versions, one online for the public, another in
        process (editable or approved/published). Older versions can be rolled
        forward and made editable.
    """)
    security = ClassSecurityInfo()

    meta_type = "Obsolete Document"

    grok.implements(IDocument)

    silvaconf.icon('www/silvadoc.gif')
    silvaconf.version_class(DocumentVersion)

    # ACCESSORS
    security.declareProtected(SilvaPermissions.View, 'is_cacheable')
    def is_cacheable(self):
        """Return true if this document is cacheable.
        That means the document contains no dynamic elements like
        code, datasource or toc.
        """
        non_cacheable_elements = ['code',]

        viewable = self.get_viewable()
        if viewable is None:
            return 0

        # It should suffice to test the children of the root element only,
        # since currently the only non-cacheable elements are root elements
        for node in viewable.content.documentElement.childNodes:
            node_name = node.nodeName
            if node_name in non_cacheable_elements:
                return 0
            # FIXME: how can we make this more generic as it is very
            # specific now..?
            if node_name == 'source':
                is_cacheable = externalsource.isSourceCacheable(
                    self.aq_inner, node)
                if not is_cacheable:
                    return 0
        return 1

    # Kupu save doing a PUT
    security.declareProtected(
        SilvaPermissions.ChangeSilvaContent, 'PUT')
    def PUT(self, REQUEST=None, RESPONSE=None):
        """PUT support"""
        # XXX we may want to make this more modular/pluggable at some point
        # to allow more content-types (+ transformations)
        if REQUEST is None:
            REQUEST = self.REQUEST
        if RESPONSE is None:
            RESPONSE = REQUEST.RESPONSE
        editable = self.get_editable()
        if editable is None:
            raise InternalError('No editable version available')
        content = REQUEST['BODYFILE'].read()
        content_type = self._get_content_type_from_request(REQUEST, content)
        if content_type not in ['text/html', 'application/xhtml+xml']:
            raise InternalError('Input format not supported')
        editable.set_document_xml_from(content, request=REQUEST)

    def _get_content_type_from_request(self, request, content):
        """tries to figure out the content type of a PUT body from a request

            the request may not have a content-type header available, if so
            we should use the contents itself to determine the content type
        """
        content_type = request.get_header('content-type')
        if content_type is not None:
            return content_type.split(';')[0]
        content = re.sub('<?.*?>', '', content).strip()
        if content.startswith('<html') or content.startswith('<!DOCTYPE html'):
            return 'text/html'
        return 'application/x-silva-document-xml'
    node.removeAttribute('id')
    return

if node.getAttribute('id') != id:
    # is changed, so remove all attrs.
    node.setAttribute('id', ustr(id))

# Use Document's context. If not, the complete widgets hierarchy comes
# in play and weird acquisition magic may cause 'source' to be a widget 
# whenever the source object has a widget's id.
doc = node.get_silva_object()
source = getSourceForId(doc, id)
if source is None:
    # should not happen since id was selected from a list...
    # or should we silently ignore this?
    raise ValueError, _('Source is a NoneType - is it not available anymore?')

form = source.form()
try:
    result = form.validate_all_to_request(request)    
except (FormValidationError, ValidationError), errs:
    pass
else:
    removeParameterElements(node)
    for field in form.get_fields():
        param = node.createElement('parameter')
        param.setAttribute('key', ustr(field.id))
        node.appendChild(param)
        vtype = 'string'
        value = result[field.id]
        if same_type(value, []):
## Script (Python) "content"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=
##
from Products.SilvaDocument.i18n import translate as _

code = context.get_code_object()

if not code:
    return '<span class="warning">[' + unicode(_('Code element is broken')) + ']</span>'

# this is also done in get_code(), but I need to get to path:
node = context.REQUEST.node
path = node.getAttribute('path')

message = _('Code element: ${title_or_id} at ${path}',
            mapping={'title_or_id': code.title_or_id(), 'path': path})

return  message