Ejemplo n.º 1
0
 def __init__(self, context, request):
     self.context = context
     self.request = request
     self.username = authenticated_userid(request)
     self.path = model_path(context)
     self.catalog = find_catalog(context)
     self.tags = find_tags(context)
Ejemplo n.º 2
0
def cleanup_content_tags(obj, docids):
    """ Remove any tags associated with 'docids'.
    """
    tags = find_tags(obj)
    if tags is not None:
        for docid in docids:
            tags.delete(item=docid)
Ejemplo n.º 3
0
def del_tags(context, request, values):
    """ Delete the specified tags.
    """
    username = authenticated_userid(request)
    path = model_path(context)
    catalog = find_catalog(context)
    docid = catalog.document_map.docid_for_address(path)
    tags = find_tags(context)
    for tag in values:
        tags.delete(item=docid, user=username, tag=tag)
Ejemplo n.º 4
0
def _getInfo(profile, content, ifaces=None):
    ifaces = ifaces or find_events(content).supported_ctx_ifaces()
    context = find_supported_interface(content, ifaces)
    if context is None:
        context_name = context_url = context_creator = context_type = None
    else:
        context_name = context.title
        context_url = model_path(context)
        context_creator = context.creator
        context_type = get_content_type(context)
    tagger = find_tags(content)
    if tagger is not None:
        cloud = list(tagger.getCloud(items=(content.docid,)))
        tag_counts = sorted(cloud, key=lambda x: x[1], reverse=True)[:3]
        tags = [x[0] for x in tag_counts]
    else:
        tags = ()
    content_type = get_content_type(content)
    desc = getattr(content, 'description', '')
    short = len(desc) > 80 and '%s...' % desc[:80] or desc
    if IPosts.providedBy(content):
        comment_count = len(content.get('comments', ()))
    else:
        comment_count = False
    content_creator = profile.__name__
    if IComment.providedBy(content):
        # my content filter needs to know if a comment was made inside my post
        content_creator = content.__parent__.__parent__.creator

    if hasattr(content, 'likes'):
        likes = len(content.likes)
    else:
        likes = 0
        
    return {'content_type': content_type.getTaggedValue('name'),
            'userid': profile.__name__,
            'context_name': context_name,
            'context_url': context_url,
            'context_creator': context_creator,
             'context_type': context_type.getTaggedValue('name') if context_type else None, 
            'content_creator': content_creator,
            'url': model_path(content),
            'title': content.title,
            'description': desc,
            'short_description': short,
            'allowed':
                principals_allowed_by_permission(content, 'view'),
            'comment_count': comment_count,
            'tags': tags,                 #XXX
            'author': profile.title,
            'profile_url': '/profiles/%s' % profile.__name__,
            'thumbnail': '/profiles/%s/profile_thumbnail' % profile.__name__,
            'timestamp': _NOW(),
            'likes':likes
           }
Ejemplo n.º 5
0
def set_tags(context, request, values):
    """ Set the specified tags, previously removing any existing tags.
    """
    if values is None:
        values = ()
    username = authenticated_userid(request)
    path = model_path(context)
    catalog = find_catalog(context)
    docid = getattr(context, 'docid', None) or catalog.document_map.docid_for_address(path)
    tags = find_tags(context)
    if tags is not None and docid is not None: # testing
        tags.update(item=docid, user=username, tags=values)
Ejemplo n.º 6
0
def manage_tags_view(context, request):
    page_title = 'Manage Tags'
    api = request.api
    api.page_title = page_title
    tagger = find_tags(context)
    userid = context.__name__
    error = ''
    old = ''
    new = ''

    if 'form.rename' in request.POST and 'old_tag' in request.POST:
        old_tag = request.POST['old_tag']
        new_tag = request.POST['new_tag']
        # check that tag contains only valid characters
        if re_tag.match(new_tag) is None:
            error = u'Value contains characters that are not allowed in a tag.'
            old = old_tag
            new = new_tag
        else:
            docids = tagger.getItems(tags=[old_tag], users=[userid])
            to_update = {}
            for tagob in tagger.getTagObjects(items=docids, users=[userid]):
                if tagob.name == old_tag:
                    name = new_tag
                else:
                    name = tagob.name
                to_update.setdefault(tagob.item, []).append(name)
            for docid in docids:
                tagger.update(item=docid, user=userid,
                              tags=to_update.get(docid, []))

    if 'form.delete' in request.POST and 'old_tag' in request.POST:
        old_tag = request.POST['old_tag']
        for docid in tagger.getItems(tags=[old_tag], users=[userid]):
            tagger.delete(item=docid, user=userid, tag=old_tag)

    if tagger is None:
        tags = ()
    else:
        tags = list(tagger.getTags(users=(context.__name__,)))
        tags.sort()

    return dict(
        api=api,
        my_tags=tags,
        error=error,
        old=old,
        new=new,
        )
Ejemplo n.º 7
0
def tag_listing_view(context, request):
    page_title = 'Tag Listing'
    api = request.api
    api.page_title = page_title
    tags = find_tags(context)

    if tags is None:
        entries = ()
    else:
        entries = [{'name': x[0], 'count': x[1]} for x in tags.getFrequency()]
        entries.sort(key=lambda x: x['name'])

    return dict(
        api=api,
        entries=entries,
        )
Ejemplo n.º 8
0
def add_tags(context, request, values):
    """ Add the specified tags.

    o Existing tags remain assigned.
    """
    if values:
        if isinstance(values, basestring):
            values = [values]
        path = model_path(context)
        catalog = find_catalog(context)
        docid = catalog.document_map.docid_for_address(path)
        username = authenticated_userid(request)
        tags = find_tags(context)
        if tags is not None: # testing
            new = list(tags.getTags(items=(docid,), users=(username,)))
            new.extend(values)
            tags.update(item=docid, user=username, tags=new)
Ejemplo n.º 9
0
def tag_cloud_view(context, request):
    page_title = 'Tag Cloud'
    api = request.api
    api.page_title = page_title
    tags = find_tags(context)
    if tags is not None:
        cloud = [{'name': x[0], 'count': x[1]} for x in tags.getCloud()]
        limited = list(reversed(sorted(cloud, key=lambda x: x['count']))
                      )[:100]
        entries = sorted(_calculateTagWeights(limited),
                         key=lambda x: x['name'])
    else:
        entries = ()

    return dict(
        api=api,
        entries=entries,
        )
Ejemplo n.º 10
0
def community_tag_users_view(context, request):
    page_title = 'Tag Users'
    api = request.api
    api.page_title = page_title

    tag = request.params.get('tag', None)
    docid = request.params.get('docid', None)
    # Test for some cases
    if tag is None:
        return HTTPBadRequest('Missing parameter for tag')
    if docid is None:
        return HTTPBadRequest('Missing parameter for docid')

    docid = int(docid)
    tags = find_tags(context)
    profiles = find_profiles(context)
    catalog = find_catalog(context)
    address = catalog.document_map.address_for_docid(docid)
    target = find_model(context, address)
    if tags is not None and profiles is not None:
        users = []
        for userid in tags.getUsers(tags=[tag], items=[docid],
                                    community=context.__name__):
            profile = profiles[userid]
            fullname = profile.firstname + ' ' + profile.lastname
            also = [x for x in tags.getTags(items=[docid], users=[userid],
                                            community=context.__name__)
                         if x != tag]
            users.append({'login': userid,
                          'fullname': fullname,
                          'also': also,
                         })

    else:
        users = ()

    return dict(
        api=api,
        tag=tag,
        url=model_url(target, request),
        title=target.title,
        users=users,
        )
Ejemplo n.º 11
0
def community_tag_listing_view(context, request):
    page_title = 'Tag Listing'
    api = request.api
    api.page_title = page_title
    tags = find_tags(context)

    if tags is None:
        entries = ()
    else:
        entries = [{'name': x[0], 'count': x[1]}
                        for x in tags.getFrequency(community=context.__name__)]
        entries.sort(key=lambda x: x['name'])

    system_name = get_setting(context, 'system_name', 'KARL')
    return dict(
        api=api,
        entries=entries,
        crumbs='%s / Communities / %s' % (system_name, context.__name__),
        )
Ejemplo n.º 12
0
def community_tag_cloud_view(context, request):
    page_title = 'Tag Cloud'
    api = request.api
    api.page_title = page_title
    tags = find_tags(context)
    if tags is not None:
        cloud = [{'name': x[0], 'count': x[1]}
                    for x in tags.getCloud(community=context.__name__)]
        limited = list(reversed(sorted(cloud, key=lambda x: x['count']))
                      )[:100]
        entries = sorted(_calculateTagWeights(limited),
                         key=lambda x: x['name'])
    else:
        entries = ()

    system_name = get_setting(context, 'system_name', 'KARL')
    return dict(
        api=api,
        entries=entries,
        crumbs='%s / Communities / %s' % (system_name, context.__name__),
        )
Ejemplo n.º 13
0
    def __call__(self):

        profile_details = getUtility(IProfileDict, name='profile-details')
        profile_details.update_details(self.context, self.request, self.api,
                                       self.photo_thumb_size)

        context = self.context
        request = self.request
        api = self.api

        # provide client data for rendering current tags in the tagbox
        client_json_data = dict(
            tagbox = get_tags_client_data(context, request),
            )

        # Get communities this user is a member of, along with moderator info
        #
        communities = {}
        communities_folder = find_communities(context)
        user_info = find_users(context).get_by_id(context.__name__)
        if user_info is not None:
            for group in user_info["groups"]:
                if group.startswith("group.community:"):
                    unused, community_name, role = group.split(":")
                    if (communities.has_key(community_name) and
                        role != "moderators"):
                        continue

                    community = communities_folder.get(community_name, None)
                    if community is None:
                        continue

                    if has_permission('view', community, request):
                        communities[community_name] = {
                            "title": community.title,
                            "moderator": role == "moderators",
                            "url": model_url(community, request),
                        }

        communities = communities.values()
        communities.sort(key=lambda x:x["title"])

        preferred_communities = []
        my_communities = None
        name = context.__name__
        # is this the current user's profile?
        if authenticated_userid(request) == name:
            preferred_communities = get_preferred_communities(communities_folder,
                                                              request)
            my_communities = get_my_communities(communities_folder, request)

        tagger = find_tags(context)
        if tagger is None:
            tags = ()
        else:
            tags = []
            names = tagger.getTags(users=[context.__name__])
            for name, count in sorted(tagger.getFrequency(names,
                                                          user=context.__name__),
                                      key=lambda x: x[1],
                                      reverse=True,
                                     )[:10]:
                tags.append({'name': name, 'count': count})



        self.profile = profile_details
        self.communities = communities
        self.my_communities = my_communities or []
        self.preferred_communities = preferred_communities
        self.tags = tags
        self.actions = get_profile_actions(context,request)
        self.head_data = convert_to_script(client_json_data)
        return self.make_response()
Ejemplo n.º 14
0
 def tags(self):
     if self._tags is None:
         self._tags = find_tags(self.context)
     return self._tags
Ejemplo n.º 15
0
def showtag_view(context, request, community=None, user=None, crumb_title=None):
    """Show a page for a particular tag, optionally refined by context."""

    page_title = 'Show Tag'
    api = request.api
    api.page_title = page_title

    # The tag screens (cloud, listing, and this view) each have a
    # "jump box" that allows you to quickly jump to another tag.  All
    # three will point here at /showtag?tag=tag1.  We detect this mode
    # and do a redirect.
    jump_tag = request.params.get('jumptag', False)
    if jump_tag:
        location = model_url(context, request, request.view_name, jump_tag)
        return HTTPFound(location=location)

    # Our strategy is to support tag URLs that are like this:
    #     /showtag/tag1
    # ...instead of:
    #     /tagpage.html?tag=tag1
    # However, our tag data isn't traversable (it is site.tags and not
    # site['tags'].  So we have a view at /showtag that picks apart
    # the next hop in the URL.
    tag = request.subpath
    if not tag:
        # The user didn't provide anything beyond /showtag in the URL
        tag = None
        entries = related = []
    else:
        # Ahh, the good part.  Let's find some tag results and unpack
        # data into what the ZPT needs.
        tag = tag[0]
        page_title = 'Show Tag ' + tag

        catalog = find_catalog(context)
        dm = catalog.document_map
        tags = find_tags(context)
        related = tags.getRelatedTags(tag, user=user, community=community)
        entries = []
        if user:
            users = (user,)
        else:
            users = None
        for docid in tags.getItems(tags=(tag,), users=users,
                                   community=community,
                                   ):
            # XXX Need to wire in batching
            address = dm.address_for_docid(int(docid))
            if address is None:
                raise KeyError(docid)
            resource = find_model(context, address)

            # Skip documents which aren't viewable by authenticated user
            #if not has_permission('view', resource, request):
            #    continue

            # Do a secondary query for each result to find the
            # per-user info
            users = tags.getUsers(tags=(tag,), items=(docid,),
                                  community=community)
            if len(users) == 1:
                tuh = '1 person'
            else:
                tuh = '%s people' % len(users)

            tuhref = model_url(context, request, 'tagusers.html',
                               query={'tag': tag, 'docid': docid})
            entry = {
                'title': resource.title,
                'description': getattr(resource, 'description', ''),
                'href': model_url(resource, request),
                'type': get_content_type_name(resource),
                'tagusers_href': tuhref,
                'tagusers_count': tuh,
                }
            entries.append(entry)

    args = dict(
        api=api,
        tag=tag,
        entries=entries,
        related=related,
    )

    if crumb_title:
        # XXX Would context.title be a bit nicer for displaying to user?
        system_name = get_setting(context, 'system_name', 'KARL')
        args['crumbs'] = '%s / %s / %s' % (
            system_name, crumb_title, context.__name__)

    return dict(**args)