Ejemplo n.º 1
0
    def PUT(self):
        """ Modifies the community itself. """
        params = {}
        params['title'] = self.params.pop('title', None)
        params['community_type'] = self.params.pop('community_type', None)
        params['description'] = self.params.pop('description', None)
        params['image'] = self.params.pop('image', None)
        params['activity_view'] = self.params.pop('activity_view', None)
        params['twitter_hashtag'] = self.params.pop('twitter_hashtag', None)
        params['notify_activity_via_push'] = self.params.pop('notify_activity_via_push', None)
        params['notify_activity_via_push_comments_too'] = self.params.pop('notify_activity_via_push_comments_too', None)

        if params['community_type']:
            # We are changing the type of the community
            # Check if it's a legit change
            if params['community_type'] in ['Open', 'Closed', 'Organizative']:
                adapter = self.target.adapted(name=params['community_type'])
            else:
                return ApiResponse.from_string({"error": "Bad request, wrong community type"}, code=400)

            if params['community_type'] == self.target.community_type:
                return ApiResponse.from_string({"error": "Bad request, already that community type"}, code=400)

            # Everything is ok, proceed
            adapter.update_community_type()

        modified = self.update_community(params)
        if modified:
            success_response = 'Updated community "{}"'.format(self.target.absolute_url())
        else:
            success_response = 'Error with change values "{}".'.format(self.target.absolute_url())

        logger.info(success_response)
        return ApiResponse.from_string(success_response)
Ejemplo n.º 2
0
    def create_user(self, username, email, password, **properties):
        existing_user = api.user.get(username=username)
        maxclient, settings = getUtility(IMAXClient)()
        maxclient.setActor(settings.max_restricted_username)
        maxclient.setToken(settings.max_restricted_token)

        avatar = properties.pop('avatar', None)

        if not existing_user:
            args = dict(email=email, username=username, properties=properties)
            if password:
                args['password'] = password
            api.user.create(**args)
            maxclient.people[username].put(displayName=properties['fullname'])
            # Save the image into the Plone user profile if provided
            if avatar:
                portal = api.portal.get()
                membership_tool = getToolByName(portal, 'portal_membership')
                imgName = (avatar.split('/')[-1]).decode('utf-8')
                imgData = requests.get(avatar).content
                image = StringIO(imgData)
                image.filename = imgName
                execute_under_special_role(portal, "Manager",
                                           changeMemberPortrait,
                                           membership_tool, image, username)

            status = 201

        else:
            # Update portal membership user properties
            has_email = existing_user.getProperty('email', False)
            if not has_email:
                properties.update({'email': email})

            existing_user.setMemberProperties(properties)

            # Update MAX properties
            maxclient.people[username].post(
            )  # Just to make sure user exists (in case it was only on ldap)
            status = maxclient.last_response_code
            maxclient.people[username].put(displayName=properties['fullname'])

            if avatar:
                portal = api.portal.get()
                membership_tool = getToolByName(portal, 'portal_membership')
                imgName = (avatar.split('/')[-1]).decode('utf-8')
                imgData = requests.get(avatar).content
                image = StringIO(imgData)
                image.filename = imgName
                execute_under_special_role(portal, "Manager",
                                           changeMemberPortrait,
                                           membership_tool, image, username)

        if status == 201:
            return ApiResponse.from_string('User {} created'.format(username),
                                           code=status)
        else:
            return ApiResponse.from_string('User {} updated'.format(username),
                                           code=200)
Ejemplo n.º 3
0
    def GET(self):
        """ Launch an editacl SAVE process on all communities """
        pc = api.portal.get_tool('portal_catalog')
        communities = pc.unrestrictedSearchResults(
            portal_type='ulearn.community')
        results = []
        communities_ok = []
        communities_error = []
        for item in communities:
            try:
                self.target = item._unrestrictedGetObject()
                self.payload = ICommunityACL(self.target)().attrs.get(
                    'acl', '')
                adapter = self.target.adapted(request=self.request)
                adapter.update_acl(self.payload)
                acl = adapter.get_acl()
                adapter.set_plone_permissions(acl)
                adapter.update_hub_subscriptions()
                updated = 'Updated community subscriptions on: "{}" '.format(
                    self.target.absolute_url())
                logger.info(updated)
                communities_ok.append(self.target.absolute_url())
            except:
                error = 'Error updating community subscriptions on: "{}" '.format(
                    self.target.absolute_url())
                logger.error(error)
                communities_error.append(self.target.absolute_url())

        results.append(
            dict(successfully_updated_communities=communities_ok,
                 error_updating_communities=communities_error))

        return ApiResponse(results)
Ejemplo n.º 4
0
    def GET(self):
        main_color = api.portal.get_registry_record(
            name=
            'ulearn.core.controlpanel.IUlearnControlPanelSettings.main_color')
        secondary_color = api.portal.get_registry_record(
            name=
            'ulearn.core.controlpanel.IUlearnControlPanelSettings.secondary_color'
        )
        max_server = api.portal.get_registry_record(
            name='mrs.max.browser.controlpanel.IMAXUISettings.max_server')
        max_server_alias = api.portal.get_registry_record(
            name='mrs.max.browser.controlpanel.IMAXUISettings.max_server_alias'
        )
        hub_server = api.portal.get_registry_record(
            name='mrs.max.browser.controlpanel.IMAXUISettings.hub_server')
        domain = api.portal.get_registry_record(
            name='mrs.max.browser.controlpanel.IMAXUISettings.domain')
        oauth_server = max_server + '/info'
        buttonbar_selected = api.portal.get_registry_record(
            name=
            'ulearn.core.controlpanel.IUlearnControlPanelSettings.buttonbar_selected'
        )
        if 'username' in self.params:
            username = self.params['username']
            user = api.user.get(username=username)
            if hasattr(user,
                       'language') and user.getProperty('language') != '':
                language = user.getProperty('language')
            else:
                language = api.portal.get_default_language()
        else:
            language = api.portal.get_default_language()

        session = requests.Session()
        resp = session.get(oauth_server)

        try:
            max_oauth_server = resp.json()['max.oauth_server']
        except:
            max_oauth_server = 'ERROR: UNABLE TO CONNECT TO MAX OAUTH SERVER'

        show_news_in_app = api.portal.get_registry_record(
            name=
            'ulearn.core.controlpanel.IUlearnControlPanelSettings.show_news_in_app'
        )

        info = dict(main_color=main_color,
                    secondary_color=secondary_color,
                    max_server=max_server,
                    max_server_alias=max_server_alias,
                    hub_server=hub_server,
                    domain=domain,
                    oauth_server=oauth_server,
                    max_oauth_server=max_oauth_server,
                    show_news_in_app=show_news_in_app,
                    buttonbar_selected=buttonbar_selected,
                    language=language)
        return ApiResponse(info)
Ejemplo n.º 5
0
    def POST(self):
        params = {}
        params['nom'] = self.params.pop('title')
        params['community_type'] = self.params.pop('community_type')
        params['description'] = self.params.pop('description', None)
        params['image'] = self.params.pop('image', None)
        params['activity_view'] = self.params.pop('activity_view', None)
        params['twitter_hashtag'] = self.params.pop('twitter_hashtag', None)
        params['notify_activity_via_push'] = self.params.pop(
            'notify_activity_via_push', None)
        params['notify_activity_via_push_comments_too'] = self.params.pop(
            'notify_activity_via_push_comments_too', None)

        pc = api.portal.get_tool('portal_catalog')
        nom = safe_unicode(params['nom'])
        util = queryUtility(IIDNormalizer)
        id_normalized = util.normalize(nom, max_length=500)
        result = pc.unrestrictedSearchResults(portal_type='ulearn.community',
                                              id=id_normalized)

        imageObj = ''
        if params['image']:
            mime = MimeTypes()
            mime_type = mime.guess_type(params['image'])
            imgName = (params['image'].split('/')[-1]).decode('utf-8')
            imgData = requests.get(params['image']).content
            imageObj = NamedBlobImage(data=imgData,
                                      filename=imgName,
                                      contentType=mime_type[0])

        if result:
            # community = result[0].getObject()
            success_response = 'Community already exists.'
            status = 200
        else:
            new_community_id = self.context.invokeFactory(
                'ulearn.community',
                id_normalized,
                title=params['nom'],
                description=params['description'],
                image=imageObj,
                community_type=params['community_type'],
                activity_view=params['activity_view'],
                twitter_hashtag=params['twitter_hashtag'],
                notify_activity_via_push=True
                if params['notify_activity_via_push'] == 'True' else None,
                notify_activity_via_push_comments_too=True
                if params['notify_activity_via_push_comments_too'] == 'True'
                else None,
                checkConstraints=False)
            new_community = self.context[new_community_id]
            success_response = 'Created community "{}" with hash "{}".'.format(
                new_community.absolute_url(),
                sha1(new_community.absolute_url()).hexdigest())
            status = 201
        logger.info(success_response)
        return ApiResponse.from_string(success_response, code=status)
Ejemplo n.º 6
0
    def PUT(self):
        """
            Modify displayName user

            /api/people/{username}

            data = {'displayName':'Nom Cognom'}

        """
        existing_user = api.user.get(username=self.params['username'].lower())
        maxclient, settings = getUtility(IMAXClient)()
        maxclient.setActor(settings.max_restricted_username)
        maxclient.setToken(settings.max_restricted_token)

        if existing_user:
            if 'displayName' in self.params:
                # Update portal membership user properties
                existing_user.setMemberProperties(
                    {'fullname': self.params['displayName']})
                properties = get_all_user_properties(existing_user)
                add_user_to_catalog(existing_user, properties, overwrite=True)
                username = self.params['username'].lower()
                # Update max
                maxclient.people[username].put(
                    displayName=properties['fullname'])
                status = maxclient.last_response_code
            else:
                status = 500
        else:
            status = 404

        if status == 404:
            return ApiResponse.from_string('User {} not found'.format(
                self.params['username'].lower()),
                                           code=status)
        elif status == 200:
            return ApiResponse.from_string('User {} updated'.format(
                self.params['username'].lower()),
                                           code=status)
        elif status == 500:
            return ApiResponse.from_string(
                'User {} not updated. Not displayName.'.format(
                    self.params['username'].lower()),
                code=status)
Ejemplo n.º 7
0
    def DELETE(self):
        """
            Deletes a user from the plone & max & communities subscribe
        """
        self.deleteMembers([self.params['username']])
        remove_user_from_catalog(self.params['username'].lower())
        pc = api.portal.get_tool(name='portal_catalog')
        username = self.params['username']

        maxclient, settings = getUtility(IMAXClient)()
        maxclient.setActor(settings.max_restricted_username)
        maxclient.setToken(settings.max_restricted_token)

        # portal_url = api.portal.get().absolute_url()
        communities_subscription = maxclient.people[
            username].subscriptions.get()

        if communities_subscription != []:

            for num, community_subscription in enumerate(
                    communities_subscription):
                community = pc.unrestrictedSearchResults(
                    portal_type="ulearn.community",
                    community_hash=community_subscription['hash'])
                try:
                    obj = community[0]._unrestrictedGetObject()
                    self.context.plone_log(
                        'Processant {} de {}. Comunitat {}'.format(
                            num, len(communities_subscription), obj))
                    gwuuid = IGWUUID(obj).get()
                    portal = api.portal.get()
                    soup = get_soup('communities_acl', portal)

                    records = [r for r in soup.query(Eq('gwuuid', gwuuid))]

                    # Save ACL into the communities_acl soup
                    if records:
                        acl_record = records[0]
                        acl = acl_record.attrs['acl']
                        exist = [
                            a for a in acl['users']
                            if a['id'] == unicode(username)
                        ]
                        if exist:
                            acl['users'].remove(exist[0])
                            acl_record.attrs['acl'] = acl
                            soup.reindex(records=[acl_record])
                            adapter = obj.adapted()
                            adapter.set_plone_permissions(adapter.get_acl())

                except:
                    continue

        maxclient.people[username].delete()
        logger.info('Delete user: {}'.format(username))
        return ApiResponse({}, code=204)
Ejemplo n.º 8
0
    def PUT(self):
        """ Modifies the community itself. """
        params = {}
        params['title'] = self.params.pop('title', None)
        params['community_type'] = self.params.pop('community_type', None)
        params['description'] = self.params.pop('description', None)
        params['image'] = self.params.pop('image', None)
        params['activity_view'] = self.params.pop('activity_view', None)
        params['twitter_hashtag'] = self.params.pop('twitter_hashtag', None)
        params['notify_activity_via_push'] = self.params.pop(
            'notify_activity_via_push', None)
        params['notify_activity_via_push_comments_too'] = self.params.pop(
            'notify_activity_via_push_comments_too', None)

        if params['community_type']:
            # We are changing the type of the community
            # Check if it's a legit change
            if params['community_type'] in ['Open', 'Closed', 'Organizative']:
                adapter = self.target.adapted(name=params['community_type'])
            else:
                return ApiResponse.from_string(
                    {"error": "Bad request, wrong community type"}, code=400)

            if params['community_type'] == self.target.community_type:
                return ApiResponse.from_string(
                    {"error": "Bad request, already that community type"},
                    code=400)

            # Everything is ok, proceed
            adapter.update_community_type()

        modified = self.update_community(params)
        if modified:
            success_response = 'Updated community "{}"'.format(
                self.target.absolute_url())
        else:
            success_response = 'Error with change values "{}".'.format(
                self.target.absolute_url())

        logger.info(success_response)
        return ApiResponse.from_string(success_response)
Ejemplo n.º 9
0
    def GET(self):
        """ Return the number of communities. """
        pc = api.portal.get_tool('portal_catalog')
        community_type = self.params.pop('community_type', None)
        if community_type is not None:
            results = pc.unrestrictedSearchResults(
                portal_type='ulearn.community', community_type=community_type)
        else:
            results = pc.unrestrictedSearchResults(
                portal_type='ulearn.community')

        return ApiResponse(len(results))
Ejemplo n.º 10
0
    def create_event(self, eventid, title, desc, body, date_start, date_end):
        date_start = date_start.split('/')
        time_start = date_start[3].split(':')
        date_end = date_end.split('/')
        time_end = date_end[3].split(':')
        portal_url = api.portal.get()
        news_url = portal_url['events']
        pc = api.portal.get_tool('portal_catalog')
        brains = pc.unrestrictedSearchResults(portal_type='Event', id=eventid)
        if not brains:
            new_event = createContentInContainer(news_url,
                                                 'Event',
                                                 title=eventid,
                                                 start=datetime(int(date_start[2]),
                                                                int(date_start[1]),
                                                                int(date_start[0]),
                                                                int(time_start[0]),
                                                                int(time_start[1])
                                                                ),
                                                 end=datetime(int(date_end[2]),
                                                              int(date_end[1]),
                                                              int(date_end[0]),
                                                              int(time_end[0]),
                                                              int(time_end[1])
                                                              ),
                                                 timezone="Europe/Madrid",
                                                 checkConstraints=False)
            new_event.title = title
            new_event.description = desc
            new_event.text = IRichText['text'].fromUnicode(body)
            new_event.reindexObject()
            resp = ApiResponse.from_string('Event {} created'.format(eventid), code=201)
        else:
            event = brains[0].getObject()
            event.title = title
            event.text = IRichText['text'].fromUnicode(body)
            event.reindexObject()
            resp = ApiResponse.from_string('Event {} updated'.format(eventid))

        return resp
Ejemplo n.º 11
0
    def DELETE(self):
        # Check if there's a valid community with the requested hash
        # lookedup_obj = self.lookup_community()
        # if lookedup_obj is not True:
        #     return lookedup_obj

        # Hard security validation as the view is soft checked
        # check_permission = self.check_roles(self.community, ['Owner', 'Manager'])
        # if check_permission is not True:
        #     return check_permission
        api.content.delete(obj=self.target)

        return ApiResponse({}, code=204)
Ejemplo n.º 12
0
    def GET(self):
        """ Return the links from Menu Gestion folder and Menu ControlPanel """
        language = self.params['language']
        portal = api.portal.get()

        resultsGestion = {}
        try:
            path = portal['gestion']['menu'][language]  # fixed en code... always in this path
            folders = api.content.find(context=path, portal_type=('Folder', 'privateFolder'), depth=1)
            found = True
        except:
            # 'Menu Gestion not configured or Language not found.'
            resultsGestion = ''
            found = False

        if found:
            # Links from gestion folder
            for folder in folders:
                resultsGestion[folder.Title] = []
                menufolder = folder.getObject().items()
                for item in menufolder:
                    if ILink.providedBy(item[1]):
                        menuLink = dict(url=item[1].remoteUrl,
                                        title=item[1].title,
                                        )
                        resultsGestion[folder.Title].append(menuLink)

            if not resultsGestion:
                # 'No Menu Gestion configured in this Site.'
                resultsGestion = ''

        registry = getUtility(IRegistry)
        settings = registry.forInterface(IUlearnControlPanelSettings, check=False)

        # Links from controlpanel
        resultsControlPanel = []
        if settings.quicklinks_table:
            for item in settings.quicklinks_table:
                quickLink = dict(title=item['text'],
                                 url=item['link'],
                                 icon=item['icon'],
                                 )
                resultsControlPanel.append(quickLink)

        if not resultsControlPanel:
            # 'Menu Quicklinks not configured in the ControlPanel.'
            resultsControlPanel = ''

        values = {'Menu_Gestion': resultsGestion, 'Menu_Controlpanel': resultsControlPanel}

        return ApiResponse(values)
Ejemplo n.º 13
0
    def PUT(self):
        """
            Subscribes a bunch of users to a community the security is given an
            initial soft check for authenticated users at the view level and
            then by checking explicitly if the requester user has permission on
            the target community.
        """

        self.update_subscriptions()

        # Response successful
        success_response = 'Updated community "{}" subscriptions'.format(self.target.absolute_url())
        logger.info(success_response)
        return ApiResponse.from_string(success_response)
Ejemplo n.º 14
0
    def GET(self):
        portal = api.portal.get()
        soup = get_soup('user_properties', portal)
        records = [r for r in soup.data.items()]

        result = {}
        user_properties_utility = getUtility(ICatalogFactory,
                                             name='user_properties')
        extender_name = api.portal.get_registry_record(
            'genweb.controlpanel.core.IGenwebCoreControlPanelSettings.user_properties_extender'
        )
        for record in records:

            username = record[1].attrs['username']
            user = api.user.get(username=username)
            rendered_properties = []
            if extender_name in [
                    a[0] for a in getUtilitiesFor(ICatalogFactory)
            ]:
                extended_user_properties_utility = getUtility(
                    ICatalogFactory, name=extender_name)
                for prop in extended_user_properties_utility.directory_properties:
                    userProp = user.getProperty(prop, '')
                    if userProp:
                        rendered_properties.append(
                            dict(name=prop,
                                 value=userProp,
                                 icon=extended_user_properties_utility.
                                 directory_icons[prop]))
            else:
                # If it's not extended, then return the simple set of data we know
                # about the user using also the directory_properties field
                for prop in user_properties_utility.directory_properties:
                    try:
                        userProp = user.getProperty(prop, '')
                        if userProp:
                            rendered_properties.append(
                                dict(
                                    name=prop,
                                    value=userProp,
                                    icon=user_properties_utility.
                                    directory_icons[prop],
                                ))
                    except:
                        # Some users has @ in the username and is not valid...
                        pass
            result[record[1].attrs['id']] = rendered_properties

        return ApiResponse(result)
Ejemplo n.º 15
0
    def PUT(self):
        """
            Subscribes a bunch of users to a community the security is given an
            initial soft check for authenticated users at the view level and
            then by checking explicitly if the requester user has permission on
            the target community.
        """

        self.update_subscriptions()

        # Response successful
        success_response = 'Updated community "{}" subscriptions'.format(
            self.target.absolute_url())
        logger.info(success_response)
        return ApiResponse.from_string(success_response)
Ejemplo n.º 16
0
    def create_event(self, eventid, title, desc, body, date_start, date_end):
        date_start = date_start.split('/')
        time_start = date_start[3].split(':')
        date_end = date_end.split('/')
        time_end = date_end[3].split(':')
        portal_url = api.portal.get()
        news_url = portal_url['events']
        pc = api.portal.get_tool('portal_catalog')
        brains = pc.unrestrictedSearchResults(portal_type='Event', id=eventid)
        if not brains:
            new_event = createContentInContainer(
                news_url,
                'Event',
                title=eventid,
                start=datetime(int(date_start[2]), int(date_start[1]),
                               int(date_start[0]), int(time_start[0]),
                               int(time_start[1])),
                end=datetime(int(date_end[2]), int(date_end[1]),
                             int(date_end[0]), int(time_end[0]),
                             int(time_end[1])),
                timezone="Europe/Madrid",
                checkConstraints=False)
            new_event.title = title
            new_event.description = desc
            new_event.text = IRichText['text'].fromUnicode(body)
            new_event.reindexObject()
            resp = ApiResponse.from_string('Event {} created'.format(eventid),
                                           code=201)
        else:
            event = brains[0].getObject()
            event.title = title
            event.text = IRichText['text'].fromUnicode(body)
            event.reindexObject()
            resp = ApiResponse.from_string('Event {} updated'.format(eventid))

        return resp
Ejemplo n.º 17
0
    def GET(self):
        """ Launch an editacl SAVE process on all communities """
        pc = api.portal.get_tool('portal_catalog')
        communities = pc.unrestrictedSearchResults(
            portal_type='ulearn.community')
        results = []
        communities_ok = []
        communities_error = []
        for item in communities:
            try:
                self.target = item._unrestrictedGetObject()
                self.payload = ICommunityACL(self.target)().attrs.get(
                    'acl', '')
                print '--- Community: ' + str(self.target.absolute_url())
                print '---- Payload: ' + str(self.payload)
                adapter = self.target.adapted(request=self.request)
                adapter.update_acl(self.payload)
                users = self.payload['users']
                users_checked = []

                for user in users:
                    try:
                        adapter.update_acl_atomic(user['id'], user['role'])
                        users_checked.append(
                            str(user['id']) + ' as role ' + str(user['role']))
                    except:
                        raise BadParameters(user)

                acl = adapter.get_acl()
                adapter.set_plone_permissions(acl)
                adapter.update_hub_subscriptions()
                updated = 'Updated community subscriptions on: "{}" '.format(
                    self.target.absolute_url())
                logger.info(updated)
                communities_ok.append(
                    dict(url=self.target.absolute_url(),
                         users_checked=users_checked))
            except:
                error = 'Error updating community subscriptions on: "{}" '.format(
                    self.target.absolute_url())
                logger.error(error)
                communities_error.append(self.target.absolute_url())

        results.append(
            dict(successfully_updated_communities=communities_ok,
                 error_updating_communities=communities_error))

        return ApiResponse(results)
Ejemplo n.º 18
0
    def POST(self):
        params = {}
        params['nom'] = self.params.pop('title')
        params['community_type'] = self.params.pop('community_type')
        params['description'] = self.params.pop('description', None)
        params['image'] = self.params.pop('image', None)
        params['activity_view'] = self.params.pop('activity_view', None)
        params['twitter_hashtag'] = self.params.pop('twitter_hashtag', None)
        params['notify_activity_via_push'] = self.params.pop('notify_activity_via_push', None)
        params['notify_activity_via_push_comments_too'] = self.params.pop('notify_activity_via_push_comments_too', None)

        pc = api.portal.get_tool('portal_catalog')
        nom = safe_unicode(params['nom'])
        util = queryUtility(IIDNormalizer)
        id_normalized = util.normalize(nom, max_length=500)
        result = pc.unrestrictedSearchResults(portal_type='ulearn.community',
                                              id=id_normalized)

        imageObj = ''
        if params['image']:
            mime = MimeTypes()
            mime_type = mime.guess_type(params['image'])
            imgName = (params['image'].split('/')[-1]).decode('utf-8')
            imgData = requests.get(params['image']).content
            imageObj = NamedBlobImage(data=imgData,
                                      filename=imgName,
                                      contentType=mime_type[0])

        if result:
            # community = result[0].getObject()
            success_response = 'Community already exists.'
            status = 200
        else:
            new_community_id = self.context.invokeFactory('ulearn.community', id_normalized,
                                                          title=params['nom'],
                                                          description=params['description'],
                                                          image=imageObj,
                                                          community_type=params['community_type'],
                                                          activity_view=params['activity_view'],
                                                          twitter_hashtag=params['twitter_hashtag'],
                                                          notify_activity_via_push=True if params['notify_activity_via_push'] == 'True' else None,
                                                          notify_activity_via_push_comments_too=True if params['notify_activity_via_push_comments_too'] == 'True' else None,
                                                          checkConstraints=False)
            new_community = self.context[new_community_id]
            success_response = 'Created community "{}" with hash "{}".'.format(new_community.absolute_url(), sha1(new_community.absolute_url()).hexdigest())
            status = 201
        logger.info(success_response)
        return ApiResponse.from_string(success_response, code=status)
Ejemplo n.º 19
0
    def DELETE(self):
        # # Check if there's a valid community with the requested hash
        # lookedup_obj = self.lookup_community()
        # if lookedup_obj is not True:
        #     return lookedup_obj
        #
        # # Hard security validation as the view is soft checked
        # check_permission = self.check_roles(self.community, ['Owner', 'Manager'])
        # if check_permission is not True:
        #     return check_permission

        self.remove_subscriptions()

        # Response successful
        success_response = 'Unsubscription to the requested community done.'
        logger.info(success_response)
        return ApiResponse.from_string(success_response, code=200)
Ejemplo n.º 20
0
    def DELETE(self):
        # # Check if there's a valid community with the requested hash
        # lookedup_obj = self.lookup_community()
        # if lookedup_obj is not True:
        #     return lookedup_obj
        #
        # # Hard security validation as the view is soft checked
        # check_permission = self.check_roles(self.community, ['Owner', 'Manager'])
        # if check_permission is not True:
        #     return check_permission

        self.remove_subscriptions()

        # Response successful
        success_response = 'Unsubscription to the requested community done.'
        logger.info(success_response)
        return ApiResponse.from_string(success_response, code=200)
Ejemplo n.º 21
0
    def GET(self):
        """ Returns all the user communities and the open ones. """

        # Hard security validation as the view is soft checked
        # check_permission = self.check_roles(roles=['Member', 'Manager'])
        # if check_permission is not True:
        #     return check_permission

        # Get all communities for the current user
        pc = api.portal.get_tool('portal_catalog')
        r_results = pc.searchResults(
            portal_type='ulearn.community',
            community_type=[u'Closed', u'Organizative'])
        ur_results = pc.unrestrictedSearchResults(
            portal_type='ulearn.community', community_type=u'Open')
        communities = r_results + ur_results

        self.is_role_manager = False
        self.username = api.user.get_current().id
        global_roles = api.user.get_roles()
        if 'Manager' in global_roles:
            self.is_role_manager = True

        result = []
        favorites = self.get_favorites()
        for brain in communities:
            if brain.community_type == 'Closed':
                community_type = 'WOP Team'
            if brain.community_type == 'Open':
                community_type = 'Community of Practice'
            if brain.community_type == 'Organizative':
                community_type = 'Corporate'
            community = dict(
                id=brain.id,
                title=brain.Title,
                description=brain.Description,
                url=brain.getURL(),
                gwuuid=brain.gwuuid,
                type=community_type,
                image=brain.image_filename if brain.image_filename else False,
                favorited=brain.id in favorites,
                can_manage=self.is_community_manager(brain))
            result.append(community)

        return ApiResponse(result)
Ejemplo n.º 22
0
    def GET(self):
        """ Returns all communities """

        # Get all communities
        pc = api.portal.get_tool('portal_catalog')
        communities = pc.unrestrictedSearchResults(
            portal_type='ulearn.community')

        result = []
        for brain in communities:
            object_community = brain.getObject()
            try:
                community = dict(
                    id=brain.id,
                    title=brain.Title,
                    description=brain.Description,
                    url=brain.getURL(),
                    gwuuid=brain.gwuuid,
                    type=brain.community_type,
                    image=brain.image_filename
                    if brain.image_filename else False,
                    listCreators=brain.listCreators,
                    ModificationDate=brain.ModificationDate,
                    CreationDate=brain.CreationDate,
                    favoritedBy=str(brain.favoritedBy),
                    community_hash=brain.community_hash,
                    is_shared=brain.is_shared,
                    Creator=brain.Creator,
                    UID=brain.UID,
                    editacl=self.get_editacl(brain),
                    twitter_hashtag=object_community.twitter_hashtag,
                    notify_activity_via_push=object_community.
                    notify_activity_via_push,
                    notify_activity_via_push_comments_too=object_community.
                    notify_activity_via_push_comments_too,
                    activity_view=object_community.activity_view,
                    rawimage=b64encode(object_community.image.data)
                    if object_community.image else '')
                result.append(community)
            except:
                logger.info('HA FALLAT LA COMUNITAT {}'.format(brain.id))

        return ApiResponse(result)
Ejemplo n.º 23
0
    def GET(self):
        """

        """
        portal = api.portal.get()
        soup = get_soup('communities_acl', portal)
        records = [r for r in soup.query(Eq('groups', self.params['group']))]

        result = []
        for record in records:
            users = [user['id'] for user in record.attrs['acl']['users']]
            result.append(
                dict(
                    url=record.attrs['hash'],
                    groups=record.attrs['groups'],
                    users=users,
                ))

        return ApiResponse(result)
Ejemplo n.º 24
0
    def GET(self):
        """
            Get the subscriptions for the community. The security is given an
            initial soft check for authenticated users at the view level and
            then by checking explicitly if the requester user has permission on
            the target community.
        """
        # Lookup for object
        # lookedup_obj = self.lookup_community()
        # if lookedup_obj is not True:
        #     return lookedup_obj

        # Hard security validation as the view is soft checked
        # check_permission = self.check_roles(self.community, ['Owner', 'Manager'])
        # if check_permission is not True:
        #     return check_permission
        result = ICommunityACL(self.target)().attrs.get('acl', '')

        return ApiResponse(result)
Ejemplo n.º 25
0
    def GET(self):
        """ Returns the user profile values. """
        username = self.params['username']
        user = api.user.get(username=username)

        user_properties_utility = getUtility(ICatalogFactory,
                                             name='user_properties')

        rendered_properties = []
        try:
            extender_name = api.portal.get_registry_record(
                'genweb.controlpanel.core.IGenwebCoreControlPanelSettings.user_properties_extender'
            )
            if extender_name in [
                    a[0] for a in getUtilitiesFor(ICatalogFactory)
            ]:
                extended_user_properties_utility = getUtility(
                    ICatalogFactory, name=extender_name)
                for prop in extended_user_properties_utility.directory_properties:
                    userProp = user.getProperty(prop, '')
                    if userProp:
                        rendered_properties.append(
                            dict(name=prop,
                                 value=userProp,
                                 icon=extended_user_properties_utility.
                                 directory_icons[prop]))
            else:
                # If it's not extended, then return the simple set of data we know
                # about the user using also the profile_properties field
                for prop in user_properties_utility.directory_properties:
                    userProp = user.getProperty(prop, '')
                    if userProp:
                        rendered_properties.append(
                            dict(name=prop,
                                 value=userProp,
                                 icon=user_properties_utility.
                                 directory_icons[prop]))
        except:
            raise ObjectNotFound('User not found')

        return ApiResponse(rendered_properties)
Ejemplo n.º 26
0
    def POST(self):
        """
            Subscribes a bunch of users to a community the security is given an
            initial soft check for authenticated users at the view level and
            then by checking explicitly if the requester user has permission on
            the target community.
        """
        # Lookup for object
        # lookedup_obj = self.lookup_community()
        # if lookedup_obj is not True:
        #     return lookedup_obj

        # Hard security validation as the view is soft checked
        # check_permission = self.check_roles(self.community, ['Owner', 'Manager'])
        # if check_permission is not True:
        #     return check_permission

        self.set_subscriptions()

        # Response successful
        success_response = 'Updated community "{}" subscriptions'.format(self.target.absolute_url())
        logger.info(success_response)
        return ApiResponse.from_string(success_response)
Ejemplo n.º 27
0
    def POST(self):
        """
            Subscribes a bunch of users to a community the security is given an
            initial soft check for authenticated users at the view level and
            then by checking explicitly if the requester user has permission on
            the target community.
        """
        # Lookup for object
        # lookedup_obj = self.lookup_community()
        # if lookedup_obj is not True:
        #     return lookedup_obj

        # Hard security validation as the view is soft checked
        # check_permission = self.check_roles(self.community, ['Owner', 'Manager'])
        # if check_permission is not True:
        #     return check_permission

        self.set_subscriptions()

        # Response successful
        success_response = 'Updated community "{}" subscriptions'.format(
            self.target.absolute_url())
        logger.info(success_response)
        return ApiResponse.from_string(success_response)
Ejemplo n.º 28
0
    def GET(self):
        """ Expanded bitly links """
        url = self.params['url']
        session = requests.Session()
        resp = session.head(url, allow_redirects=True)
        if 'came_from' in resp.url:
            expanded = resp.url.split('came_from=')[1].replace('%3A', ':')
        else:
            expanded = resp.url

        portal = api.portal.get()
        local_url = portal.absolute_url()
        results = []
        if local_url in expanded:
            item_id = expanded.split(local_url)[1][1:]
            mountpoint_id = self.context.getPhysicalPath()[1]
            if mountpoint_id == self.context.id:
                item_path = api.portal.getSite().absolute_url_path(
                ) + '/' + item_id
            else:
                item_path = '/' + mountpoint_id + '/' + api.portal.get(
                ).id + '/' + item_id
            if item_path[-5:] == '/view':
                item_path = item_path.replace('/view', '')

            try:
                # Check if value deleted / moved --> NOT FOUND!
                item_found = api.content.find(path=item_path)[0]
            except:
                item_found = False

            if item_found:
                value = item_found
                item = value.getObject()
                text = image = image_caption = ''
                raw_image = content_type = ''

                external_url = False
                if value.portal_type == 'News Item':
                    text = item.text.output
                    image_caption = item.image_caption
                    image = item.image.filename
                elif value.portal_type == 'Image':
                    image = item.image.filename
                    raw_image = b64encode(item.image.data),
                    content_type = item.image.contentType
                elif value.portal_type == 'Document':
                    text = item.text.output
                elif value.portal_type == 'Link':
                    text = item.remoteUrl
                    external_url = True
                elif value.portal_type == 'Event':
                    text = item.text.output
                    external_url = True
                elif value.portal_type == 'File':
                    text = ''
                    external_url = True
                else:
                    text = ''
                    external_url = True

                new = dict(title=value.Title,
                           id=value.id,
                           description=value.Description,
                           portal_type=value.portal_type,
                           external_url=external_url,
                           absolute_url=expanded,
                           text=text,
                           item_not_found=False,
                           image_caption=image_caption,
                           image=image,
                           raw_image=raw_image,
                           content_type=content_type)
                results.append(new)
            else:
                new = dict(title='',
                           id='',
                           description='',
                           portal_type='',
                           external_url=False,
                           absolute_url='',
                           text='ITEM NOT FOUND',
                           item_not_found=True,
                           image_caption='',
                           image='',
                           raw_image='',
                           content_type='')
                results.append(new)
        else:
            # Bit.ly object linked is from outside this Community
            # Only reports url
            value = api.content.find(path=local_url)
            new = dict(title='',
                       id='',
                       description='',
                       portal_type='',
                       external_url=True,
                       absolute_url=expanded,
                       text='',
                       item_not_found=False,
                       image_caption='',
                       image='',
                       raw_image='',
                       content_type='')
            results.append(new)

        return ApiResponse(results)
Ejemplo n.º 29
0
    def POST(self):
        """
            Syncs user local registry with remote ldap attributes
        """
        maxclient, settings = getUtility(IMAXClient)()
        maxclient.setActor(settings.max_restricted_username)
        maxclient.setToken(settings.max_restricted_token)
        users = self.params['users']

        notfound_errors = []
        properties_errors = []
        max_errors = []
        users_sync = []
        for userid in users:
            username = userid.lower()
            logger.info(
                '- API REQUEST /api/people/sync: Synchronize user {}'.format(
                    username))
            user_memberdata = api.user.get(username=username)
            try:
                plone_user = user_memberdata.getUser()
            except:
                logger.info(
                    '- API REQUEST /api/people/sync: ERROR sync user {}'.
                    format(username))
                notfound_errors.append(username)
                continue

            # Delete user cache
            for prop in plone_user.getOrderedPropertySheets():
                try:
                    ldap = prop
                    ldap._invalidateCache(plone_user)
                    plone_user._getPAS().ZCacheable_invalidate(
                        view_name='_findUser-' + username)
                    ldap._getLDAPUserFolder(plone_user)._expireUser(plone_user)
                    break
                except:
                    continue

            response = {}
            try:
                user_memberdata = api.user.get(username=username)
                plone_user = user_memberdata.getUser()
            except:
                notfound_errors.append(username)
                logger.error(
                    'User {} cannot be found in LDAP repository'.format(
                        username))
            else:
                try:
                    properties = get_all_user_properties(plone_user)
                    add_user_to_catalog(plone_user, properties, overwrite=True)
                except:
                    logger.error(
                        'Cannot update properties catalog for user {}'.format(
                            username))
                    properties_errors.append(username)

                try:
                    fullname = properties.get('fullname', '')
                    maxclient.people.post(username=username,
                                          displayName=fullname)

                    # If user hasn't been created right now, update displayName
                    if maxclient.last_response_code == 200:
                        maxclient.people[username].put(displayName=fullname)
                    users_sync.append(username)
                    logger.info(
                        '- API REQUEST /api/people/sync: OK sync user {}'.
                        format(username))
                except:
                    logger.error(
                        'User {} couldn\'t be created or updated on max'.
                        format(username))
                    max_errors.append(username)

        response = {}
        if notfound_errors:
            response['not_found'] = notfound_errors
        if properties_errors:
            response['properties_errors'] = properties_errors
        if max_errors:
            response['max_errors'] = max_errors
        response['synced_users'] = users_sync

        return ApiResponse(response)
Ejemplo n.º 30
0
    def create_new(self, newid, title, desc, body, imgData, imgName, date_start, date_end):
        date_start = date_start.split('/')
        time_start = date_start[3].split(':')

        portal_url = api.portal.get()
        news_url = portal_url['news']
        pc = api.portal.get_tool('portal_catalog')
        brains = pc.unrestrictedSearchResults(portal_type='News Item', id=newid)
        if not brains:
            if imgName != '':
                new_new = createContentInContainer(news_url,
                                                   'News Item',
                                                   title=newid,
                                                   image=NamedBlobImage(data=imgData,
                                                                        filename=imgName,
                                                                        contentType='image/jpeg'),
                                                   description=desc,
                                                   timezone="Europe/Madrid",
                                                   checkConstraints=False)
            else:
                new_new = createContentInContainer(news_url,
                                                   'News Item',
                                                   title=newid,
                                                   description=desc,
                                                   timezone="Europe/Madrid",
                                                   checkConstraints=False)
            new_new.title = title
            new_new.setEffectiveDate(datetime(int(date_start[2]),
                                              int(date_start[1]),
                                              int(date_start[0]),
                                              int(time_start[0]),
                                              int(time_start[1])
                                              )
                                     )
            if date_end:
                date_end = date_end.split('/')
                time_end = date_end[3].split(':')
                new_new.setExpirationDate(datetime(int(date_end[2]),
                                                   int(date_end[1]),
                                                   int(date_end[0]),
                                                   int(time_end[0]),
                                                   int(time_end[1])
                                                   )
                                          )
            new_new.text = IRichText['text'].fromUnicode(body)
            new_new.reindexObject()
            resp = ApiResponse.from_string('News Item {} created'.format(newid), code=201)
        else:
            new = brains[0].getObject()
            new.title = title
            new.description = desc
            new.setEffectiveDate(datetime(int(date_start[2]),
                                          int(date_start[1]),
                                          int(date_start[0]),
                                          int(time_start[0]),
                                          int(time_start[1])
                                          )
                                 )
            if date_end:
                new.setExpirationDate(datetime(int(date_end[2]),
                                               int(date_end[1]),
                                               int(date_end[0]),
                                               int(time_end[0]),
                                               int(time_end[1])
                                               )
                                      )
            if imgName != '':
                new.image = NamedBlobImage(data=imgData,
                                           filename=imgName,
                                           contentType='image/jpeg')
            new.text = IRichText['text'].fromUnicode(body)
            new.reindexObject()
            resp = ApiResponse.from_string('News Item {} updated'.format(newid), code=200)

        return resp
Ejemplo n.º 31
0
    def GET(self):
        show_news_in_app = api.portal.get_registry_record(name='ulearn.core.controlpanel.IUlearnControlPanelSettings.show_news_in_app')
        if show_news_in_app:
            newid = self.params['newid']
            mountpoint_id = self.context.getPhysicalPath()[1]
            if mountpoint_id == self.context.id:
                default_path = api.portal.get().absolute_url_path() + '/news'
            else:
                default_path = '/' + mountpoint_id + '/' + api.portal.get().id + '/news'
            item = api.content.find(portal_type="News Item", path=default_path, id=newid)
            if item:
                newitem = item[0]
                value = newitem.getObject()
                if value.effective_date:
                    date = value.effective_date.strftime("%d/%m/%Y")
                else:
                    date = value.creation_date.strftime("%d/%m/%Y")
                if value.text:
                    text = value.text.output
                else:
                    text = ''

                is_inapp = None
                is_outoflist = None
                is_flash = None
                is_important = None
                filename = None
                contentType = None
                raw_image = None

                if getattr(newitem, 'is_inapp', None):
                    is_inapp = newitem.is_inapp
                if getattr(newitem, 'is_outoflist', None):
                    is_outoflist = newitem.is_outoflist
                if getattr(newitem, 'is_flash', None):
                    is_flash = newitem.is_flash
                if getattr(newitem, 'is_important', None):
                    is_important = newitem.is_important
                if getattr(value, 'image', None):
                    filename = value.image.filename
                    contentType = value.image.contentType
                    raw_image = value.absolute_url() + '/thumbnail-image'

                new = dict(title=value.title,
                           id=value.id,
                           description=value.description,
                           path=value.absolute_url(),
                           absolute_url=value.absolute_url_path(),
                           text=text,
                           filename=filename,
                           caption=value.image_caption,
                           is_inapp=is_inapp,
                           is_outoflist=is_outoflist,
                           is_flash=is_flash,
                           is_important=is_important,
                           effective_date=date,
                           creators=value.creators,
                           content_type=contentType,
                           raw_image=raw_image,
                           )
            else:
                raise ObjectNotFound('News Item not found')
            return ApiResponse(new)
        else:
            return ApiResponse.from_string('Show in App not enabled on this site', code=404)
Ejemplo n.º 32
0
    def create_new(self, newid, title, desc, body, imgData, imgName, date_start, date_end):
        date_start = date_start.split('/')
        time_start = date_start[3].split(':')

        portal_url = api.portal.get()
        news_url = portal_url['news']
        pc = api.portal.get_tool('portal_catalog')
        brains = pc.unrestrictedSearchResults(portal_type='News Item', id=newid)
        if not brains:
            if imgName != '':
                new_new = createContentInContainer(news_url,
                                                   'News Item',
                                                   title=newid,
                                                   image=NamedBlobImage(data=imgData,
                                                                        filename=imgName,
                                                                        contentType='image/jpeg'),
                                                   description=desc,
                                                   timezone="Europe/Madrid",
                                                   checkConstraints=False)
            else:
                new_new = createContentInContainer(news_url,
                                                   'News Item',
                                                   title=newid,
                                                   description=desc,
                                                   timezone="Europe/Madrid",
                                                   checkConstraints=False)
            new_new.title = title
            new_new.setEffectiveDate(datetime(int(date_start[2]),
                                              int(date_start[1]),
                                              int(date_start[0]),
                                              int(time_start[0]),
                                              int(time_start[1])
                                              )
                                     )
            if date_end:
                date_end = date_end.split('/')
                time_end = date_end[3].split(':')
                new_new.setExpirationDate(datetime(int(date_end[2]),
                                                   int(date_end[1]),
                                                   int(date_end[0]),
                                                   int(time_end[0]),
                                                   int(time_end[1])
                                                   )
                                          )
            new_new.text = IRichText['text'].fromUnicode(body)
            new_new.reindexObject()
            resp = ApiResponse.from_string('News Item {} created'.format(newid), code=201)
        else:
            new = brains[0].getObject()
            new.title = title
            new.description = desc
            new.setEffectiveDate(datetime(int(date_start[2]),
                                          int(date_start[1]),
                                          int(date_start[0]),
                                          int(time_start[0]),
                                          int(time_start[1])
                                          )
                                 )
            if date_end:
                new.setExpirationDate(datetime(int(date_end[2]),
                                               int(date_end[1]),
                                               int(date_end[0]),
                                               int(time_end[0]),
                                               int(time_end[1])
                                               )
                                      )
            if imgName != '':
                new.image = NamedBlobImage(data=imgData,
                                           filename=imgName,
                                           contentType='image/jpeg')
            new.text = IRichText['text'].fromUnicode(body)
            new.reindexObject()
            resp = ApiResponse.from_string('News Item {} updated'.format(newid), code=200)

        return resp
Ejemplo n.º 33
0
    def GET(self):
        show_news_in_app = api.portal.get_registry_record(name='ulearn.core.controlpanel.IUlearnControlPanelSettings.show_news_in_app')
        if show_news_in_app:
            newid = self.params['newid']
            mountpoint_id = self.context.getPhysicalPath()[1]
            if mountpoint_id == self.context.id:
                default_path = api.portal.get().absolute_url_path() + '/news'
            else:
                default_path = '/' + mountpoint_id + '/' + api.portal.get().id + '/news'
            item = api.content.find(portal_type="News Item", path=default_path, id=newid)
            if item:
                newitem = item[0]
                value = newitem.getObject()
                if value.effective_date:
                    date = value.effective_date.strftime("%d/%m/%Y")
                else:
                    date = value.creation_date.strftime("%d/%m/%Y")
                if value.text:
                    text = value.text.output
                else:
                    text = ''

                is_inapp = None
                is_outoflist = None
                is_flash = None
                is_important = None
                filename = None
                contentType = None
                raw_image = None

                if getattr(newitem, 'is_inapp', None):
                    is_inapp = newitem.is_inapp
                if getattr(newitem, 'is_outoflist', None):
                    is_outoflist = newitem.is_outoflist
                if getattr(newitem, 'is_flash', None):
                    is_flash = newitem.is_flash
                if getattr(newitem, 'is_important', None):
                    is_important = newitem.is_important
                if getattr(value, 'image', None):
                    filename = value.image.filename
                    contentType = value.image.contentType
                    raw_image = value.absolute_url() + '/thumbnail-image'

                new = dict(title=value.title,
                           id=value.id,
                           description=value.description,
                           path=value.absolute_url(),
                           absolute_url=value.absolute_url_path(),
                           text=text,
                           filename=filename,
                           caption=value.image_caption,
                           is_inapp=is_inapp,
                           is_outoflist=is_outoflist,
                           is_flash=is_flash,
                           is_important=is_important,
                           effective_date=date,
                           creators=value.creators,
                           content_type=contentType,
                           raw_image=raw_image,
                           )
            else:
                raise ObjectNotFound('News Item not found')
            return ApiResponse(new)
        else:
            return ApiResponse.from_string('Show in App not enabled on this site', code=404)
Ejemplo n.º 34
0
    def GET(self):
        show_news_in_app = api.portal.get_registry_record(name='ulearn.core.controlpanel.IUlearnControlPanelSettings.show_news_in_app')
        results = []
        news_per_page = 10  # Default items per page
        pagination_page = self.params.pop('page', None)
        more_items = False
        total_news = 0
        if show_news_in_app:
            mountpoint_id = self.context.getPhysicalPath()[1]
            if mountpoint_id == self.context.id:
                default_path = api.portal.get().absolute_url_path() + '/news'
            else:
                default_path = '/' + mountpoint_id + '/' + api.portal.get().id + '/news'
            total_news = len(api.content.find(
                portal_type="News Item",
                path=default_path,
                sort_order='descending',
                sort_on='effective',
                is_inapp=True))
            if pagination_page:
                # Si page = 0, devolvemos la ?page=1 (que es lo mismo)
                if pagination_page == '0':
                    pagination_page = 1
                start = int(news_per_page) * (int(pagination_page) - 1)
                end = int(news_per_page) * int(pagination_page)
                # Devolvemos paginando
                news = api.content.find(
                    portal_type="News Item",
                    path=default_path,
                    sort_order='descending',
                    sort_on='effective',
                    is_inapp=True)[start:end]
                if end < total_news:
                    more_items = True
            else:
                # No paginammos, solo devolvemos 10 primeras => ?page=1
                news = api.content.find(
                    portal_type="News Item",
                    path=default_path,
                    sort_order='descending',
                    sort_on='effective',
                    is_inapp=True)[0:news_per_page]
                if news_per_page < total_news:
                    more_items = True
            for item in news:
                value = item.getObject()
                if value.effective_date:
                    date = value.effective_date.strftime("%d/%m/%Y")
                else:
                    date = value.creation_date.strftime("%d/%m/%Y")
                if value.text:
                    text = value.text.output
                else:
                    text = ''

                is_inapp = None
                is_outoflist = None
                is_flash = None
                is_important = None
                filename = None
                contentType = None
                raw_image = None

                if getattr(item, 'is_inapp', None):
                    is_inapp = item.is_inapp
                if getattr(item, 'is_outoflist', None):
                    is_outoflist = item.is_outoflist
                if getattr(item, 'is_flash', None):
                    is_flash = item.is_flash
                if getattr(item, 'is_important', None):
                    is_important = item.is_important
                if getattr(value, 'image', None):
                    filename = value.image.filename
                    contentType = value.image.contentType
                    raw_image = value.absolute_url() + '/thumbnail-image'

                new = dict(title=value.title,
                           id=value.id,
                           description=value.description,
                           path=item.getURL(),
                           absolute_url=value.absolute_url_path(),
                           text=text,
                           filename=filename,
                           caption=value.image_caption,
                           is_inapp=is_inapp,
                           is_outoflist=is_outoflist,
                           is_flash=is_flash,
                           is_important=is_important,
                           effective_date=date,
                           creators=value.creators,
                           raw_image=raw_image,
                           content_type=contentType,
                           )
                results.append(new)
        values = dict(items=results,
                      more_items=more_items,
                      total_news=total_news)
        return ApiResponse(values)