示例#1
0
    def set(self, instance, value, **kwargs):
        """ Assign input value to object. If mimetype is not specified,
        pass to processing method without one and add mimetype
        returned to kwargs. Assign kwargs to instance.
        """
        if value is None:
            # nothing to do
            return

        TextField.set(self, instance, value, **kwargs)

        if isinstance(value, BaseUnit):
            # Baseunit: can occur when overriding atct text fields.
            value = value()
        if not isinstance(value, basestring):
            value.seek(0)
            value = value.read()

        # build list of uids from the value here
        uids = [m.group('uid') for m in UID_PATTERN.finditer(value)]
        uids = dict.fromkeys(uids).keys()  # Remove duplicate uids.

        tool = getToolByName(instance, REFERENCE_CATALOG)

        relationship = self.relationship
        if relationship is None:
            relationship = self.__name__

        targetUIDs = [
            ref.targetUID
            for ref in tool.getReferences(instance, relationship)
        ]

        add = [v for v in uids if v and v not in targetUIDs]
        sub = [t for t in targetUIDs if t not in uids]

        # tweak keyword arguments for addReference
        addRef_kw = kwargs.copy()
        addRef_kw.setdefault('referenceClass', self.referenceClass)
        if addRef_kw.has_key('schema'): del addRef_kw['schema']

        for uid in add:
            __traceback_info__ = (instance, uid, value, targetUIDs)
            try:
                # throws ReferenceException if uid is invalid
                tool.addReference(instance, uid, relationship, **addRef_kw)
            except ReferenceException:
                pass
        for uid in sub:
            tool.deleteReference(instance, uid, relationship)
示例#2
0
    def set(self, instance, value, **kwargs):
        """ Assign input value to object. If mimetype is not specified,
        pass to processing method without one and add mimetype
        returned to kwargs. Assign kwargs to instance.
        """
        if value is None:
            # nothing to do
            return

        TextField.set(self, instance, value, **kwargs)

        if isinstance(value, BaseUnit):
            # Baseunit: can occur when overriding atct text fields.
            value = value()
        if not isinstance(value, basestring):
            value.seek(0);
            value = value.read()

        # build list of uids from the value here
        uids = [ m.group('uid') for m in UID_PATTERN.finditer(value) ]
        uids = dict.fromkeys(uids).keys() # Remove duplicate uids.

        tool = getToolByName(instance, REFERENCE_CATALOG)

        relationship = self.relationship
        if relationship is None:
            relationship = self.__name__

        targetUIDs = [ref.targetUID for ref in
                      tool.getReferences(instance, relationship)]

        add = [v for v in uids if v and v not in targetUIDs]
        sub = [t for t in targetUIDs if t not in uids]

        # tweak keyword arguments for addReference
        addRef_kw = kwargs.copy()
        addRef_kw.setdefault('referenceClass', self.referenceClass)
        if addRef_kw.has_key('schema'): del addRef_kw['schema']

        for uid in add:
            __traceback_info__ = (instance, uid, value, targetUIDs)
            try:
                # throws ReferenceException if uid is invalid
                tool.addReference(instance, uid, relationship, **addRef_kw)
            except ReferenceException:
                pass
        for uid in sub:
            tool.deleteReference(instance, uid, relationship)
示例#3
0
    def convert(self, data, idata, filename=None, **kwargs):
        """convert the data, store the result in idata and return that
        optional argument filename may give the original file name of received data
        additional arguments given to engine's convert, convertTo or __call__ are
        passed back to the transform
        
        The object on which the translation was invoked is available as context
        (default: None)
        """
        context = kwargs.get('context', None)
        template = context.kupu_captioned_image
        if context:
            at_tool = context.archetype_tool
            rc = at_tool.reference_catalog

        if context and at_tool:        
            def replaceImage(match):
                tag = match.group('pat0') or match.group('pat1')
                attrs = ATTR_PATTERN.match(tag)
                atag = match.group('atag0') or match.group('atag1')
                src = attrs.group('src')
                subtarget = None
                m = SRC_TAIL.match(tag, attrs.end('src'))
                if m:
                    srctail = m.group(1)
                else:
                    srctail = None
                if src:
                    d = attrs.groupdict()
                    target = self.resolveuid(context, rc, src)
                    if target:
                        d['class'] = attrs.group('class')
                        d['originalwidth'] = attrs.group('width')
                        d['originalalt'] = attrs.group('alt')
                        d['url_path'] = target.absolute_url_path()
                        #d['caption'] = newline_to_br(html_quote(target.Description()))
                        ##get licenseinfo here
                        license = target.restrictedTraverse('@@copyright_byline_view').getLicenseByline()
                        licenseinfo = ''
                        if license[2] != 'All Rights Reserved':
                            licenseinfo += 'Image: %s, <a href="%s" title="%s" alt="%s">%s</a>.' % (license[1], license[3],license[2],license[2],license[2])
                        else:
                            licenseinfo += 'Image: %s, %s.' % (license[1], license[2])

                        d['caption'] = licenseinfo


                        d['image'] = d['fullimage'] = target
                        d['tag'] = None
                        d['isfullsize'] = True
                        d['width'] = target.width
                        if srctail:
                            if isinstance(srctail, unicode):
                                srctail =srctail.encode('utf8') # restrictedTraverse doesn't accept unicode
                            try:
                                subtarget = target.restrictedTraverse(srctail)
                            except:
                                subtarget = getattr(target, srctail, None)
                            if subtarget:
                                d['image'] = subtarget

                            if srctail.startswith('image_'):
                                d['tag'] = target.getField('image').tag(target, scale=srctail[6:])
                            elif subtarget:
                                d['tag'] = subtarget.tag()

                        if d['tag'] is None:
                            d['tag'] = target.tag()

                            if d['originalwidth'] is None:
                                #create relative url based tag
                                url = makeUrlRelative(target.absolute_url(),context.absolute_url())[0]
                                d['tag'] = '<img src="%s" alt="%s" height="%s" width="%s" />' % (url, d['originalalt'], target.height, target.width )


                        if subtarget:
                            d['isfullsize'] = subtarget.width == target.width and subtarget.height == target.height
                            d['width'] = subtarget.width

                        if atag: # Must preserve original link, don't overwrite with a link to the image
                            d['isfullsize'] = True
                            d['tag'] = "%s%s</a>" % (atag, d['tag'])

                        return template(**d)
                return match.group(0) # No change

            if isinstance(data, unicode):
                data = data.decode('utf8')
            html = IMAGE_PATTERN.sub(replaceImage, data)

            # Replace urls that use UIDs with human friendly urls.
            def replaceUids(match):
                tag = match.group('tag')
                uid = match.group('uid')
                target = self.resolveuid(context, rc, uid)
                if target:
                    try:
                        url = target.getRemoteUrl()
                    except AttributeError:
                        url = target.absolute_url_path()
                    return tag + url
                return match.group(0)

            html = UID_PATTERN.sub(replaceUids, html)
            if isinstance(html, unicode):
                html = html.encode('utf8') # Indexing requires a string result.
            idata.setData(html)
            return idata

        # No context to use for replacements, so don't bother trying.
        idata.setData(data)
        return idata
示例#4
0
    def convert(self, data, idata, filename=None, **kwargs):
        """convert the data, store the result in idata and return that
        optional argument filename may give the original file name of received data
        additional arguments given to engine's convert, convertTo or __call__ are
        passed back to the transform
        
        The object on which the translation was invoked is available as context
        (default: None)
        """
        context = kwargs.get('context', None)
        at_tool = None
        template = context.kupu_captioned_image
        if context is not None:
            at_tool = context.archetype_tool
            rc = at_tool.reference_catalog

        if context is not None and at_tool is not None:
            def replaceImage(match):
                tag = match.group('pat0') or match.group('pat1')
                attrs = ATTR_PATTERN.match(tag)
                atag = match.group('atag0') or match.group('atag1')
                src = attrs.group('src')
                subtarget = None
                m = SRC_TAIL.match(tag, attrs.end('src'))
                if m is not None:
                    srctail = m.group(1)
                else:
                    srctail = None
                if src is not None:
                    d = attrs.groupdict()
                    target = self.resolveuid(context, rc, src)
                    if target is not None:
                        d['class'] = attrs.group('class')
                        d['originalwidth'] = attrs.group('width')
                        d['originalalt'] = attrs.group('alt')
                        d['url_path'] = target.absolute_url_path()
                        d['caption'] = newline_to_br(html_quote(target.Description()))
                        d['image'] = d['fullimage'] = target
                        d['tag'] = None
                        d['isfullsize'] = True
                        d['width'] = target.width
                        if srctail:
                            if isinstance(srctail, unicode):
                                srctail =srctail.encode('utf8') # restrictedTraverse doesn't accept unicode
                            try:
                                subtarget = target.restrictedTraverse(srctail)
                            except:
                                subtarget = getattr(target, srctail, None)
                            if subtarget is not None:
                                d['image'] = subtarget

                            if srctail.startswith('image_'):
                                d['tag'] = target.getField('image').tag(target, scale=srctail[6:])
                            elif subtarget:
                                d['tag'] = subtarget.tag()

                        if d['tag'] is None:
                            d['tag'] = target.tag()

                        if subtarget is not None:
                            d['isfullsize'] = subtarget.width == target.width and subtarget.height == target.height
                            d['width'] = subtarget.width

                        # strings that may contain non-ascii characters need to be decoded to unicode
                        for key in ('caption', 'tag'):
                            if isinstance(d[key], str):
                                d[key] = d[key].decode('utf8', 'replace')

                        if atag is not None: # Must preserve original link, don't overwrite with a link to the image
                            d['isfullsize'] = True
                            d['tag'] = "%s%s</a>" % (atag, d['tag'])

                        result = template(**d)
                        if isinstance(result, str):
                            result = result.decode('utf8')

                        return result

                return match.group(0) # No change

            if isinstance(data, str):
                # Transform for end user output should avoid erroring
                # if it can, so use 'replace' on decode.
                data = data.decode('utf8', 'replace')
            html = IMAGE_PATTERN.sub(replaceImage, data)

            # Replace urls that use UIDs with human friendly urls.
            def replaceUids(match):
                tag = match.group('tag')
                uid = match.group('uid')
                target = self.resolveuid(context, rc, uid)
                if target is not None:
                    if getattr(aq_base(target), 'getRemoteUrl', None) is not None:
                        url = target.getRemoteUrl()
                    else:
                        url = target.absolute_url_path()
                    return tag + url
                return match.group(0)

            html = UID_PATTERN.sub(replaceUids, html)
            if isinstance(html, unicode):
                html = html.encode('utf8') # Indexing requires a string result.
            idata.setData(html)
            return idata

        # No context to use for replacements, so don't bother trying.
        idata.setData(data)
        return idata