示例#1
0
 def getImageSize(self, image_obj):
     if HAS_PAC:
         if (IImage.providedBy(image_obj) or IImage.providedBy(image_obj)):
             return image_obj.image.getImageSize()
     field = image_obj.getField('image')
     if field.type in ("blob", "file", "image"):
         return field.getSize(image_obj)
     elif field.type == "reference":
         return field.get(image_obj).getSize()
     else:
         raise ValueError("image field type unknown")
示例#2
0
 def getImageSize(self, image_obj):
     if HAS_PAC:
         if (
             IImage.providedBy(image_obj) or IImage.providedBy(image_obj)
         ):
             return image_obj.image.getImageSize()
     field = image_obj.getField('image')
     if field.type in ("blob", "file", "image"):
         return field.getSize(image_obj)
     elif field.type == "reference":
         return field.get(image_obj).getSize()
     else:
         raise ValueError("image field type unknown")
    def test_fix_interface_for_image(self):
        self.obj.portal_type = 'Image'
        self.catalog.reindexObject(self.obj)

        self.portal.restrictedTraverse('fix_base_classes')()

        self.assertTrue(IImage.providedBy(self.obj))
    def test_fix_interface_for_image(self):
        self.obj.portal_type = 'Image'
        self.catalog.reindexObject(self.obj)

        self.portal.restrictedTraverse('fix_base_classes')()

        self.assertTrue(IImage.providedBy(self.obj))
 def is_printable(self):
     if ILink.providedBy(self.context):
         return False
     if IFile.providedBy(self.context):
         return IIconifiedPreview(self.context).is_convertible()
     if IImage.providedBy(self.context):
         return True
     return True
示例#6
0
 def test_factory(self):
     fti = queryUtility(
         IDexterityFTI,
         name='Image'
     )
     factory = fti.factory
     new_object = createObject(factory)
     self.assertTrue(IImage.providedBy(new_object))
 def test_factory(self):
     fti = queryUtility(
         IDexterityFTI,
         name='Image'
     )
     factory = fti.factory
     new_object = createObject(factory)
     self.assertTrue(IImage.providedBy(new_object))
示例#8
0
 def preview_image(self, uid):
     images = self.contained_items(uid)
     preview = None
     if len(images):
         first_item = images[0].getObject()
         if IImage.providedBy(first_item):
             preview = first_item
     return preview
示例#9
0
 def fields(self):
     if IATBlobImage.providedBy(
             self.context) or (has_dx and IImage.providedBy(self.context)):
         fields = z3cfield.Fields(self.interface)
         fields['bannerImageLink'].widgetFactory = ContentTreeFieldWidget
     else:
         fields = z3cfield.Fields(self.interface).select(
             'bannerLocalOnly', 'bannerStopAcquisition')
     return fields
示例#10
0
 def test_image_is_migrated(self):
     from Products.ATContentTypes.content.image import ATImage
     from plone.app.contenttypes.migration.migration import ImageMigrator
     from plone.app.contenttypes.interfaces import IImage
     at_image = self.createATCTobject(ATImage, 'image')
     migrator = self.get_migrator(at_image, ImageMigrator)
     migrator.migrate()
     new_image = self.portal['image']
     self.assertTrue(IImage.providedBy(new_image))
     self.assertTrue(at_image is not new_image)
示例#11
0
 def attachable_objs(self):
     """
     We can only attach files. When implemented, we will also attach the PDF
     version of Documents
     """
     objs = []
     for obj in self.items:
         if IFile.providedBy(obj) or IImage.providedBy(obj):
             objs.append(obj)
     return objs
 def _download_url(self):
     """Return the download url (None by default) for the current object"""
     url = u'{url}/@@download'
     portal_url = api.portal.get_tool('portal_url')
     if IFile.providedBy(self.obj):
         return url.format(
             url=portal_url.getRelativeUrl(self.context))
     if IImage.providedBy(self.obj):
         return url.format(
             url=portal_url.getRelativeUrl(self.context))
示例#13
0
 def canLogo(self):
     if has_dx and (IDocument.providedBy(self.context)
                    or IImage.providedBy(self.context)):
         return True
     if hasattr(self.context, 'getText'):
         return True
     if hasattr(self.context, 'tag'):
         return True
     if self.context.portal_type == 'FlashMovie':
         return True
     return False
 def test_blob_image_is_migrated(self):
     from plone.app.contenttypes.migration.migration import\
         BlobImageMigrator
     from plone.app.contenttypes.interfaces import IImage
     self.portal.invokeFactory('Image', 'image')
     at_image = self.portal['image']
     applyProfile(self.portal, 'plone.app.contenttypes:default')
     migrator = self.get_migrator(at_image, BlobImageMigrator)
     migrator.migrate()
     dx_image = self.portal['image']
     self.assertTrue(IImage.providedBy(dx_image))
     self.assertTrue(at_image is not dx_image)
示例#15
0
 def _album_results(self):
     """Get results to display an album with subalbums.
     """
     results = self.results()
     images = []
     folders = []
     for it in results:
         # TODO: potentially expensive!
         ob = it.getObject()
         if IImage.providedBy(ob):
             images.append(it)
         elif IFolder.providedBy(ob):
             folders.append(it)
     return {'images': images, 'folders': folders}
 def _album_results(self):
     """Get results to display an album with subalbums.
     """
     results = self.results()
     images = []
     folders = []
     for it in results:
         # TODO: potentially expensive!
         ob = it.getObject()
         if IImage.providedBy(ob):
             images.append(it)
         elif IFolder.providedBy(ob):
             folders.append(it)
     return {'images': images, 'folders': folders}
示例#17
0
def get_path_to_icon(obj=None, content_type=None):
    if IImage.providedBy(obj):
        return None
    if obj is None and content_type is None:
        log.warn('Could not get object: {0}'.format(obj.getPath()))
        return 'unknown.png'
    mtr = api.portal.get_tool(name='mimetypes_registry')
    if obj is not None and content_type is None:
        for mime in mtr.lookup(obj.file.contentType):
            if mime.icon_path:
                return mime.icon_path
    elif content_type is not None:
        for mime in mtr.lookup(content_type):
            if mime.icon_path:
                return mime.icon_path
    return 'application.png'
示例#18
0
def get_path_to_icon(obj=None, content_type=None):
    if IImage.providedBy(obj):
        return None
    if obj is None and content_type is None:
        log.warn('Could not get object: {0}'.format(obj.getPath()))
        return 'unknown.png'
    mtr = api.portal.get_tool(name='mimetypes_registry')
    if obj is not None and content_type is None:
        for mime in mtr.lookup(obj.file.contentType):
            if mime.icon_path:
                return mime.icon_path
    elif content_type is not None:
        for mime in mtr.lookup(content_type):
            if mime.icon_path:
                return mime.icon_path
    return 'application.png'
 def logo(self):
     logo = self.getItems()
     if not logo:
         return None
     if getattr(logo, 'image_sizes', None):
         sizes = logo.image_sizes['base']
         return {
             'id':
             logo.getId,
             'content':
             '<img width="%s" height="%s" title="%s" alt="%s" src="%s"/>' %
             (str(sizes[0]), str(
                 sizes[1]), logo.Description, logo.Title, logo.getPath())
         }
     else:
         logo = logo.getObject()
         if has_dx and IImage.providedBy(logo):
             return {
                 'id':
                 logo.id,
                 'content':
                 ImageScaling(logo,
                              self.request).tag(title=logo.Description())
             }
         elif hasattr(logo, 'tag'):
             return {
                 'id': logo.id,
                 'content': logo.tag(title=logo.Description())
             }
         elif has_dx and IDocument.providedBy(logo):
             return {
                 'id': logo.id,
                 'content': logo.text and logo.text.raw or ''
             }
         elif hasattr(logo, 'getText'):
             return {'id': logo.id, 'content': logo.getText()}
         elif logo.portal_type == 'FlashMovie':
             return {
                 'id':
                 logo.id,
                 'content':
                 ObjectView(logo, self.request,
                            'flashmovie_macro_flashobject.pt')
             }
     return None
def set_title_description(obj, event):
    ''' Sets title to filename if no title
        was provided.
        Also sets an empty unicode as description if
        no description was provided.
    '''
    title = obj.title
    if not title:
        if IImage.providedBy(obj):
            datafield = obj.image
        else:
            datafield = obj.file
        if datafield:
            filename = datafield.filename
            obj.title = filename

    description = obj.description
    if not description:
        obj.description = u''
def set_title_description(obj, event):
    """ Sets title to filename if no title
        was provided.
        Also sets an empty unicode as description if
        no description was provided.
    """
    title = obj.title
    if not title:
        if IImage.providedBy(obj):
            datafield = obj.image
        else:
            datafield = obj.file
        if datafield:
            filename = datafield.filename
            obj.title = filename

    description = obj.description
    if not description:
        obj.description = u""
示例#22
0
    def get_previews(self, obj):
        if IImage.providedBy(obj):
            return {
                'class': '',
                'url': '{}/@@images/image'.format(obj.absolute_url()),
                'page_count': 1,
                'has_preview': True,
            }
        portal = api.portal.get()
        gsettings = GlobalSettings(portal)

        preview_details = {'class': 'not-generated', 'has_preview': False}
        if not allowedDocumentType(obj, gsettings.auto_layout_file_types):
            preview_details['class'] = 'not-possible'
        elif previews.has_previews(obj):
            preview_urls = previews.get_preview_urls(obj)
            if preview_urls:
                preview_details = {
                    'class': '',
                    'url': preview_urls[0],
                    'page_count': len(preview_urls),
                    'has_preview': True,
                }
        return preview_details
 def _filesize(self):
     """Return the filesize if the contenttype is a File or an Image"""
     if IFile.providedBy(self.obj):
         return self.obj.file.size
     if IImage.providedBy(self.obj):
         return self.obj.image.size
示例#24
0
    def secondLevelTabs(self, query, currentlevel, currentitem, sublevels=None, group=1):
        context = aq_inner(self.context)

        result = []

        if currentitem.portal_type in ['Topic', 'Collection'] and getattr(currentitem, 'show_results_in_globalnav', False):
            topic = currentitem.getObject()
            rawresult = topic.queryCatalog(review_state=query['review_state'], portal_type=query['portal_type'])
        else:
            rawresult = self.portal_catalog.searchResults(**query)
        if group > 1:
            grouplist = []
            lgroup = range(group)
            for i in lgroup:
                grouplist.append([])
            for item in rawresult:
                idx = (list(rawresult).index(item)+1)%group
                grouplist[idx-1].append(item)
            rawresult = []
            for g in grouplist:
                rawresult += g
        if sublevels == None:
            sublevels = getattr(self.navtree_properties, 'sections_depth', 1)

        def _get_url(item):
            if item.getRemoteUrl and not member == item.Creator:
                return (get_id(item), item.getRemoteUrl)
            return get_view_url(item)
            
        # now add the content to results
        for item in rawresult:
            if not getattr(item, 'exclude_from_nav', False) and not getattr(item, 'exclude_from_globalnav', False):

                cid, item_url = _get_url(item)

                children = []
                if sublevels > currentlevel:
                    itempath = item.getPath()
                    query['path'] = {'query' : itempath.replace('/','',1), 'depth' : 1}
                    newlevel = currentlevel + 1
                    children = self.secondLevelTabs(query, newlevel, item, sublevels)

                data = {'name'        : utils.pretty_title_or_id(context, item),
                        'id'          : item.getId,
                        'url'         : item_url,
                        'description' : item.Description,
                        'review_state': 'state-'+item.review_state,
                        'children'    : children,
                        }
                menucontent = getattr(currentitem, 'menu_content', None)
                if not menucontent:
                    menucontent = ['title']
                data['menucontent'] = menucontent
                if menucontent and 'image' in menucontent:
                    data['menuimage'] = None
                    image = None
                    if has_cie:
                        if getattr(item, 'image_assoc', None):
                            results = self.portal_catalog.searchResults({'UID':item.image_assoc[0], 'Language':'all'})
                            if results:
                                image = results[0].getObject()
                    if not image:
                        obj = item.getObject()
                        if (has_dx and IImage.providedBy(obj)) or hasattr(obj, 'tag') or getattr(obj, 'image', None):
                            image = obj
                    if image:
                        size = getattr(currentitem, 'menu_image_size', 'tile')
                        if not size:
                            size = 'tile'
                        data['menuimagesize'] = size
                        if hasattr(image, 'tag'):
                            data['menuimage'] = image.tag(scale=size, css_class='')
                        elif has_dx:
                            if IImage.providedBy(image):
                                data['menuimage'] = ImageScaling(image, self.request).tag(scale=size, css_class='')
                            else:
                                data['menuimage'] = ImageScaling(image, self.request).tag(fieldname='image', scale=size, css_class='')
                                
                submenudisplay = getattr(currentitem, 'submenu_display', None)
                if not submenudisplay:
                    submenudisplay = 'hover'
                data['submenudisplay'] = submenudisplay
                if not getattr(item, 'is_default_page', False):
                    result.append(data)

        return result
示例#25
0
 def canBackground(self):
     if has_dx and IImage.providedBy(self.context):
         return True
     return IATBlobImage.providedBy(self.context)
 def test_adding(self):
     self.portal.invokeFactory(
         'Image',
         'doc1'
     )
     self.assertTrue(IImage.providedBy(self.portal['doc1']))
    def getSolgemaBandeaux(self):
        bandeaux = self.getItems()
        bandeauxList = []
        base_ajax_content_load = self.request.get('ajax_content_load')
        base_ajax_load = self.request.get('ajax_load')
        setattr(self.request, 'ajax_content_load', 1)
        setattr(self.request, 'ajax_load', 1)
        for bandeau in bandeaux:
            bdict = {}
            if getattr(bandeau, 'image_sizes', None):
                height = str(bandeau.image_sizes['base'][1])
                url = str(bandeau.getPath() + '/image')
                try:
                    title = str(bandeau.Description)
                except:
                    try:
                        title = str(bandeau.Description.encode('utf-8'))
                    except:
                        try:
                            title = str(bandeau.Description.decode('utf-8'))
                        except:
                            title = safe_unicode(bandeau.Description)
                if getattr(bandeau, 'bannerImageLink', ''):
                    link = str(self.context.absolute_url() + '/resolveuid/' +
                               bandeau.bannerImageLink)
                else:
                    link = None
                repeat = getattr(bandeau, 'backgroundRepeat', None)
                if not repeat:
                    repeat = 'no-repeat'
                repeat = str(repeat)
                align = getattr(bandeau, 'backgroundAlign', None)
                if not align:
                    align = 'left'
                align = str(align)
                cssClass = 'bandeau_image'
                cssStyle = 'position:relative;'
                if getattr(bandeau, 'backgroundExtend', False):
                    cssClass += ' backgroundExtend'
                if getattr(bandeau, 'backgroundFixed', False):
                    cssClass += ' backgroundFixed'
                if len(bandeauxList) == 0:
                    cssClass += ' ' + bandeau.id.replace(
                        '.', '_') + ' carousel-banner-content selected'
                    cssStyle += ' display:block;'
                else:
                    cssClass += ' ' + bandeau.id.replace(
                        '.', '_') + ' carousel-banner-content'
                    cssStyle += ' display:none;'

                if link:
                    backgrounddiv = '<a style="display:block; height:%spx; width:100%%; background:transparent url(%s) %s %s top;" title="%s" class="%s" href="%s"></a>' % (
                        height, url, repeat, align, title, cssClass, link)
                else:
                    backgrounddiv = '<div style="height:%spx; width:100%%; background:transparent url(%s) %s %s top;" title="%s" class="%s"></div>' % (
                        height, url, repeat, align, title, cssClass)


#                bandeauxList.append({'id':bandeau.id, 'content':bandeau.tag(title=bandeau.Description())})
                bdict = {
                    'id': bandeau.id,
                    'content': backgrounddiv,
                    'cssClass': cssClass,
                    'cssStyle': cssStyle,
                    'url': url,
                    'link': link,
                    'align': align,
                    'repeat': repeat
                }
            else:
                bandeau = bandeau.getObject()
                if (has_dx and IImage.providedBy(bandeau)) or hasattr(
                        bandeau, 'tag'):
                    if hasattr(bandeau, 'getHeight'):
                        height = bandeau.getHeight()
                    else:
                        height = ImageScaling(bandeau,
                                              self.request).scale().height
                    if has_dx and IImage.providedBy(bandeau):
                        url = bandeau.absolute_url()
                    else:
                        url = str(bandeau.absolute_url() + '/image')
                    title = bandeau.title
                    bkg = IBackgroundContent(bandeau, None)
                    repeat = getattr(bkg, 'backgroundRepeat', None)
                    if not repeat:
                        repeat = 'no-repeat'
                    align = getattr(bkg, 'backgroundAlign', None)
                    if not align:
                        align = 'left'
                    align = str(align)
                    cssClass = 'bandeau_image'
                    cssStyle = 'position:relative;'
                    if getattr(bkg, 'backgroundExtend', False):
                        cssClass += ' backgroundExtend'
                    if getattr(bkg, 'backgroundFixed', False):
                        cssClass += ' backgroundFixed'
                    if len(bandeauxList) == 0:
                        cssClass += ' ' + bandeau.id.replace(
                            '.', '_') + ' carousel-banner-content selected'
                        cssStyle += ' display:block;'
                    else:
                        cssClass += ' ' + bandeau.id.replace(
                            '.', '_') + ' carousel-banner-content'
                        cssStyle += ' display:none;'

                    if getattr(bkg, 'bannerImageLink', ''):
                        link = str(self.context.absolute_url() +
                                   '/resolveuid/' + bkg.bannerImageLink)
                    else:
                        link = None
                    if link:
                        backgrounddiv = '<a style="display:block; height:%spx; width:100%%; background:transparent url(%s) %s %s top;" title="%s" class="%s" href="%s"></a>' % (
                            height, url, repeat, align, title, cssClass, link)
                    else:
                        backgrounddiv = '<div style="height:%spx; width:100%%; background:transparent url(%s) %s %s top;" title="%s" class="%s"></div>' % (
                            height, url, repeat, align, title, cssClass)
                    bdict = {
                        'id': bandeau.id,
                        'content': backgrounddiv,
                        'cssClass': cssClass,
                        'cssStyle': cssStyle,
                        'url': url,
                        'link': link,
                        'align': align,
                        'repeat': repeat
                    }
                elif has_dx and IDocument.providedBy(bandeau):
                    bdict['id'] = bandeau.id
                    bdict['content'] = bandeau.text and bandeau.text.raw or ''
                elif hasattr(bandeau,
                             'getText') and not bandeau.portal_type in [
                                 'Topic', 'Collection'
                             ]:
                    try:
                        bdict['id'] = bandeau.id
                        bdict['content'] = bandeau.getText()
                    except:
                        raise ValueError('error with: ' + str(bandeau))
                elif bandeau.portal_type == 'Collage':
                    bdict['id'] = bandeau.id
                    bdict['content'] = ObjectView(bandeau, self.request,
                                                  'collage_renderer.pt')
                elif bandeau.portal_type == 'FlashMovie':
                    bdict['id'] = bandeau.id
                    bdict['content'] = ObjectView(
                        bandeau, self.request,
                        'flashmovie_macro_flashobject.pt')
                elif bandeau.portal_type == 'Folder':
                    bdict['id'] = bandeau.id
                    bdict['content'] = ObjectView(bandeau, self.request,
                                                  'folder_renderer.pt')
                else:
                    bdict['id'] = bandeau.id
                    bdict['content'] = bandeau()
            bandeauxList.append(bdict)
        if not base_ajax_content_load:
            delattr(self.request, 'ajax_content_load')
        if not base_ajax_load:
            delattr(self.request, 'ajax_load')
        return bandeauxList
示例#28
0
 def test_adding(self):
     self.portal.invokeFactory(
         'Image',
         'doc1'
     )
     self.assertTrue(IImage.providedBy(self.portal['doc1']))
    def _getAllObjectsData(self, context, objects_listing, tfile, tmp=False):
        """ Returns the data in all files with a content object to be placed
            in a zipfile
        """
        props = getToolByName(context, 'portal_properties')
        nameByTitle = props.zipfile_properties.name_by_title
        allow_zip64 = props.zipfile_properties.allow_zip64
        # Use temporary IO object instead of writing to filesystem.
        if tmp:
            fd, path = tempfile.mkstemp('.zipfiletransport')
            tfile = path
            close(fd)

        zipFile = ZipFile(tfile, 'w', ZIP_DEFLATED, allowZip64=allow_zip64)
        context_path = str(context.virtual_url_path())

        for obj in objects_listing:
            object_extension = ''
            object_path = str(obj.virtual_url_path())
            file_data = None
            if HAS_PAC:
                if IImage.providedBy(obj):
                    file_data = str(obj.image.data)
                    object_path = object_path.replace(context_path + '/', '')
                elif IFile.providedBy(obj):
                    file_data = str(obj.file.data)
                    object_path = object_path.replace(context_path + '/', '')
            if file_data is not None and object_path is not None:
                # early escape coming from plone.app.contenttypes
                pass
            elif self._objImplementsInterface(obj, interfaces.IATFile) or \
                        self._objImplementsInterface(obj, interfaces.IATImage):
                file_data = str(obj.data)
                object_path = object_path.replace(context_path + '/', '')

            elif self._objImplementsInterface(obj, interfaces.IATDocument):

                if "text/html" == obj.Format():
                    file_data = obj.getText()
                    object_extension = ".html"

                elif "text/x-rst" == obj.Format():
                    file_data = obj.getRawText()
                    object_extension = ".rst"

                elif "text/structured" == obj.Format():
                    file_data = obj.getRawText()
                    object_extension = ".stx"

                elif "text/plain" == obj.Format():
                    file_data = obj.getRawText()
                    object_extension = ".txt"

                else:
                    file_data = obj.getRawText()

                object_path = object_path.replace(context_path + '/', '')

            elif self._objImplementsInterface(obj, interfaces.IATFolder):
                if hasattr(obj, 'getRawText'):
                    file_data = obj.getRawText()

                    if object_path == context_path:
                        object_path = object_path.split("/")[-1]
                    else:
                        object_path = object_path.replace(context_path + '/', '')

                    if object_path[-5:] != ".html" and object_path[-4:] != ".htm":
                        object_extension = ".html"
            else:
                continue

            # start point for object path, adding 1 removes the initial '/'
            object_path = self.generateSafeFileName(object_path)

            if object_path:
                # Reconstruct path with filename, use ID unless
                # name_by_title has been set. Name by ID is the
                # default behavior so that links to other documents
                # in documents will be preserved when the same file
                # is imported back into your Plone site. If you use
                # name_by_title, you will be able to save non-ascii
                # chars in the filename but you will not be able to
                # round trip the ZIP archive and have links in your
                # documents continue to work. ID is the preferred
                # solution, as it is much work to go through lots of
                # documents by hand, find the internal links and
                # correct them manually.
                filename_path = []
                for i in range(0, len(object_path.split('/'))):
                    if nameByTitle:
                        # Use title for filename in ZIP export
                        filename_path.append(obj.Title())
                    else:
                        filename_path.append(obj.getId())
                    obj = obj.aq_inner.aq_parent

                if len(filename_path) > 1:
                    filename_path.reverse()
                    filename_path = '/'.join(filename_path)
                else:
                    filename_path = filename_path[0]

                # Add the correct file extension
                if filename_path[-len(object_extension):] != object_extension:
                    filename_path += object_extension

                if 'Windows' in context.REQUEST['HTTP_USER_AGENT']:
                    filename_path = filename_path.decode('utf-8').encode('cp437')
                zipFile.writestr(filename_path, file_data)

        zipFile.close()
        if not tmp:
            tfile = ''
        return tfile