Exemplo n.º 1
0
 def _convertPath(self, path):
     """if it's not an absolute url, run it through the
       IPath adapter on the REQUEST to take into account
       virtual hosting situations"""
     if urlparse(path)[0]:
         return path
     pad = IPath(self.context.REQUEST)
     return pad.pathToUrlPath(path)
Exemplo n.º 2
0
 def _convertPath(self, path):
     """if it's not an absolute url, run it through the
       IPath adapter on the REQUEST to take into account
       virtual hosting situations"""
     if urlparse(path)[0]:
         return path
     pad = IPath(self.context.REQUEST)
     return pad.pathToUrlPath(path)
 def test_request_urlToPath(self):
     path_adapter = IPath(self.request)
     utp = path_adapter.urlToPath
     self.assertEquals(
         utp('index'),
         'index')
     self.assertEquals(
         utp('folder/index'),
         'folder/index')
     self.assertEquals(
         utp('folder/index#anchor'),
         'folder/index#anchor')
     self.assertEquals(
         utp('/index'),
         '/root/folder/index')
     self.assertEquals(
         utp('/index?p=b'),
         '/root/folder/index?p=b')
     self.assertEquals(
         utp('/index#anchor'),
         '/root/folder/index#anchor')
     self.assertEquals(
         utp('/index?p=b#anchor'),
         '/root/folder/index?p=b#anchor')
     self.assertEquals(
         utp('http://example.com:80/index'),
         '/root/folder/index')
     self.assertEquals(
         utp('http://example.com:80/index#anchor'),
         '/root/folder/index#anchor')
     self.assertEquals(
         utp('tel:+31 10 2140440'),
         'tel:+31 10 2140440')
    def test_request_pathToUrlPath(self):
        path_adapter = IPath(self.request)
        ptu = path_adapter.pathToUrlPath
        self.assertEquals(
            ptu('folder'),
            'folder')
        self.assertEquals(
            ptu('index'),
            'index')
        self.assertEquals(
            ptu('index#anchor'),
            'index#anchor')
        self.assertEquals(
            ptu('/root/folder/index'),
            '/index')
        self.assertEquals(
            ptu('/root/folder/index#anchor'),
            '/index#anchor')

        # If you give a valid URL it should not be touched
        self.assertEquals(
            ptu('http://somewhere.com:80/index#anchor'),
            'http://somewhere.com:80/index#anchor')
        self.assertEquals(
            ptu('http://example.com:80/index#anchor'),
            'http://example.com:80/index#anchor')
        self.assertEquals(
            ptu('tel:+31 10 2140440'),
            'tel:+31 10 2140440')
Exemplo n.º 5
0
    def convert(self, context):
        title = self.getattr('title', None)
        target = self.getattr('target', None)
        anchor = self.getattr('anchor', None)

        if self.hasattr('reference'):
            # We have a reference
            reference_name = str(self.getattr('reference'))
            reference_name, reference = context.get_reference(
                reference_name, read_only=True)
            assert reference is not None, "Invalid reference"
            attributes = {
                'href': 'reference',
                'title': title,
                'target': target,
                '_silva_anchor': anchor,
                '_silva_target': reference.target_id,
                '_silva_reference': reference_name}
            if not reference.target_id:
                attributes['class'] = 'broken-link'
            return html.a(
                self.content.convert(context),
                **attributes)

        path = ''
        if self.hasattr('url'):
            url = self.getattr('url')
            path = IPath(context.request).pathToUrlPath(str(url))
        return html.a(
            self.content.convert(context),
            href=path,
            title=title,
            target=target,
            _silva_href=path,
            _silva_anchor=anchor)
Exemplo n.º 6
0
    def sax_node(self, node):
        """Export child nodes of a (version of a) Silva Document to XML
        """
        attributes = {}
        if node.attributes:
            attributes = get_dict(node.attributes)
        if node.nodeName == 'source':
            self.sax_source(node)
        elif node.nodeName == 'table':
            self.sax_table(node)
        elif node.nodeName == 'image':
            self.sax_img(node)
        else:
            if node.nodeName == 'link':
                options = self.getOptions()
                if options.external_rendering:
                    href = ''
                    if 'reference' in attributes:
                        service = getUtility(IReferenceService)
                        reference = service.get_reference(
                            self.context, name=attributes['reference'])
                        if options.upgrade30:
                            attributes['data-silva-target'] = str(reference.target_id)
                            attributes['data-silva-reference'] = reference.tags[1]
                            reference.tags[0] = u"body link"
                            reference._p_changed = True
                        else:
                            target = reference.target
                            if target is not None:
                                href = absoluteURL(
                                    reference.target,
                                    self.getExported().request)
                            else:
                                attributes['class'] = 'broken-link'
                    elif 'url' in attributes:
                        if options.upgrade30:
                            attributes['data-silva-url'] = attributes['url']
                        else:
                            document = self.context.get_content()
                            href = IPath(document).pathToUrlPath(attributes['url'])

                    anchor = attributes.get('anchor', '')
                    if anchor:
                        if options.upgrade30:
                            attributes['data-silva-anchor'] = anchor
                        else:
                            href += '#' + anchor
                    attributes['href'] = href
                else:
                    if 'reference' in attributes:
                        attributes['reference'] = self.get_reference(
                            attributes['reference'])

            self.startElementNS(NS_DOCUMENT_URI, node.nodeName, attributes)
            if node.hasChildNodes():
                self.sax_children(node)
            elif node.nodeValue:
                self.handler.characters(node.nodeValue)
            self.endElementNS(NS_DOCUMENT_URI, node.nodeName)
    def test_silva_pathToUrlPath(self):
        # test the ISilvaObject SilvaPathAdapter, which converts
        # the url attribute of silvaxml <link> tags to href= values.
        # in some circumstances, the IHTTPRequest IPath adapter will
        # be used to finalize the url of an absolute or relative path
        path_adapter = IPath(self.document)
        ptup = path_adapter.pathToUrlPath

        self.assertEquals(
            ptup("mailto:f.o'*****@*****.**"),
            "mailto:f.o'*****@*****.**")
        self.assertEquals(
            ptup('tel:+31 10 2140440'),
            'tel:+31 10 2140440')
Exemplo n.º 8
0
    def convert(self, context):
        image = None
        attributes = {'alignment': self.getattr('alignment', 'default'),
                      'alt': self.getattr('title', '')}

        if self.hasattr('reference'):
            # We have a reference
            reference_name = str(self.getattr('reference'))
            reference_name, reference = context.get_reference(
                reference_name, read_only=True)
            assert reference is not None, "Invalid reference"
            attributes['_silva_target'] = reference.target_id
            attributes['_silva_reference'] = reference_name
            image = reference.target
            if image is not None:
                attributes['src'] = absoluteURL(image, context.request)
            else:
                site = IVirtualSite(context.request)
                attributes['src'] = site.get_root_url() + \
                    "/++resource++Products.SilvaDocument/broken-link.jpg"
                attributes['alt'] = u'Referenced image is missing.'
        elif self.hasattr('path'):
            path = self.getattr('path')
            src = IPath(context.request).pathToUrlPath(str(path))
            attributes['src'] = src
            try:
                image = context.model.unrestrictedTraverse(src.split('/'))
            except:
                pass
        else:
            raise ValueError('Invalid silva image tag')

        if image and IImage.providedBy(image):
            attributes['width'], attributes['height'] = \
                image.get_dimensions(image.image)

        return html.img(self.content.convert(context), **attributes)
Exemplo n.º 9
0
   def convert(self, context):
       if hasattr(self, 'should_be_removed') and self.should_be_removed:
           return Frag()

       title = self.getattr('alt', '')
       alignment = self.getattr('alignment', 'default')
       if alignment == 'default':
           alignment = ''

       if self.hasattr('_silva_reference'):
           reference_name = str(self.getattr('_silva_reference'))
           reference_name, reference = context.get_reference(reference_name)
           if reference is not None:
               target_id = self.getattr('_silva_target', '0')
               try:
                   target_id = int(str(target_id))
               except ValueError:
                   target_id = 0
           else:
               reference_name, reference = context.get_reference('new')
               target_id = 0

           # The target changed, update it
           if target_id != reference.target_id:
               reference.set_target_id(target_id)

           return silva.image(
               self.content.convert(context),
               reference=reference_name,
               alignment=alignment,
               title=title)

       # This is an old url-based image link
       src = getattr(self.attr, 'src', None)
       if src is None:
           src = 'unknown'
       elif hasattr(src, 'content'):
           src = src.content
       src = urlparse(str(src))[2]
       src = IPath(context.request).urlToPath(str(src))
       if src.endswith('/image'):
           src = src[:-len('/image')]
       # turn path into relative if possible, traverse to the object to
       # fix an IE problem that adds the current location in front of paths
       # in an attempt to make them absolute, which leads to nasty paths
       # such as '/silva/index/edit/index/edit/foo.jpg'
       try:
           obj = context.model.unrestrictedTraverse(src.split('/'))
           # bail out if obj is not a Silva Image, otherwise the old
           # href value would be lost
           if not IImage.providedBy(obj):
               raise NotFound(src)
       except (KeyError, NotFound):
           pass
       else:
           modelpath = context.model.aq_parent.getPhysicalPath()
           src = '/'.join(Path(modelpath, obj.getPhysicalPath()))

       return silva.image(
           self.content.convert(context),
           path=src,
           alignment=alignment,
           title=title)
Exemplo n.º 10
0
    def convert(self, context):
        title = self.getattr('title', default='')
        name = self.getattr('name', default=None)
        href = self.getattr('href', default='#')
        anchor = self.getattr('_silva_anchor', default=None)
        window_target = self.getattr('target', default='')

        link_attributes = {'target': window_target,
                           'title': title,
                           'anchor': anchor}

        if name is not None and href == '#':
            # Case one, we are an anchor
            if self.getattr('class', None) == 'index':
                # index item
                text = ''.join([t.convert(context).asBytes('UTF-8') for
                                t in extract_texts(self, context)])
                textnode = Frag()
                if text and (text[0] != '[' or text[-1] != ']'):
                    textnode = Text(text)
                return Frag(
                    textnode,
                    silva.index(name=name, title=title))
            else:
                # named anchor, probably pasted from some other page
                return Frag(self.content.convert(context))
        elif self.hasattr('_silva_reference'):
            # Case of a Silva reference used
            reference_name = str(self.getattr('_silva_reference'))
            reference_name, reference = context.get_reference(reference_name)
            if reference is not None:
                target_id = self.getattr('_silva_target', '0')
                try:
                    target_id = int(str(target_id))
                    assert get_content_from_id(target_id) is not None
                except (ValueError, AssertionError):
                    # Invalid target id, set it as zero (broken)
                    target_id = 0
            else:
                # Invalid reference. We create a new one and mark the
                # target as broken
                reference_name, reference = context.get_reference('new')
                target_id = 0

            # If the target changed, update it
            if target_id != reference.target_id:
                reference.set_target_id(target_id)
            link_attributes['reference'] = reference_name
            return silva.link(
                self.content.convert(context),
                **link_attributes)
        elif self.hasattr('href'):
            # External links
            url = self.getattr('_silva_href', None)
            if url is None:
                url = self.getattr('href', '')
            if unicode(url).startswith('/'):
                # convert to physical path before storing
                url = Text(IPath(context.request).urlToPath(unicode(url)))
            if url:
                link_attributes['url'] = url
            return silva.link(
                self.content.convert(context),
                **link_attributes)
        elif anchor is not None:
            # Link to an anchor on the same page
            return silva.link(
                self.content.convert(context),
                **link_attributes)
        else:
            return Frag()
Exemplo n.º 11
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)