Пример #1
0
 def __init__(self, site_path, base_path='/images'):
     ResolveUIDAndCaptionFilter.__init__(self)
     self.atag = None
     self.abuffer = []
     self.items = []
     self.site_path = site_path
     self.base_path = base_path
 def __init__(self, target='images', sourcedomain=''):
     ResolveUIDAndCaptionFilter.__init__(self)
     # self.atag = None
     # self.abuffer = []
     self.items = []
     self.target = target
     self.sourcedomain = sourcedomain
Пример #3
0
 def unknown_endtag(self, tag):
     if tag == 'a':
         attrs = self.atag.items()
         self.atag = None
         self.append_tag('a', attrs)
         self.pieces.extend(self.abuffer)
         self.abuffer = []
     return ResolveUIDAndCaptionFilter.unknown_endtag(self, tag)
Пример #4
0
def fix_hrefs(tree, context):
    """Resolve any resolveuid links, and fixup internal links."""
    resolver = ResolveUIDAndCaptionFilter(context)
    for el in tree.findall('.//a'):
        href = el.get('href')
        if href:
            obj, subpath, appendix = resolver.resolve_link(href)
            if obj:
                href = obj_url(obj)
                if subpath:
                    href += subpath
                if appendix:
                    href += appendix
                el.set('href', href)
            else:
                new_url = transform_url(href)
                if new_url and new_url != href:
                    el.set('href', new_url)
Пример #5
0
    def get_login_message(self):
        nav_root = api.portal.get_navigation_root(self.context)
        login_message_page = getattr(nav_root, 'login-message', None)
        if not login_message_page or not login_message_page.text:
            return u''

        login_message = login_message_page.text.raw
        login_message = login_message.replace('http://resolveuid/',
                                              'resolveuid/')
        parser = ResolveUIDAndCaptionFilter(login_message_page)
        transform_text = parser(login_message)
        # return login_message_page.absolute_url()
        return transform_text
Пример #6
0
    def get_field(self, contact, field_name):
        if field_name is "id":
            return getattr(contact, field_name, "")
        if field_name not in self.selected_fields:
            return ""
        if field_name in self.address_fields:
            contactable = IContactable(contact)
            details = contactable.get_contact_details()
            return details["address"].get(field_name)
        # field = getattr(contact, field_name, '')
        # find way to check if field is richetext or image or simple field
        if getattr(getattr(contact, field_name, ""), "raw", None):
            if getattr(contact, field_name, ""):
                text = getattr(contact, field_name).raw
                text = text.replace("http://resolveuid/", "resolveuid/")
                parser = ResolveUIDAndCaptionFilter(contact)
                transform_text = parser(text)
                return transform_text if transform_text else ""
        if field_name in ["logo", "photo"]:
            if getattr(contact, field_name, ""):
                img = contact.unrestrictedTraverse("@@images")
                logo = img.scale(field_name)
                return logo.tag() if logo.tag() else ""
        if field_name == "schedule":
            from plone.directives import dexterity

            display = dexterity.DisplayForm(contact, self.request)
            display.update()
            if display.w.get("IScheduledContent.schedule", None):
                return display.w.get("IScheduledContent.schedule").render()
            else:
                return ""
        if field_name in ["phone", "cell_phone", "fax"]:
            phones = getattr(contact, field_name, "")
            if not phones:
                return False
            if not isinstance(phones, list):
                phones = [getattr(contact, field_name)]
            return [format_phone(phone) for phone in phones]
        if field_name in ["position"]:
            positions = [pos.title.strip() for pos in contact.get_held_positions()]
            return ", ".join(positions)
        return getattr(contact, field_name, "")
Пример #7
0
def imagesToPath(context, xhtmlContent, pretty_print=False):
    '''Turn <img> source contained in given p_xhtmlContent to a FileSystem absolute path
       to the .blob binary stored on the server.  This is usefull when generating documents
       with XHTML containing images that are private, LibreOffice is not able to access these
       images using the HTTP request.
       <img src='http://mysite/myfolder/myimage.png' /> becomes
       <img src='/absolute/path/to/blobstorage/myfile.blob'/>,
       external images are left unchanged.
       The image_scale is not kept, so :
       <img src='http://mysite/myfolder/myimage.png/image_preview' /> becomes
       <img src='/absolute/path/to/blobstorage/myfile.blob'/>.'''
    # keep original xhtmlContent in case we need to return it without changes
    originalXhtmlContent = xhtmlContent

    if not originalXhtmlContent or not originalXhtmlContent.strip():
        return originalXhtmlContent

    # if using resolveuid, turn src to real image path
    if 'resolveuid' in xhtmlContent:
        xhtmlContent = ResolveUIDAndCaptionFilter()(xhtmlContent)

    xhtmlContent = "<special_tag>%s</special_tag>" % xhtmlContent
    tree = lxml.html.fromstring(safe_unicode(xhtmlContent))
    imgs = tree.findall('.//img')
    if not imgs:
        return originalXhtmlContent

    portal = api.portal.get()
    portal_url = portal.absolute_url()
    for img in imgs:
        # check if it is a local or an external image
        img_src = img.attrib.get('src', None)
        # wrong <img> without src or external image
        if not img_src or (img_src.startswith('http')
                           and not img_src.startswith(portal_url)):
            continue
        # here, we have an image contained in the portal
        # either absolute path (http://...) or relative (../images/myimage.png)
        imageObj = None
        # absolute path
        if img_src.startswith(portal_url):
            img_src = img_src.replace(portal_url, '')
            try:
                # get the image but remove leading '/'
                imageObj = portal.unrestrictedTraverse(img_src[1:])
            except (KeyError, AttributeError, NotFound):
                continue
        # relative path
        else:
            try:
                imageObj = context.unrestrictedTraverse(img_src)
            # in case we have a wrong resolveuid/unknown_uid, it raises NotFound
            except (KeyError, AttributeError, NotFound):
                continue
        # maybe we have a ImageScale instead of the real Image object?
        if isinstance(imageObj, ImageScale):
            imageObj = imageObj.aq_inner.aq_parent
        blob_path = None
        # be defensinve in case this is a wrong <img> with a src to someting else than an image...
        if hasattr(aq_base(imageObj),
                   'getBlobWrapper') and imageObj.get_size():
            blob_path = imageObj.getBlobWrapper().blob._p_blob_committed
        # change img src only if a blob_path was found
        if blob_path:
            img.attrib['src'] = blob_path

    # use encoding to 'ascii' so HTML entities are translated to something readable
    return ''.join([
        lxml.html.tostring(x,
                           encoding='ascii',
                           pretty_print=pretty_print,
                           method='html') for x in tree.iterchildren()
    ])
 def _makeParser(self, **kw):
     parser = ResolveUIDAndCaptionFilter(context=self.portal)
     for k, v in kw.items():
         setattr(parser, k, v)
     return parser
Пример #9
0
def split_images(imgs, before_anchor=None, after_anchor=None, context=None):
    """Convert img elements into data to be used in photo components"""
    resolver = ResolveUIDAndCaptionFilter(context)
    before_parts = []
    after_parts = []
    before_images = []
    after_images = []
    for img in imgs:
        insert_before = True
        src = img.get('src')
        if not src:
            continue
        image, fullimage, src, description = resolver.resolve_image(src)
        parent = img.getparent()

        # image is only moved after if it is he last element in parent
        tail = img.tail and img.tail.strip()
        if not tail and img.getnext() is None:
            insert_before = False

        # Prepend any text attached after the image to the next
        # sibling text/tail. If there's no next sibling, it will be
        # appended to the previous sibling tail. If there's no previous
        # Sibling it's appended to the parent text.
        # We move all images with tail text before the current elemet and all
        # without after. It's not ideal, but it should behave reasonably for
        # reasonable markup.
        elif tail:
            nxt = img.getnext()
            prev = img.getprevious()
            if nxt is not None and nxt.tag not in {'img', 'code', 'pre'}:
                prefix = ''
                text = (nxt.text or '').lstrip()
                if text != nxt.text:
                    prefix = ' '
                nxt.text = prefix + img.tail.rstrip() + ' ' + text
            elif prev is not None:
                tail = (prev.tail or '').rstrip()
                prev.tail = tail + ' ' + img.tail.lstrip()
            else:
                text = (parent.text or '').rstrip()
                parent.text = text + ' ' + img.tail.lstrip()
        parent.remove(img)
        data = {
            'image': image,
            'fullimage': fullimage,
            'src': src,
            'description': description,
            'classes': img.get('class', '').split(' ')
        }

        if insert_before:
            if before_anchor:
                data['anchor'] = before_anchor
            before_images.append(data)
        else:
            if after_anchor:
                data['anchor'] = after_anchor
            after_images.append(data)

    if before_images:
        before_parts = [{'type': 'body_images', 'contents': before_images}]
    if after_images:
        after_parts = [{'type': 'body_images', 'contents': after_images}]

    return before_parts, after_parts