Beispiel #1
0
 def get_remote_url(self):
     """
     Resolve uid and return ref absolute url
     """
     if ILink.providedBy(self.context):
         value = getattr(self.context, "remoteUrl", "")
     else:
         value = self.context.getRemoteUrl
     if not value:
         return ""
     if value.startswith("http"):
         # it isn't an internal link, so we can return it
         return value
     path = replace_link_variables_by_paths(context=self.context, url=value)
     match = RESOLVEUID_RE.match(path)
     if match:
         uid, suffix = match.groups()
         return uuidToURL(uid)
     else:
         portal = api.portal.get()
         try:
             ref_obj = portal.restrictedTraverse(path, None)
             if ref_obj:
                 return ref_obj.absolute_url()
         except Exception:
             return ""
     return ""
    def absolute_target_url(self, urlstring):
        """Compute the absolute target URL."""
        url = urlstring  # self.url(obj, attributename)

        if self._url_uses_scheme(NON_RESOLVABLE_URL_SCHEMES, url):
            return url

        if url.startswith('.'):
            # we just need to adapt ../relative/links, /absolute/ones work
            # anyway -> this requires relative links to start with ./ or
            # ../
            context_state = self.context.restrictedTraverse(
                '@@plone_context_state')
            url = '/'.join([context_state.canonical_object_url(), url])
        else:
            if not url.startswith(('http://', 'https://')):
                # url = self.request['SERVER_URL'] + url
                if 'resolveuid/' in url:
                    try:
                        uuid = url.split("resolveuid/")[1]
                        url = uuidToURL(uuid)
                    except Exception:
                        pass
                else:
                    url = api.portal.get().absolute_url() + url
        return url
Beispiel #3
0
    def __call__(self):
        value = copy.deepcopy(self.get_value())

        # Resolve UID links
        if self.field.getName() == "blocks":
            for block in value.values():
                if block.get("@type") == "text":
                    entity_map = block.get("text", {}).get("entityMap", {})
                    for entity in entity_map.values():
                        if entity.get("type") == "LINK":
                            href = entity.get("data", {}).get("url", "")
                            before = href  # noqa
                            if href:
                                match = RESOLVEUID_RE.match(href)
                                if match is not None:
                                    uid, suffix = match.groups()
                                    href = uuidToURL(uid)
                                    if href is None:
                                        continue
                                    if suffix:
                                        href += "/" + suffix
                                    entity["data"]["href"] = href
                                    entity["data"]["url"] = href
                                    print("SERIALIZE " + before + " -> " +
                                          href)  # noqa
        return json_compatible(value)
 def test_uuidToURL_permission(self):
     from plone.outputfilters.browser.resolveuid import uuidToURL
     from plone.outputfilters.browser.resolveuid import uuidToObject
     self.portal.invokeFactory('Document', id='page', title='Page')
     page = self.portal['page']
     self.logout()
     self.assertEqual('http://nohost/plone/page', uuidToURL(page.UID()))
     self.assertTrue(page.aq_base is uuidToObject(page.UID()).aq_base)
    def test_uuidToURL_permission(self):
        from plone.outputfilters.browser.resolveuid import uuidToURL
        from plone.outputfilters.browser.resolveuid import uuidToObject

        self.portal.invokeFactory("Document", id="page", title="Page")
        page = self.portal["page"]
        self.logout()
        self.assertEqual("http://nohost/plone/page", uuidToURL(page.UID()))
        self.assertTrue(page.aq_base is uuidToObject(page.UID()).aq_base)
Beispiel #6
0
    def __call__(self):
        if self.field.getName() != "remoteUrl":
            return super(TextLineFieldSerializer, self).__call__()
        value = self.get_value()

        path = replace_link_variables_by_paths(context=self.context, url=value)
        match = RESOLVEUID_RE.match(path)
        if match:
            uid, suffix = match.groups()
            value = uuidToURL(uid)
        else:
            portal = getMultiAdapter((self.context, self.context.REQUEST),
                                     name="plone_portal_state").portal()
            ref_obj = portal.restrictedTraverse(path, None)
            if ref_obj:
                value = ref_obj.absolute_url()

        return json_compatible(value)
 def get_remote_url(self):
     if ILink.providedBy(self.context):
         value = getattr(self.context, "remoteUrl", "")
     else:
         value = self.context.getRemoteUrl
     if not value:
         return ""
     path = replace_link_variables_by_paths(context=self.context, url=value)
     match = RESOLVEUID_RE.match(path)
     if match:
         uid, suffix = match.groups()
         return uuidToURL(uid)
     else:
         portal = getMultiAdapter(
             (self.context, self.context.REQUEST), name="plone_portal_state"
         ).portal()
         ref_obj = portal.restrictedTraverse(path, None)
         if ref_obj:
             return ref_obj.absolute_url()
     return value
Beispiel #8
0
def uid_to_url(path):
    if not path:
        return ""
    match = RESOLVEUID_RE.match(path)
    if match is None:
        return path

    uid, suffix = match.groups()
    href = uuidToURL(uid)
    if href is None:
        return path
    if suffix:
        href += "/" + suffix
    else:
        target_object = uuidToObject(uid)
        if target_object:
            adapter = queryMultiAdapter((target_object, target_object.REQUEST),
                                        IObjectPrimaryFieldTarget)
            if adapter and adapter():
                href = adapter()
    return href
Beispiel #9
0
def storeImagesLocally(context,
                       xhtmlContent,
                       imagePortalType='Image',
                       store_external_images=True,
                       store_internal_images=True,
                       pretty_print=False,
                       force_resolve_uid=False):
    """If images are found in the given p_xhtmlContent,
       we download it and stored it in p_context, this way we ensure that it will
       always be available in case the external/internal image image disappear.
       If p_store_external_images is True, we retrieve external image and store it
       in p_context, if p_store_internal_images is True, we do the same for internal
       images."""
    def _handle_internal_image(img_src):
        """ """
        # get image from URL
        img_path = img_src.replace(portal_url, '')
        img_path = path.join(portal.absolute_url_path(), img_path)
        # path can not start with a '/'
        img_path = img_path.lstrip('/')

        # right, traverse to image
        try:
            imageObj = portal.unrestrictedTraverse(img_path)
        except (KeyError, AttributeError):
            # wrong img_path
            logger.warning('In \'storeImagesLocally\', could not traverse '
                           'img_path \'{0}\' for \'{1}\'!'.format(
                               img_path, context.absolute_url()))
            return None, None

        # not an image
        if getattr(imageObj, 'portal_type', None) != 'Image':
            return None, None

        filename = imageObj.getId()
        data = imageObj.getBlobWrapper().data
        return filename, data

    def _handle_external_image(img_src):
        """ """
        # right, we have an external image, download it, stores it in context and update img_src
        try:
            downloaded_img_path, downloaded_img_infos = urllib.urlretrieve(
                img_src)
        except IOError:
            # url not existing
            return None, None

        # not an image
        if not downloaded_img_infos.maintype == 'image':
            return None, None

        # retrieve filename
        filename = 'image'
        disposition = downloaded_img_infos.getheader('Content-Disposition')
        # get real filename from 'Content-Disposition' if available
        if disposition:
            disp_value, disp_params = cgi.parse_header(disposition)
            filename = disp_params.get('filename', 'image')
        # if no 'Content-Disposition', at least try to get correct file extension
        elif hasattr(downloaded_img_infos, 'subtype'):
            filename = '{0}.{1}'.format(filename, downloaded_img_infos.subtype)
        f = open(downloaded_img_path, 'r')
        data = f.read()
        f.close()
        # close and delete temporary file
        if path.exists(downloaded_img_path):
            os.remove(downloaded_img_path)
        return filename, data

    tree = _turnToLxmlTree(xhtmlContent)
    if not isinstance(tree, lxml.html.HtmlElement):
        return xhtmlContent

    imgs = tree.findall('.//img')
    if not imgs:
        return xhtmlContent
    portal = api.portal.get()
    portal_url = portal.absolute_url()
    # make sure context_url ends with a '/' to avoid mismatch if folder holding the
    # image absolute_url starts with context_url
    context_url = context.absolute_url() + '/'
    # adapter to generate a valid id, it needs a container, so it will be context or it's parent
    try:
        name_chooser = INameChooser(context)
    except TypeError:
        parent = context.getParentNode()
        name_chooser = INameChooser(parent)
    # return received xhtmlContent if nothing was changed
    changed = False
    for img in imgs:
        original_img_src = img.get('src', '')

        # we only handle http stored images
        if not original_img_src.startswith(
                'http') and 'resolveuid' not in original_img_src:
            continue
        filename = data = None
        # external images
        if store_external_images and not original_img_src.startswith(portal_url) and \
           'resolveuid' not in original_img_src:
            filename, data = _handle_external_image(original_img_src)

        # image in portal but not already stored in context
        # handle images using resolveuid
        end_of_url = None
        img_src = original_img_src
        if 'resolveuid' in original_img_src:
            # manage cases like :
            # - resolveuid/2ff7ea3317df43438a09edfa84965b13
            # - resolveuid/2ff7ea3317df43438a09edfa84965b13/image_preview
            # - http://portal_url/resolveuid/2ff7ea3317df43438a09edfa84965b13
            img_uid = original_img_src.split('resolveuid/')[-1].split('/')[0]
            # save end of url if any, like /image_preview
            end_of_url = original_img_src.split(img_uid)[-1]
            if end_of_url == img_uid:
                end_of_url = None
            # if not found, like when copy/paste HTML code containing resolveuid, use '' instead None
            img_src = uuidToURL(img_uid) or ''

        if store_internal_images and \
           img_src.startswith(portal_url) and \
           not img_src.startswith(context_url):
            filename, data = _handle_internal_image(img_src)

        if not filename:
            continue
        changed = True

        # create image
        name = name_chooser.chooseName(filename, context)
        new_img_id = context.invokeFactory(imagePortalType,
                                           id=name,
                                           title=name,
                                           file=data)
        new_img = getattr(context, new_img_id)
        # store a resolveuid if using it, the absolute_url to image if not
        if force_resolve_uid or \
           original_img_src.startswith('resolveuid') or \
           (HAS_CKEDITOR and
                hasattr(portal.portal_properties, 'ckeditor_properties') and
                portal.portal_properties.ckeditor_properties.allow_link_byuid):
            new_img_src = 'resolveuid/{0}'.format(new_img.UID())
        else:
            new_img_src = new_img.absolute_url()
        if end_of_url:
            new_img_src = '/'.join([new_img_src, end_of_url.strip('/')])

        img.attrib['src'] = new_img_src

    if not changed:
        return xhtmlContent

    return ''.join([
        lxml.html.tostring(x,
                           encoding='utf-8',
                           pretty_print=pretty_print,
                           method='html') for x in tree.iterchildren()
    ])
 def __call__(self):
     return uuidToURL(self.uuid)
 def test_uuidToURL(self):
     from plone.outputfilters.browser.resolveuid import uuidToURL
     self.assertEqual('http://nohost/plone/image.jpg',
                      uuidToURL(self.UID))
 def test_uuidToURL(self):
     from plone.outputfilters.browser.resolveuid import uuidToURL
     self.assertEqual('http://nohost/plone/image.jpg', uuidToURL(self.UID))