Example #1
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)
Example #2
0
    def test_fix_image_field_modification_time(self):
        from persistent.dict import PersistentDict
        title = u'Fix image field modification time'
        step = self._get_upgrade_step(title)
        assert step is not None

        # simulate state on previous version
        cover = self._create_cover('test-cover', 'Empty layout')
        cover.cover_layout = (
            '[{"type": "row", "children": [{"column-size": 16, "type": '
            '"group", "children": [{"tile-type": '
            '"collective.cover.basic", "type": "tile", "id": '
            '"ca6ba6675ef145e4a569c5e410af7511"}], "roles": ["Manager"]}]}]'
        )

        tile = cover.get_tile('ca6ba6675ef145e4a569c5e410af7511')
        obj = self.portal['my-image']
        tile.populate_with_object(obj)

        dmgr = ITileDataManager(tile)
        old_data = dmgr.get()
        old_data['image_mtime'] = repr(old_data['image_mtime'])
        dmgr.annotations[dmgr.key] = PersistentDict(old_data)

        data = dmgr.get()
        assert isinstance(data['image_mtime'], str)

        # run the upgrade step to validate the update
        self._do_upgrade_step(step)

        data = dmgr.get()
        self.assertIsInstance(data['image_mtime'], float)
    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)
Example #4
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)
    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)
Example #6
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)
    def test_double_assign_tile_image(self):
        obj = self.portal['my-dexterity-item']
        data_mgr = ITileDataManager(self.tile)

        self.tile.populate_with_object(obj)
        self.assertTrue('image_mtime' in data_mgr.get())
        mtime = data_mgr.get()['image_mtime']

        self.tile.populate_with_object(obj)
        self.assertTrue('image_mtime' in data_mgr.get(), 'Image mtime was removed from data')
        self.assertEqual(mtime, data_mgr.get()['image_mtime'])
Example #8
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()
 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(RelevantAceContentItemsTile, self).remove_item(uuid)  # check permission
     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)
 def test_double_dragging_content_with_image(self):
     # https://github.com/collective/collective.cover/issues/449
     obj = self.portal['my-image']
     data_mgr = ITileDataManager(self.tile)
     self.tile.populate_with_object(obj)
     self.assertIn('image_mtime', data_mgr.get())
     self.assertTrue(float(data_mgr.get()['image_mtime']))
     # populate tile for second time with same object
     self.tile.populate_with_object(obj)
     self.assertIn('image_mtime', data_mgr.get())
     self.assertTrue(float(data_mgr.get()['image_mtime']))
     # tile is rendered with no issues
     rendered = self.tile()
     self.assertIn('<html xmlns="http://www.w3.org/1999/xhtml">', rendered)
Example #11
0
    def populate_with_object(self, obj):
        super(ListTile, self).populate_with_object(obj)
        uuid = IUUID(obj, None)
        data_mgr = ITileDataManager(self)
        if data_mgr.get()['uuids']:
            uuids = data_mgr.get()['uuids']
            if type(uuids) != list:
                uuids = [uuid]
            elif uuid not in uuids:
                uuids.append(uuid)

            data_mgr.set({'uuids': uuids[:self.limit]})
        else:
            data_mgr.set({'uuids': [uuid]})
    def test_double_assign_tile_dexterity_image(self):
        # https://github.com/collective/collective.cover/issues/449
        from plone.namedfile.file import NamedBlobImage
        from plone.namedfile.tests.test_image import zptlogo
        with api.env.adopt_roles(['Manager']):
            obj = api.content.create(self.portal, 'Dexterity Image', 'foo')
            obj.image = NamedBlobImage(zptlogo)

        data_mgr = ITileDataManager(self.tile)
        self.tile.populate_with_object(obj)
        self.assertIn('image_mtime', data_mgr.get())
        mtime = data_mgr.get()['image_mtime']
        self.tile.populate_with_object(obj)
        self.assertIn('image_mtime', data_mgr.get())
        self.assertEqual(mtime, data_mgr.get()['image_mtime'])
Example #13
0
    def __str__(self):
        url = super(TransientTileAbsoluteURL, self).__str__()
        manager = ITileDataManager(self.context)

        # Transient looking tile with id is only really transient
        # if it caches its decoded query data in request annotations
        transient = manager.storage == IAnnotations(self.request)

        # When transient looking tile with id is not really transient,
        # its data should not be encoded into query string
        if self.context.id and not transient:
            return url

        # All tiles don't need / have configuration data at all.
        data = manager.get()
        if not data:
            return url

        # But when configuration data is really read from query string
        # and not persisted, it should also be kept in query string
        tileType = queryUtility(ITileType, name=self.context.__name__)
        if tileType is not None and tileType.schema is not None:
            if '?' in url:
                url += '&' + encode(data, tileType.schema)
            else:
                url += '?' + encode(data, tileType.schema)
        return url
Example #14
0
 def _move_selected_content(self, origin_tile, target_tile, obj):
     """Move selected content from one tile to another tile"""
     target_tile.populate_with_object(obj)
     if IListTile.providedBy(origin_tile):
         uuid = IUUID(obj)
         origin_tile.remove_item(uuid)
     else:
         origin_dmgr = ITileDataManager(origin_tile)
         origin_data = origin_dmgr.get()
         target_dmgr = ITileDataManager(target_tile)
         target_data = target_dmgr.get()
         for k, v in origin_data.iteritems():
             if k in target_data and not k.startswith('uuid') and v is not None:
                 target_data[k] = v
         target_dmgr.set(target_data)
         origin_dmgr.delete()
    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)
        content = dataManager.get()
        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
        contextURL = absoluteURL(tile.context, 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(contextURL)
Example #16
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)
Example #17
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)
Example #18
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})
Example #19
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]
Example #20
0
    def populate_with_object(self, obj):
        super(ListTile, self).populate_with_object(obj)
        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):
        if not obj.aq_parent.id == 'areas-tematicas':
            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)
Example #22
0
    def getContent(self):
        typeName = self.tileType.__name__
        tileId = self.tileId

        # Traverse to the tile. If it is a transient tile, it will pick up
        # query string parameters from the original request
        tile = self.context.restrictedTraverse('@@%s/%s' % (typeName, tileId,))

        dataManager = ITileDataManager(tile)
        return dataManager.get()
Example #23
0
    def replace_with_objects(self, objs):
        super(ListTile, self).replace_with_objects(objs)
        data_mgr = ITileDataManager(self)
        old_data = data_mgr.get()
        if type(objs) == list:
            old_data['uuids'] = objs[:self.limit]
        else:
            old_data['uuids'] = [objs]

        data_mgr.set(old_data)
Example #24
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)
    def test_delete_tile_persistent_data(self):
        eventtesting.clearEvents()
        # First, let's store some data on the tile
        data_mgr = ITileDataManager(self.tile)
        data_mgr.set({'test': 'data'})

        # We see that the data persists
        self.assertIn('test', data_mgr.get())
        self.assertEqual(data_mgr.get()['test'], 'data')

        # Call the delete method
        self.tile.delete()

        # Now we should not see the stored data anymore
        self.assertNotIn('test', data_mgr.get())

        events = eventtesting.getEvents()

        # Finally, test that ObjectModifiedEvent was fired for the cover
        self.assertEqual(events[0].object, self.cover)
Example #26
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)
    def test_delete_tile_persistent_data(self):
        eventtesting.clearEvents()
        # First, let's assign an id to the tile and store some data
        self.tile.id = 'test-tile'
        data_mgr = ITileDataManager(self.tile)
        data_mgr.set({'test': 'data'})

        # We see that the data persists
        self.assertEqual(data_mgr.get(), {'test': 'data'})

        # Call the delete method
        self.tile.delete()

        # Now we should not see the stored data anymore
        self.assertEqual(data_mgr.get(), {})

        events = eventtesting.getEvents()

        # Finally, test that ObjectModifiedEvent was fired for the cover
        self.assertEqual(events[0].object, self.portal)
Example #28
0
 def get_content_portal_type(self, tile_type, tile_id):
     """Return content type of data inside the tile."""
     tile = self.context.restrictedTraverse('{0}/{1}'.format(str(tile_type), str(tile_id)))
     data_mgr = ITileDataManager(tile)
     data = data_mgr.get()
     uuid = data.get('uuid', None)
     if uuid is None:
         return
     obj = uuidToObject(uuid)
     if obj is None:
         return
     return obj.portal_type
 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)
 def test_getURL_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)
Example #31
0
 def test_autoplay(self):
     # autoplay is True when tile is empty
     self.assertTrue(self.tile.autoplay())
     # but Galleria init code is not rendered
     self.assertNotIn('data-autoplay="True"', self.tile())
     obj = self.portal['my-image']
     self.tile.populate_with_object(obj)
     self.assertIn('data-autoplay="True"', self.tile())
     data_mgr = ITileDataManager(self.tile)
     data = data_mgr.get()
     data['autoplay'] = False
     data_mgr.set(data)
     self._update_tile_data()
     self.assertFalse(self.tile.autoplay())
     self.assertIn('data-autoplay="False"', self.tile())
Example #32
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
     """
     if not self.isAllowedToEdit():
         raise Unauthorized(
             _('You are not allowed to add content to this tile'))
     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)
Example #33
0
    def populate_with_object(self, obj):
        super(ListTile, self).populate_with_object(obj)  # check permission

        # here we should check if the embeded item has its a video
        # XXX

        self.set_limit()
        header = obj.Title()  # use collection's title as header
        uuid = api.content.get_uuid(obj)
        data_mgr = ITileDataManager(self)

        old_data = data_mgr.get()
        old_data['header'] = header
        old_data['uuids'] = [uuid]
        data_mgr.set(old_data)
    def populate_with_object(self, obj):
        super(CarouselTile, 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)
        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)
Example #35
0
    def populate_with_uids(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
        data_mgr.set(old_data)
        notify(ObjectModifiedEvent(self))
Example #36
0
    def populate_with_uuids(self, uuids):
        self.set_limit()
        data_mgr = ITileDataManager(self)

        old_data = data_mgr.get()
        old_data['header'] = _(u'tile List Title')
        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)
Example #37
0
def show_remote_url_field(setup_tool):
    """Show remote_url field on Basic tiles."""
    logger.info(__doc__)
    results = get_valid_objects()
    for cover in results:
        for tile_id in cover.list_tiles(TILE_TYPES):
            tile = cover.get_tile(tile_id)
            data_mgr = ITileDataManager(tile)
            data = data_mgr.get()
            remote_url = data.get('remote_url')
            if not remote_url:
                continue

            # show information on possible issue
            path = cover.absolute_url_path()
            msg = '{0} ("{1}"): remote_url={2}'
            logger.info(msg.format(path, tile_id, remote_url))
Example #38
0
def replace_attribute_data(obj, tile_type, key):
    """Replace and convert value list to dict"""
    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()
        value = data.get(key)

        if value and isinstance(value, list):
            data[key] = {
                item: {
                    'order': index
                }
                for index, item in enumerate(data.pop(key))
            }
            data_mgr.set(data)
    def populate_with_object(self, obj):
        super(ListTile, self).populate_with_object(obj)  # check permission

        # here we should check if the embeded item has its a video
        # XXX

        self.set_limit()
        tile_title = obj.Title()  # use collection's title as header
        uuid = api.content.get_uuid(obj)
        data_mgr = ITileDataManager(self)

        old_data = data_mgr.get()
        old_data['tile_title'] = tile_title
        old_data['uuids'] = {
            uuid: {'order': six.text_type(0)},
        }
        data_mgr.set(old_data)
Example #40
0
    def populate_with_object(self, obj):
        image = obj.image()

        data_mgr = ITileDataManager(self)
        data = data_mgr.get()
        data['title'] = obj.title
        data['description'] = obj.description
        data['subtitle'] = obj.subtitle
        data['section'] = obj.section
        data['uuid'] = api.content.get_uuid(obj=obj)
        data['date'] = True
        data['subjects'] = True
        data['image'] = self.get_image_data(image)
        data['media_producer'] = obj.media_producer()

        # clear scales as new image is getting saved
        self.clear_scales()
        data_mgr.set(data)
Example #41
0
    def populate_with_uids(self, uuids):
        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()
        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)
        notify(ObjectModifiedEvent(self))
Example #42
0
    def get_title(self, item):
        """Get the title of the item, or the custom title if set.

        :param item: [required] The item for which we want the title
        :type item: Content object
        :returns: the item title
        :rtype: unicode
        """
        # First we get the title for the item itself
        title = item.Title()
        uuid = self.get_uuid(item)
        data_mgr = ITileDataManager(self)
        data = data_mgr.get()
        uuids = data['uuids']
        if uuid in uuids:
            if uuids[uuid].get('custom_title', u''):
                # If we had a custom title set, then get that
                title = uuids[uuid].get('custom_title')
        return title
Example #43
0
    def getContent(self):
        typeName = self.tileType.__name__
        tileId = self.tileId

        # Traverse to the tile. If it is a transient tile, it will pick up
        # query string parameters from the original request It is necessary to
        # defer security checking because during initial form setup, the
        # security context is not yet set. Setting the IDeferSecurityCheck
        # interface on the request is handled in
        # plone.z3cform.traversal.FormWidgetTraversal
        if IDeferSecurityCheck.providedBy(self.request):
            tile = self.context.unrestrictedTraverse(
                '@@%s/%s' % (typeName, tileId,))
        else:
            tile = self.context.restrictedTraverse(
                '@@%s/%s' % (typeName, tileId,))

        dataManager = ITileDataManager(tile)
        return AcquirableDictionary(dataManager.get()).__of__(self.context)
 def get_description(self, item):
     """Get the description of the item, or the custom description
     if set.
     :param item: [required] The item for which we want the description
     :type item: Content object
     :returns: the item description
     :rtype: unicode
     """
     # First we get the url for the item itself
     description = item.Description()
     uuid = self.get_uuid(item)
     data_mgr = ITileDataManager(self)
     data = data_mgr.get()
     uuids = data['uuids']
     if uuid in uuids:
         if uuids[uuid].get('custom_description', u''):
             # If we had a custom description set, then get that
             description = uuids[uuid].get('custom_description')
     return description
Example #45
0
    def get_url(self, item):
        """Get the URL of the item, or the custom URL if set.

        :param item: [required] The item for which we want the URL
        :type item: Content object
        :returns: the item URL
        :rtype: str
        """
        # First we get the url for the item itself
        url = item.absolute_url()
        if item.portal_type in get_types_use_view_action_in_listings():
            url += '/view'
        uuid = self.get_uuid(item)
        data_mgr = ITileDataManager(self)
        data = data_mgr.get()
        uuids = data['uuids']
        if uuid in uuids:
            if uuids[uuid].get('custom_url', u''):
                # If we had a custom url set, then get that
                url = uuids[uuid].get('custom_url')
        return url
Example #46
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:
            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)
        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)
Example #47
0
    def handleSave(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        tile = self.getTile()

        # 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)

        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)
Example #48
0
def fix_image_field_modification_time(context):
    """Fix image modification time to be float timestamp instead of string."""

    covers = context.portal_catalog(object_provides=ICover.__identifier__)
    logger.info('About to update {0} objects'.format(len(covers)))
    for cover in covers:
        obj = cover.getObject()
        for tile_id in obj.list_tiles():
            tile = obj.get_tile(tile_id)
            dmgr = ITileDataManager(tile)
            data = dmgr.get()
            for k, v in data.items():
                if not INamedImage.providedBy(v):
                    continue

                mtime_key = '{0}_mtime'.format(k)
                data[mtime_key] = float(data[mtime_key])
                # need to set changes directly into annotation
                dmgr.annotations[dmgr.key] = PersistentDict(data)
                msg = 'Tile {0} at {1} updated'
                logger.info(msg.format(tile_id, cover.getPath()))

    logger.info('Done')
Example #49
0
 def get_content_uuid(self, tile_type, tile_id):
     """Return UUID of data inside the tile."""
     tile = self.context.restrictedTraverse('{0}/{1}'.format(str(tile_type), str(tile_id)))
     data_mgr = ITileDataManager(tile)
     data = data_mgr.get()
     return data.get('uuid', None)
Example #50
0
 def change_data(self):
     data_mgr = ITileDataManager(self)
     data = data_mgr.get()
     yield data
     data_mgr.set(data)
Example #51
0
 def getContent(self):
     dataManager = ITileDataManager(self.getTile())
     return dataManager.get()
Example #52
0
 def remove_relation(self):
     data_mgr = ITileDataManager(self)
     old_data = data_mgr.get()
     if 'uuid' in old_data:
         old_data.pop('uuid')
     data_mgr.set(old_data)
Example #53
0
 def results(self):
     """ Return the list of objects stored in the tile.
     """
     data_mgr = ITileDataManager(self)
     data = data_mgr.get()
     return data
Example #54
0
 def _set_remote_url_field(tile, remote_url):
     data_mgr = ITileDataManager(tile)
     data = data_mgr.get()
     data.update(remote_url=remote_url)
     data_mgr.set(data)
Example #55
0
 def data(self):
     if self.__cachedData is None:
         reader = ITileDataManager(self)
         self.__cachedData = reader.get()
     return self.__cachedData
Example #56
0
def tiles(site, req, tiles_data=_tiles_data):

    alsoProvides(req, ICastleLayer)

    # Sitewide slot tiles
    for meta_id, tiles in tiles_data.items():
        meta_tile = MetaTile(site, req)
        alsoProvides(meta_tile, IGlobalTile)
        meta_tile.id = 'meta-' + meta_id
        meta_tile.__name__ = 'castle.cms.meta'
        meta_data_manager = ITileDataManager(meta_tile)
        meta_data = meta_data_manager.get()
        meta_tiles = []

        for tile_data in tiles:
            meta_tiles.append(tile_data['meta'])
            tile = getMultiAdapter((site, req), name=tile_data['meta']['type'])
            alsoProvides(tile, IPersistentTile)
            tile.id = tile_data['meta']['id']
            tile.__name__ = tile_data['meta']['type']
            data_manager = ITileDataManager(tile)
            data_manager.set(tile_data['data'])

        meta_data['tiles'] = meta_tiles
        meta_data_manager.set(meta_data)

    frontpage = site['front-page']
    adapted = ILayoutAware(frontpage, None)
    if adapted:
        adapted.pageSiteLayout = 'frontpage.html'

    # Tiles only for the front-page
    frontpage_tiles = getTileData()

    for tile in frontpage_tiles:
        fp_tile = getMultiAdapter((frontpage, req), name=tile['meta']['type'])

        meta = tile['meta']
        fp_tile.id = meta['id']
        alsoProvides(fp_tile, IPersistentTile)
        data_manager = ITileDataManager(fp_tile)
        data_manager.set(tile['data'])

        if 'slot' in tile:
            meta_tile = MetaTile(frontpage, req)
            alsoProvides(meta_tile, IGlobalTile)
            meta_tile.id = 'meta-' + tile['slot']
            meta_tile.__name__ = 'castle.cms.meta'
            meta_data_manager = ITileDataManager(meta_tile)
            meta_data = meta_data_manager.get()

            existing_tiles = meta_data.get('tiles') or []
            new_tile_id = tile['meta']['id']

            if new_tile_id in [x['id'] for x in existing_tiles]:
                # check if the tile we're trying to install is already there.
                continue

            existing_tiles.append(meta)
            meta_data['tiles'] = existing_tiles
            meta_data['mode'] = 'show'

            meta_data_manager.set(meta_data)

    frontpageLayout = ILayoutAware(frontpage, None)
    if frontpageLayout:
        frontpageLayout.contentLayout = '/++contentlayout++castle/frontpage-layout.html'  # noqa