def test_basic_tile_purge_cache(self):
        provideHandler(queuePurge)

        request = self.request
        alsoProvides(request, IAttributeAnnotatable)
        setRequest(request)

        registry = queryUtility(IRegistry)
        registry.registerInterface(ICachePurgingSettings)
        provideUtility(registry, IRegistry)

        settings = registry.forInterface(ICachePurgingSettings)
        settings.enabled = True
        settings.cachingProxies = ('http://*****:*****@@collective.cover.basic/test',
                '/c1/@@collective.cover.basic/test/@@images/image',
                '/c1/@@collective.cover.basic/test/@@images/icon',
                '/c1/@@collective.cover.basic/test/@@images/mini',
                '/c1/@@collective.cover.basic/test/@@images/large',
                '/c1/@@collective.cover.basic/test/@@images/listing',
                '/c1/@@collective.cover.basic/test/@@images/thumb',
                '/c1/@@collective.cover.basic/test/@@images/preview',
                '/c1/@@collective.cover.basic/test/@@images/tile']),
            IAnnotations(request)['plone.cachepurging.urls'])
    def populate_with_object(self, obj):
        super(PagedCarouselTile, self).populate_with_object(obj)  # check permission
        
        type_display = self.data.get('type_display', None)
        content_type = self.data.get('content_type', None)
        
        if (type_display in ['more_access', 'recent'] and obj.portal_type != 'Folder') \
           or (type_display == 'featured' and obj.portal_type != content_type):
            raise Unauthorized(
                _('You are not allowed to add content to this tile'))
        
        uuid = IUUID(obj, None)
        data_mgr = ITileDataManager(self)

        old_data = data_mgr.get()
        if data_mgr.get()['uuids']:
            uuids = data_mgr.get()['uuids']
            if type(uuids) != list:
                uuids = [uuid]
            elif uuid not in uuids:
                uuids.append(uuid)
            old_data['uuids'] = uuids
        else:
            old_data['uuids'] = [uuid]
        data_mgr.set(old_data)
示例#3
0
    def handleAdd(self, action):

        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        typeName = self.tileType.__name__

        generator = getUtility(IUUIDGenerator)
        tileId = generator()

        # Traverse to a new tile in the context, with no data
        tile = self.context.restrictedTraverse(
            '@@%s/%s' % (typeName, tileId,))

        dataManager = ITileDataManager(tile)
        new_data = {}
        form.applyChanges(self, new_data, data)
        dataManager.set(new_data)

        # Look up the URL - we need to do this after we've set the data to
        # correctly account for transient tiles
        tileURL = absoluteURL(tile, self.request)

        notify(ObjectCreatedEvent(tile))
        notify(ObjectAddedEvent(tile, self.context, tileId))
        logger.debug(u"Tile created at {0}".format(tileURL))

        try:
            url = self.nextURL(tile)
        except NotImplementedError:
            url = tileURL

        self.request.response.redirect(url)
示例#4
0
文件: edit.py 项目: CGTIC/Plone_SP
    def handleSave(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        typeName = self.tileType.__name__

        # Traverse to a new tile in the context, with no data
        tile = self.context.restrictedTraverse('@@%s/%s' % (typeName, self.tileId,))

        dataManager = ITileDataManager(tile)
        dataManager.set(data)

        # Look up the URL - we need to do this after we've set the data to
        # correctly account for transient tiles
        tileURL = absoluteURL(tile, self.request)
        contextURL = absoluteURL(tile.context, self.request)
        tileRelativeURL = tileURL

        if tileURL.startswith(contextURL):
            tileRelativeURL = '.' + tileURL[len(contextURL):]

        notify(ObjectModifiedEvent(tile))

        # Get the tile URL, possibly with encoded data
        IStatusMessage(self.request).addStatusMessage(_(u"Tile saved",), type=u'info')

        self.request.response.redirect(tileURL)
示例#5
0
    def populate_with_object(self, obj):
        """Tile can be populated with images and links; in this case we're not
        going to take care of any modification of the original object; we just
        copy the data to the tile and deal with it.
        """
        if obj.portal_type not in self.accepted_ct():
            return

        super(BannerTile, self).populate_with_object(obj)  # check permissions
        obj = aq_base(obj)  # avoid acquisition
        title = obj.Title()
        rights = obj.Rights() if hasattr(obj, 'Rights') else None

        # if image, store a copy of its data
        if obj.portal_type == 'Image':
            if hasattr(obj, 'getImage'):
                data = obj.getImage().data
            else:
                data = obj.image.data
            image = NamedBlobImage(data)
        else:
            image = None
        image_description = obj.Description() or obj.Title()
        remote_url = obj.getRemoteUrl() if obj.portal_type == 'Link' else None

        data_mgr = ITileDataManager(self)
        data_mgr.set({
            'title': title,
            'image': image,
            'image_description': image_description,
            'remote_url': remote_url,
            'rights': rights,
        })
 def populate_with_object(self, obj):
     # XXX: Pode ser removido?
     # super(NoticiasHomeTile, self).populate_with_object(obj)
     if obj.portal_type in self.accepted_ct():
         uuid = IUUID(obj, None)
         data_mgr = ITileDataManager(self)
         data_mgr.set({'uuid': uuid})
示例#7
0
    def handleSave(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        typeName = self.tileType.__name__

        # Traverse to a new tile in the context, with no data
        tile = self.context.restrictedTraverse('@@%s/%s' % (typeName, self.tileId,))

        dataManager = ITileDataManager(tile)
        # We need to check first for existing content in order to not loose
        # fields that weren't sent with the form.
        old_data = dataManager.get()
        for item in data:
            if data[item] is not None:
                old_data[item] = data[item]

        dataManager.set(old_data)

        # Look up the URL - we need to do this after we've set the data to
        # correctly account for transient tiles
        tileURL = absoluteURL(tile, self.request)
        notify(ObjectModifiedEvent(tile))

        # Get the tile URL, possibly with encoded data
        IStatusMessage(self.request).addStatusMessage(_(u"Tile saved",), type=u'info')

        self.request.response.redirect(tileURL)
示例#8
0
文件: edit.py 项目: CGTIC/Plone_SP
    def handleSave(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        typeName = self.tileType.__name__

        # Traverse to a new tile in the context, with no data
        tile = self.context.restrictedTraverse(
            '@@%s/%s' % (typeName, self.tileId,))

        dataManager = ITileDataManager(tile)
        dataManager.set(data)

        # Look up the URL - we need to do this after we've set the data to
        # correctly account for transient tiles
        tileURL = absoluteURL(tile, self.request)

        notify(ObjectModifiedEvent(tile))
        logger.debug(u"Tile edited at {0}".format(tileURL))

        try:
            url = self.nextURL(tile)
        except NotImplementedError:
            url = tileURL

        self.request.response.redirect(url)
示例#9
0
    def populate_with_object(self, obj):
        super(BannerRotativoTile, self).populate_with_object(obj)  # check permission
        if not self._has_image_field(obj):
            return
        self.set_limit()
        uuid = api.content.get_uuid(obj)
        title = obj.Title()
        description = obj.Description()
        rights = obj.Rights()
        data_mgr = ITileDataManager(self)
        old_data = data_mgr.get()
        if data_mgr.get()['uuids']:
            uuids = data_mgr.get()['uuids']
            if type(uuids) != list:
                uuids = [uuid]
            elif uuid not in uuids:
                uuids.append(uuid)

            old_data['uuids'] = uuids[:self.limit]
        else:
            old_data['uuids'] = [uuid]
        old_data['title'] = title
        old_data['description'] = description
        old_data['rights'] = rights
        data_mgr.set(old_data)
示例#10
0
    def populate_with_object(self, obj):
        super(BasicTile, self).populate_with_object(obj)

        # initialize the tile with all fields needed for its rendering
        # note that we include here 'date' and 'subjects', but we do not
        # really care about their value: they came directly from the catalog
        # brain
        data = {
            'title': safe_unicode(obj.Title()),
            'description': safe_unicode(obj.Description()),
            'uuid': IUUID(obj),
            'date': True,
            'subjects': True,
            'image': self.get_image_data(obj)
        }

        if data['image']:
            # clear scales if new image is getting saved
            self.clear_scales()

        data_mgr = ITileDataManager(self)
        data_mgr.set(data)

        msg = 'tile "{0}"" populated with data: {1}'
        logger.debug(msg.format(self.id, data))
示例#11
0
    def populate_with_object(self, obj):
        super(BasicTile, self).populate_with_object(obj)

        title = safe_unicode(obj.Title())
        description = safe_unicode(obj.Description())

        image = self.get_image_data(obj)
        if image:
            # clear scales if new image is getting saved
            self.clear_scales()

        # initialize the tile with all fields needed for its rendering
        # note that we include here 'date' and 'subjects', but we do not
        # really care about their value: they came directly from the catalog
        # brain
        data = {
            'title': title,
            'description': description,
            'uuid': IUUID(obj),
            'date': True,
            'subjects': True,
            'image': image,
            # FIXME: https://github.com/collective/collective.cover/issues/778
            'alt_text': description or title,
        }

        data_mgr = ITileDataManager(self)
        data_mgr.set(data)

        msg = 'tile "{0}"" populated with data: {1}'
        logger.debug(msg.format(self.id, data))
示例#12
0
    def populate_with_object(self, obj):
        super(ContentBodyTile, self).populate_with_object(obj)

        data = {"uuid": IUUID(obj)}

        data_mgr = ITileDataManager(self)
        data_mgr.set(data)
 def test_render_text(self):
     text = u'Achievement Unlocked: a11y'
     data_mgr = ITileDataManager(self.tile)
     data_mgr.set({'title': text})
     self.tile = self.portal.restrictedTraverse(
         '@@{0}/{1}'.format(self.name, 'test'))
     self.assertIn(text, self.tile())
    def populate_with_object(self, obj):
        super(BannerRotativoTile, self).populate_with_object(obj)  # check permission
        try:
            scale = obj.restrictedTraverse('@@images').scale('image')
        except:
            scale = None
        if not scale:
            return
        self.set_limit()
        uuid = IUUID(obj, None)
        title = obj.Title()
        description = obj.Description()
        rights = obj.Rights()
        data_mgr = ITileDataManager(self)
        old_data = data_mgr.get()
        if data_mgr.get()['uuids']:
            uuids = data_mgr.get()['uuids']
            if type(uuids) != list:
                uuids = [uuid]
            elif uuid not in uuids:
                uuids.append(uuid)

            old_data['uuids'] = uuids[:self.limit]
        else:
            old_data['uuids'] = [uuid]
        old_data['title'] = title
        old_data['description'] = description
        old_data['rights'] = rights
        data_mgr.set(old_data)
示例#15
0
    def handleSave(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        # Traverse to a new tile in the context, with no data
        typeName = self.tileType.__name__
        tile = self.context.restrictedTraverse('@@{0}/{1}'.format(typeName, self.tileId))

        # We need to check first for existing content in order not not loose
        # fields that weren't sent with the form
        dataManager = ITileDataManager(tile)
        old_data = dataManager.get()
        for item in data:
            old_data[item] = data[item]
        dataManager.set(old_data)

        # notify about modification
        notify(ObjectModifiedEvent(tile))
        api.portal.show_message(_(u'Tile saved'), self.request, type='info')

        # Look up the URL - we need to do this after we've set the data to
        # correctly account for transient tiles
        tileURL = absoluteURL(tile, self.request)
        self.request.response.redirect(tileURL)
示例#16
0
    def handleAdd(self, action):

        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        typeName = self.tileType.__name__

        # Traverse to a new tile in the context, with no data
        tile = self.context.restrictedTraverse(
            '@@%s/%s' % (typeName, self.tileId,))

        dataManager = ITileDataManager(tile)
        content = {}
        applyChanges(self, content, data)
        dataManager.set(content)

        # Look up the URL - we need to do this after we've set the data to
        # correctly account for transient tiles
        tileURL = absoluteURL(tile, self.request)
        contextURL = absoluteURL(tile.context, self.request)

        notify(ObjectCreatedEvent(tile))
        notify(ObjectAddedEvent(tile, self.context, self.tileId))

        IStatusMessage(self.request).addStatusMessage(
                _(u"Tile created at ${url}",
                  mapping={'url': tileURL}),
                type=u'info',
            )

        self.request.response.redirect(contextURL)
示例#17
0
    def populate_with_object(self, obj):
        super(AudioTile, self).populate_with_object(obj)  # check permissions

        if obj.portal_type in self.accepted_ct():
            title = obj.Title()
            description = obj.Description()
            rights = obj.Rights()
            mp3 = obj.return_mp3()
            if mp3:
                url = mp3.absolute_url()
                content_type = "audio/mp3"
            else:
                url = obj.absolute_url()
                content_type = ""
            uuid = IUUID(obj)
            data_mgr = ITileDataManager(self)
            data_mgr.set(
                {
                    "title": title,
                    "description": description,
                    "url": url,
                    "credit": rights,
                    "uuid": uuid,
                    "content_type": content_type,
                }
            )
    def test_crud(self):
        self.assertTrue(self.tile.is_empty())

        obj = self.portal['my-image']
        obj2 = self.portal['my-image1']
        obj3 = self.portal['my-image2']

        self.tile.populate_with_object(obj)
        self.tile.populate_with_object(obj2)
        self.tile.populate_with_object(obj3)

        self.tile = self.portal.restrictedTraverse(
            '@@{0}/{1}'.format('brasil.gov.tiles.photogallery', 'test-tile'))

        self.assertEqual(len(self.tile.results()), 3)
        self.assertIn(obj, self.tile.results())
        self.assertIn(obj2, self.tile.results())
        self.assertIn(obj3, self.tile.results())

        data = self.tile.data
        data['tile_title'] = 'My title'
        data_mgr = ITileDataManager(self.tile)
        data_mgr.set(data)

        self.tile = self.portal.restrictedTraverse(
            '@@{0}/{1}'.format('brasil.gov.tiles.photogallery', 'test-tile'))
        self.assertEqual(self.tile.tile_title, 'My title')
示例#19
0
    def populate_with_object(self, obj):
        # check permissions
        super(ImageTile, self).populate_with_object(obj)

        data_mgr = ITileDataManager(self)

        data_mgr.set({'image': NamedBlobImage(obj.getImage().data)})
示例#20
0
    def populate_with_object(self, obj):
        super(ListTile, self).populate_with_object(obj)  # check permission
        try:
            image_size = obj.restrictedTraverse('@@images').scale('image').size
            image_size = hasattr(image_size, '__call__') and image_size() or image_size
        except:
            image_size = None
        if not image_size:
            return
        self.set_limit()
        uuid = IUUID(obj, None)
        data_mgr = ITileDataManager(self)

        old_data = data_mgr.get()
        if data_mgr.get()['uuids']:
            uuids = data_mgr.get()['uuids']
            if type(uuids) != list:
                uuids = [uuid]
            elif uuid not in uuids:
                uuids.append(uuid)

            old_data['uuids'] = uuids[:self.limit]
        else:
            old_data['uuids'] = [uuid]
        data_mgr.set(old_data)
 def populate_with_object(self, obj):
     """ Fará o set do uuid do objeto recebido por drag drop
     """
     super(ListFolderContentsTile, self).populate_with_object(obj)
     uuid = IUUID(obj, None)
     data_mgr = ITileDataManager(self)
     data_mgr.set({'uuid': uuid})
示例#22
0
    def populate_with_object(self, obj):
        super(SectionNavTile, self).populate_with_object(obj)  # check permission

        if obj.portal_type in self.accepted_ct():

            data_mgr = ITileDataManager(self)
            data_mgr.set({'uuid': IUUID(obj)})
示例#23
0
    def populate_with_object(self, obj):
        super(PhotoGalleryTile, self).populate_with_object(obj)  # check permissions

        if obj.portal_type in self.accepted_ct():
            uuid = IUUID(obj)
            data_mgr = ITileDataManager(self)
            data_mgr.set(dict(uuid=uuid))
示例#24
0
    def handleAdd(self, action):

        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        typeName = self.tileType.__name__

        context = self.context

        # Look up if our context supports tiles, if not
        # pick default view instead
        if not ILayoutAware(context, None):
            default_page_view = getMultiAdapter((context, self.request),
                                                name='default_page')
            default_page = default_page_view.getDefaultPage()
            context = default_page and context[default_page] or context
            context = ILayoutAware(context, None)

        # Traverse to a new tile in the context, with no data
        tile = context.restrictedTraverse(
            '@@%s/%s' % (typeName, self.tileId,))

        dataManager = ITileDataManager(tile)
        dataManager.set(data)

        # Look up the URL - we need to do this after we've set the data to
        # correctly account for transient tiles
        tileURL = absoluteURL(tile, self.request)
        contextURL = absoluteURL(tile.context, self.request)
        tileRelativeURL = tileURL

        if tileURL.startswith(contextURL):
            tileRelativeURL = '.' + tileURL[len(contextURL):]

        notify(ObjectCreatedEvent(tile))
        notify(ObjectAddedEvent(tile, self.context, self.tileId))

        IStatusMessage(self.request).addStatusMessage(
                _(u"Tile created at ${url}",
                  mapping={'url': tileURL}),
                type=u'info',
            )

        # Calculate the edit URL and append some data in a JSON structure,
        # to help the UI know what to do.

        url = getEditTileURL(tile, self.request)

        tileDataJson = {}
        tileDataJson['action'] = "save"
        tileDataJson['mode'] = "add"
        tileDataJson['url'] = tileRelativeURL
        tileDataJson['tile_type'] = typeName
        tileDataJson['id'] = tile.id

        url = appendJSONData(url, 'tiledata', tileDataJson)
        self.request.response.redirect(url)
示例#25
0
    def remove_item(self, uid):
        super(ListTile, self).remove_item(uid)
        data_mgr = ITileDataManager(self)

        uids = data_mgr.get()['uuids']
        if uid in uids:
            del uids[uids.index(uid)]
        data_mgr.set({'uuids': uids})
示例#26
0
 def storage(self):
     tile = self.context
     manager = ITileDataManager(tile)
     data = manager.get()
     if IMAGESCALES_KEY not in data:
         data[IMAGESCALES_KEY] = PersistentDict()
         manager.set(data)
     return data[IMAGESCALES_KEY]
示例#27
0
    def replace_with_objects(self, objs):
        super(ListTile, self).replace_with_objects(objs)
        data_mgr = ITileDataManager(self)
        if type(objs) == list:
            objs = objs[:self.limit]
        else:
            objs = [objs]

        data_mgr.set({'uuids': objs})
示例#28
0
    def populate_with_object(self, obj):
        super(ContentBodyTile, self).populate_with_object(obj)

        data = {
            'uuid': IUUID(obj, None),  # XXX: can we get None here? see below
        }

        data_mgr = ITileDataManager(self)
        data_mgr.set(data)
示例#29
0
    def populate_with_object(self, obj):
        super(CollectionTile, self).populate_with_object(obj)  # check permission

        if obj.portal_type in self.accepted_ct():
            header = safe_unicode(obj.Title())  # use collection's title as header
            footer = _(u"More…")  # XXX: can we use field's default?

            data_mgr = ITileDataManager(self)
            data_mgr.set({"header": header, "footer": footer, "uuid": IUUID(obj)})
示例#30
0
 def remove_item(self, uid):
     super(ListTile, self).remove_item(uid)
     data_mgr = ITileDataManager(self)
     old_data = data_mgr.get()
     uids = data_mgr.get()['uuids']
     if uid in uids:
         del uids[uids.index(uid)]
     old_data['uuids'] = uids
     data_mgr.set(old_data)
示例#31
0
    def populate_with_object(self, obj):
        super(NITFBasicTile, self).populate_with_object(obj)

        data_mgr = ITileDataManager(self)
        data = data_mgr.get()
        data['subtitle'] = obj.subtitle
        data['section'] = obj.section
        img = obj.getImage()
        if img:
            data['image_description'] = img.Description() or img.Title()
        data_mgr.set(data)
示例#32
0
    def test_manually_populated(self):
        # simulate user populating tile by editing it (no drag-and-drop)
        data = dict(title='foo')
        data_mgr = ITileDataManager(self.tile)
        data_mgr.set(data)
        self.assertFalse(self.tile.is_empty())

        # tile must not be empty for anonymous user
        logout()
        tile = self.get_tile  # avoid data caching on tile
        self.assertFalse(tile.is_empty())
示例#33
0
 def _move_all_content(self, origin_tile, target_tile):
     """Move all content from one tile to another tile"""
     # copy data
     origin_dmgr = ITileDataManager(origin_tile)
     origin_data = origin_dmgr.get()
     if origin_data.get('uuids', None) is None:
         return
     target_dmgr = ITileDataManager(target_tile)
     target_dmgr.set(origin_dmgr.get())
     # remove origin tile
     origin_dmgr.delete()
示例#34
0
    def populate_with_object(self, obj):
        super(PFGTile, self).populate_with_object(obj)

        data = {
            'title': safe_unicode(obj.Title()),
            'description': safe_unicode(obj.Description()),
            'uuid': IUUID(obj, None),  # XXX: can we get None here? see below
        }

        data_mgr = ITileDataManager(self)
        data_mgr.set(data)
示例#35
0
    def set_tile_data(self, id, **data):
        """Set data attributes on the tile defined by id.

        :param id: id of the tile we want to modify its data
        :type id: string
        :param data: a dictionary of attributes we want to set on the tile
        :type data: dictionary
        """
        tile = self.get_tile(id)
        data_mgr = ITileDataManager(tile)
        data_mgr.set(data)
示例#36
0
    def replace_with_objects(self, uids):
        super(ListTile, self).replace_with_objects(uids)  # check permission
        self.set_limit()
        data_mgr = ITileDataManager(self)
        old_data = data_mgr.get()
        if type(uids) == list:
            old_data['uuids'] = [i for i in uids][:self.limit]
        else:
            old_data['uuids'] = [uids]

        data_mgr.set(old_data)
示例#37
0
 def replace_with_uuids(self, uuids):
     """ Replaces the whole list of items with a new list of items
     :param uuids: The list of objects' UUIDs to be used
     :type uuids: List of strings
     """
     data_mgr = ITileDataManager(self)
     old_data = data_mgr.get()
     # Clean old data
     old_data['uuids'] = dict()
     data_mgr.set(old_data)
     # Repopulate with clean list
     self.populate_with_uuids(uuids)
示例#38
0
    def populate_with_object(self, obj):
        super(FolderContentsListingTile, self).populate_with_object(obj)

        if obj.portal_type not in self.accepted_ct():
            return

        data = {
            'title': safe_unicode(obj.Title()),
            'uuid': IUUID(obj),
        }
        data_mgr = ITileDataManager(self)
        data_mgr.set(data)
示例#39
0
    def populate_with_object(self, obj):
        PersistentCoverTile.populate_with_object(self, obj)

        if obj.portal_type not in self.accepted_ct():
            return

        data = {
            'title': safe_unicode(obj.Title()),
            'uuid': IUUID(obj),
        }
        data_mgr = ITileDataManager(self)
        data_mgr.set(data)
 def test_image_traverser(self):
     obj = self.portal['my-image']
     data = self.tile.data
     scales = api.content.get_view(u'images', obj, self.request)
     self.tile.data['image'] = NamedImageFile(str(scales.scale('image').data))
     data_mgr = ITileDataManager(self.tile)
     data_mgr.set(data)
     scales = self.cover.restrictedTraverse(
         '@@{0}/{1}/@@images'.format('collective.cover.basic', 'test'))
     img = scales.scale('image')
     self.assertTrue(images_are_equal(str(self.tile.data['image'].data),
                                      str(img.index_html().read())))
示例#41
0
    def populate_with_uuids(self, uuids):
        """Add a list of elements to the list of items. This method will
        append new elements to the already existing list of items
        :param uuids: The list of objects' UUIDs to be used
        :type uuids: List of strings
        """

        if not self.isAllowedToEdit():
            raise Unauthorized(
                _("You are not allowed to add content to this tile"))
        # self.set_limit()
        data_mgr = ITileDataManager(self)

        old_data = data_mgr.get()

        if old_data["uuids"] is None:
            # If there is no content yet, just assign an empty dict
            old_data["uuids"] = dict()

        uuids_dict = old_data.get("uuids")

        if not isinstance(uuids_dict, dict):
            # Make sure this is a dict
            uuids_dict = old_data["uuids"] = dict()

        # if uuids_dict and len(uuids_dict) > self.limit:
        #     # Do not allow adding more objects than the defined limit
        #     return

        order_list = [
            int(val.get("order", 0)) for key, val in uuids_dict.items()
        ]

        if len(order_list) == 0:
            # First entry
            order = 0
        else:
            # Get last order position and increment 1
            order_list.sort()
            order = order_list.pop() + 1

        for uuid in uuids:
            if uuid not in uuids_dict.keys():
                entry = dict()
                entry[u"order"] = unicode(order)
                uuids_dict[uuid] = entry
                order += 1

        old_data["uuids"] = uuids_dict

        # Whenever we insert an (or rearange), remove the alpha sort
        old_data["sortBy"] = ""
        data_mgr.set(old_data)
示例#42
0
 def test_getRemoteUrl_render_empty(self):
     # no anchor is rendered if URL field is empty
     obj = self.portal['my-news-item']
     self.tile.populate_with_object(obj)
     data_mgr = ITileDataManager(self.tile)
     data = data_mgr.get()
     data['remote_url'] = u''
     data_mgr.set(data)
     tile = self.get_tile
     html = etree.HTML(tile())
     a = html.find('*//a')
     self.assertIsNone(a)
示例#43
0
    def populate_with_object(self, obj):
        super(FileTile, self).populate_with_object(obj)  # check permissions

        if obj.portal_type not in self.accepted_ct():
            return
        data = {
            'title': safe_unicode(obj.Title()),
            'description': safe_unicode(obj.Description()),
            'download': True,
            'uuid': IUUID(obj),
        }
        data_mgr = ITileDataManager(self)
        data_mgr.set(data)
示例#44
0
    def populate_with_object(self, obj):
        super(CollectionTile, self).populate_with_object(obj)  # check permission

        if obj.portal_type in self.accepted_ct():
            header = safe_unicode(obj.Title())  # use collection's title as header
            footer = _(u'More…')  # XXX: can we use field's default?

            data_mgr = ITileDataManager(self)
            data_mgr.set({
                'header': header,
                'footer': footer,
                'uuid': IUUID(obj),
            })
示例#45
0
def replace_attribute(obj, tile_type, old, new):
    """Replace attribute on tiles."""
    if tile_type is None:
        return

    from plone.tiles.interfaces import ITileDataManager
    for id_ in obj.list_tiles(tile_type):
        tile = obj.get_tile(id_)
        data_mgr = ITileDataManager(tile)
        data = data_mgr.get()
        if data.get(old):
            data[new] = data.pop(old)
            data_mgr.set(data)
示例#46
0
 def test_getRemoteUrl_render_edited(self):
     # the alternate URL must be rendered
     obj = self.portal['my-news-item']
     self.tile.populate_with_object(obj)
     remote_url = 'http://example.org/'
     data_mgr = ITileDataManager(self.tile)
     data = data_mgr.get()
     data['remote_url'] = remote_url
     data_mgr.set(data)
     tile = self.get_tile
     html = etree.HTML(tile())
     a = html.find('*//a')
     self.assertEqual(a.attrib['href'], remote_url)
示例#47
0
 def remove_item(self, uuid):
     """ Removes an item from the list
     :param uuid: [required] uuid for the object that wants to be removed
     :type uuid: string
     """
     super(AssignMultipleItemsMixin, self).remove_item(uuid)
     data_mgr = ITileDataManager(self)
     old_data = data_mgr.get()
     uuids = data_mgr.get()['uuids']
     if uuid in uuids.keys():
         del uuids[uuid]
     old_data['uuids'] = uuids
     data_mgr.set(old_data)
示例#48
0
    def populate_with_object(self, obj):
        super(CollectionTile, self).populate_with_object(obj)  # check permission

        if obj.portal_type in self.accepted_ct():
            title = obj.Title()
            description = obj.Description()
            uuid = IUUID(obj)

            data_mgr = ITileDataManager(self)
            data_mgr.set({'title': title,
                          'description': description,
                          'uuid': uuid,
                          })
    def test_crud(self):
        # we start with an empty tile
        self.assertTrue(self.tile.is_empty())

        # now we add a couple of objects to the list
        obj1 = self.portal['my-document']
        obj2 = self.portal['my-image']
        self.tile.populate_with_object(obj1)
        self.tile.populate_with_object(obj2)
        # tile's data attribute is cached; reinstantiate it
        self.tile = self.portal.restrictedTraverse('@@{0}/{1}'.format(
            'brasil.gov.tiles.highlightscarousel', 'test-tile'))
        self.assertEqual(len(self.tile.results()), 1)
        # If the object does not have image associated, it will not included.
        self.assertNotIn(obj1, self.tile.results())
        self.assertIn(obj2, self.tile.results())

        # next, we replace the list of objects with a different one
        obj3 = self.portal['my-news-item']
        self.tile.replace_with_uuids([api.content.get_uuid(obj3)])
        # tile's data attribute is cached; reinstantiate it
        self.tile = self.portal.restrictedTraverse('@@{0}/{1}'.format(
            'brasil.gov.tiles.highlightscarousel', 'test-tile'))
        self.assertNotIn(obj1, self.tile.results())
        self.assertNotIn(obj2, self.tile.results())
        self.assertIn(obj3, self.tile.results())

        # We edit the tile to give it a title and a 'more...' link.
        data = self.tile.data
        data['tile_title'] = 'My title'
        data['more_link'] = api.content.get_uuid(obj2)
        data['more_link_text'] = 'Read much more...'
        # Save the new data.
        data_mgr = ITileDataManager(self.tile)
        data_mgr.set(data)

        # tile's data attribute is cached; reinstantiate it
        self.tile = self.portal.restrictedTraverse('@@{0}/{1}'.format(
            'brasil.gov.tiles.highlightscarousel', 'test-tile'))
        self.assertEqual(self.tile.tile_title, 'My title')
        self.assertEqual(self.tile.more_link, {
            'href': 'http://nohost/plone/my-image',
            'text': 'Read much more...'
        })

        # finally, we remove it from the list; the tile must be empty again
        self.tile.remove_item(obj3.UID())
        # tile's data attribute is cached; reinstantiate it
        self.tile = self.portal.restrictedTraverse('@@{0}/{1}'.format(
            'brasil.gov.tiles.highlightscarousel', 'test-tile'))
        self.assertTrue(self.tile.is_empty())
示例#50
0
    def test_crud(self):
        # we start with an empty tile
        self.assertTrue(self.tile.is_empty())

        # now we add a couple of objects to the list
        obj1 = self.portal['my-document']
        obj2 = self.portal['my-image']
        self.tile.populate_with_object(obj1)
        self.tile.populate_with_object(obj2)

        # tile's data attributed is cached so we should re-instantiate the tile
        tile = api.content.get_view(self.name, self.cover, self.request)
        tile = tile['test']
        self.assertEqual(len(tile.results()), 2)
        self.assertIn(obj1, tile.results())
        self.assertIn(obj2, tile.results())

        # next, we replace the list of objects with a different one
        obj3 = self.portal['my-news-item']
        tile.replace_with_objects([IUUID(obj3, None)])
        # tile's data attributed is cached so we should re-instantiate the tile
        tile = api.content.get_view(self.name, self.cover, self.request)
        tile = tile['test']
        self.assertNotIn(obj1, tile.results())
        self.assertNotIn(obj2, tile.results())
        self.assertIn(obj3, tile.results())

        # We edit the tile to give it a title and a 'more...' link.
        data = tile.data
        data['tile_title'] = 'My title'
        data['more_link'] = IUUID(obj2)
        data['more_link_text'] = 'Read much more...'
        # Save the new data.
        data_mgr = ITileDataManager(tile)
        data_mgr.set(data)

        # tile's data attributed is cached so we should re-instantiate the tile
        tile = api.content.get_view(self.name, self.cover, self.request)
        tile = tile['test']
        self.assertEqual(tile.tile_title, 'My title')
        self.assertEqual(tile.more_link, {
            'href': 'http://nohost/plone/my-image',
            'text': 'Read much more...'
        })

        # finally, we remove it from the list; the tile must be empty again
        tile.remove_item(obj3.UID())
        # tile's data attributed is cached so we should re-instantiate the tile
        tile = api.content.get_view(self.name, self.cover, self.request)
        tile = tile['test']
        self.assertTrue(tile.is_empty())
示例#51
0
    def populate_with_object(self, obj):
        """Tile can be populated with any content type with image
        or getImage attribute; in this case we're not
        going to take care of any modification of the original object; we just
        copy the data to the tile and deal with it.
        """
        if obj.portal_type not in self.accepted_ct():
            return

        super(BannerTile, self).populate_with_object(obj)  # check permissions

        if hasattr(obj, 'getRemoteUrl'):
            remote_url = obj.getRemoteUrl()
        else:
            # Get object URL
            # For Image and File objects (or any other in typesUseViewActionInListings)
            # we must add a /view to prevent the download of the file
            obj_url = obj.absolute_url_path()
            props = api.portal.get_tool('portal_properties')
            stp = props.site_properties
            view_action_types = stp.getProperty('typesUseViewActionInListings', ())

            if hasattr(obj, 'portal_type') and obj.portal_type in view_action_types:
                obj_url += '/view'

            remote_url = obj_url

        image = None
        # if has image, store a copy of its data
        if self._has_image_field(obj) and self._field_is_visible('image'):
            scales = obj.restrictedTraverse('@@images')
            image = scales.scale('image', None)

        if image is not None and image != '':
            if isinstance(image.data, NamedBlobImage):
                # Dexterity
                image = image.data
            else:
                # Archetypes
                image = NamedBlobImage(image.data)

        obj = aq_base(obj)  # avoid acquisition
        title = safe_unicode(obj.Title())

        data_mgr = ITileDataManager(self)
        data_mgr.set({
            'title': title,
            'image': image,
            'remote_url': remote_url,
        })
示例#52
0
    def populate_with_uids(self, uuids):
        self.set_limit()
        data_mgr = ITileDataManager(self)

        old_data = data_mgr.get()
        for uuid in uuids:
            if old_data['uuids']:
                if type(old_data['uuids']) != list:
                    old_data['uuids'] = [uuid]
                elif uuid not in old_data['uuids']:
                    old_data['uuids'].append(uuid)
            else:
                old_data['uuids'] = [uuid]
        data_mgr.set(old_data)
示例#53
0
    def populate_with_object(self, obj):
        super(HeaderTile, self).populate_with_object(obj)  # check permissions

        title = obj.Title()
        url = obj.absolute_url()
        link_text = title
        data_mgr = ITileDataManager(self)
        uuid = IUUID(obj)
        data_mgr.set({
            'title': title,
            'link_url': url,
            'link_text': link_text,
            'uuid': uuid
        })
示例#54
0
    def remove_item(self, uid):
        """ Removes an item from the list

        :param uid: [required] uid for the object that wants to be removed
        :type uid: string
        """
        super(ListTile, self).remove_item(uid)  # check permission
        data_mgr = ITileDataManager(self)
        old_data = data_mgr.get()
        uuids = data_mgr.get()['uuids']
        if uid in uuids.keys():
            del uuids[uid]
        old_data['uuids'] = uuids
        data_mgr.set(old_data)
示例#55
0
    def add_tile(self):
        generator = getUtility(IUUIDGenerator)
        tile_id = generator()
        tile_type = self.request.get('type')
        tile = self.get_tile(tile_type, tile_id)
        data_manager = ITileDataManager(tile)
        data_manager.set({})

        meta_data_manager = self.get_meta_data_manager()
        data = meta_data_manager.get()
        tiles = data.get('tiles', []) or []
        tiles.append({'id': tile_id, 'type': tile_type})
        data['tiles'] = tiles
        meta_data_manager.set(data)
示例#56
0
    def populate_with_object(self, obj):
        super(FileTile, self).populate_with_object(obj)  # check permissions

        if obj.portal_type in self.accepted_ct():
            title = safe_unicode(obj.Title())
            description = safe_unicode(obj.Description())
            uuid = IUUID(obj)

            data_mgr = ITileDataManager(self)
            data_mgr.set({'title': title,
                          'description': description,
                          'download': True,
                          'uuid': uuid,
                          })
示例#57
0
    def test_crud(self):
        # we start with an empty tile
        self.assertTrue(self.tile.is_empty())

        # now we add a couple of objects to the list
        obj1 = self.portal['my-document']
        obj2 = self.portal['my-image']
        self.tile.populate_with_object(obj1)
        self.tile.populate_with_object(obj2)
        # tile's data attribute is cached; reinstantiate it
        self.tile = self.cover.restrictedTraverse('@@{0}/{1}'.format(
            'collective.cover.list', 'test'))
        self.assertEqual(len(self.tile.results()), 2)
        self.assertIn(obj1, self.tile.results())
        self.assertIn(obj2, self.tile.results())

        # next, we replace the list of objects with a different one
        obj3 = self.portal['my-news-item']
        self.tile.replace_with_objects([IUUID(obj3, None)])
        # tile's data attribute is cached; reinstantiate it
        self.tile = self.cover.restrictedTraverse('@@{0}/{1}'.format(
            'collective.cover.list', 'test'))
        self.assertNotIn(obj1, self.tile.results())
        self.assertNotIn(obj2, self.tile.results())
        self.assertIn(obj3, self.tile.results())

        # We edit the tile to give it a title and a 'more...' link.
        data = self.tile.data
        data['tile_title'] = 'My title'
        data['more_link'] = IUUID(obj2)
        data['more_link_text'] = 'Read much more...'
        # Save the new data.
        data_mgr = ITileDataManager(self.tile)
        data_mgr.set(data)

        # tile's data attribute is cached; reinstantiate it
        self.tile = self.cover.restrictedTraverse('@@{0}/{1}'.format(
            'collective.cover.list', 'test'))
        self.assertEqual(self.tile.tile_title, 'My title')
        self.assertEqual(self.tile.more_link, {
            'href': 'http://nohost/plone/my-image',
            'text': 'Read much more...'
        })

        # finally, we remove it from the list; the tile must be empty again
        self.tile.remove_item(obj3.UID())
        # tile's data attribute is cached; reinstantiate it
        self.tile = self.cover.restrictedTraverse('@@{0}/{1}'.format(
            'collective.cover.list', 'test'))
        self.assertTrue(self.tile.is_empty())
    def populate_with_object(self, obj):
        super(CollectionTile, self).populate_with_object(obj)

        title = obj.Title() or None
        description = obj.Description() or None
        uuid = IUUID(obj, None)

        data_mgr = ITileDataManager(self)

        data_mgr.set({
            'title': title,
            'description': description,
            'uuid': uuid,
        })
示例#59
0
    def replace_with_objects(self, uids):
        if not self.isAllowedToEdit():
            raise Unauthorized(
                _('You are not allowed to add content to this tile'))
        self.set_limit()
        data_mgr = ITileDataManager(self)
        old_data = data_mgr.get()
        if type(uids) == list:
            old_data['uuids'] = [i for i in uids][:self.limit]
        else:
            old_data['uuids'] = [uids]

        data_mgr.set(old_data)
        notify(ObjectModifiedEvent(self))
 def test_image_traverser(self):
     obj = self.portal['my-image']
     data = self.tile.data
     scales = queryMultiAdapter((obj, self.request), name="images")
     self.tile.data['image'] = NamedImageFile(
         str(scales.scale('image').data))
     data_mgr = ITileDataManager(self.tile)
     data_mgr.set(data)
     scales = self.layer['portal'].restrictedTraverse(
         '@@{0}/{1}/@@images'.format('collective.cover.basic',
                                     'test-basic-tile'))
     img = scales.scale('image')
     self.assertTrue(
         images_are_equal(str(self.tile.data['image'].data),
                          str(img.index_html().read())))