Exemplo n.º 1
0
def get_image_info(image, request, thumb_size=THUMB_SIZE):
    """Return the info about a particular image,
    in the format specified by the client's needs.

    This is used when:

        - a batch of images are returned

        - information about the succesfully uploaded
          image is returned

    """
    profiles = find_profiles(image)
    creator = profiles[image.creator]
    width, height = image.image_size
    image_url = urlparse.urlparse(thumb_url(image, request, DISPLAY_SIZE))

    return dict(
        name = image.__name__,
        title = image.title,
        author_name = creator.title,
        location = breadcrumbs(image, request),
        image_url = image_url.path,
        image_width = width,
        image_height = height,
        image_size = image.size,
        thumbnail_url = thumb_url(image, request, thumb_size),
        last_modified = image.modified.ctime(),  # XXX Format?
    )
Exemplo n.º 2
0
def get_image_info(image, request, thumb_size=THUMB_SIZE):
    """Return the info about a particular image,
    in the format specified by the client's needs.

    This is used when:

        - a batch of images are returned

        - information about the succesfully uploaded
          image is returned

    """
    profiles = find_profiles(image)
    creator = profiles[image.creator]
    width, height = image.image_size
    image_url = urlparse.urlparse(thumb_url(image, request, DISPLAY_SIZE))

    return dict(
        name = image.__name__,
        title = image.title,
        author_name = creator.title,
        location = breadcrumbs(image, request),
        image_url = image_url.path,
        image_width = width,
        image_height = height,
        image_size = image.size,
        thumbnail_url = thumb_url(image, request, thumb_size),
        last_modified = image.modified.ctime(),  # XXX Format?
    )
Exemplo n.º 3
0
    def __init__(self, context, request):
        super(AdvancedSearchResultsDisplayPeople,
              self).__init__(context, request)
        contact_items = []
        if context.extension and context.extension.strip():
            extension_html = (
                '<span class="sras-people-extension">x%s</span>' %
                context.extension)
            contact_items.append(extension_html)
        if context.room_no and context.room_no.strip():
            room_html = ('<span class="sras-people-room">Room %s</span>' %
                         context.room_no)
            contact_items.append(room_html)
        if context.email and context.email.strip():
            email_html = ('<a href="mailto:%s">%s</a>' %
                          (context.email, context.email))
            contact_items.append(email_html)

        photo = context.get('photo')
        if photo is None:
            thumbnail = get_static_url(request) + '/images/defaultUser.gif'
        else:
            thumbnail = thumb_url(photo, request, (50, 50))

        self.display_data = dict(
            contact_html=' - '.join(contact_items),
            thumbnail=thumbnail,
        )
Exemplo n.º 4
0
Arquivo: panels.py Projeto: hj91/karl
def chatter_user_info(context, request, userid=None):
    chatter = find_chatter(context)
    chatter_url = resource_url(chatter, request)
    profiles = find_profiles(context)
    if userid is None:
        userid = request.GET.get('userid')
    if userid is None:
        userid = authenticated_userid(request)
    profile = profiles.get(userid)
    profile_url = profile and resource_url(profile, request) or None
    photo = profile and profile.get('photo') or None
    if photo is not None:
        photo_url = thumb_url(photo, request, CHATTER_THUMB_SIZE)
    else:
        photo_url = get_static_url(request) + "/images/defaultUser.gif"
    posts = sum(1 for p in chatter.recentWithCreators(*[userid]))
    following = sum(1 for u in chatter.listFollowed(userid))
    followers = sum(1 for u in chatter.listFollowing(userid))
    return {
        'creator': getattr(profile, 'title', 'anonymous'),
        'creator_url': '%s%s' % (chatter_url, userid),
        'creator_profile_url': profile_url,
        'creator_image_url': photo_url,
        'creator_userid': userid,
        'chatter_url': chatter_url,
        'posts': posts,
        'following': following,
        'followers': followers
    }
Exemplo n.º 5
0
    def __init__(self, context, request):
        super(AdvancedSearchResultsDisplayPeople, self).__init__(context,
                                                                 request)
        contact_items = []
        if context.extension and context.extension.strip():
            extension_html = ('<span class="sras-people-extension">x%s</span>'
                              % context.extension)
            contact_items.append(extension_html)
        if context.room_no and context.room_no.strip():
            room_html = ('<span class="sras-people-room">Room %s</span>'
                         % context.room_no)
            contact_items.append(room_html)
        if context.email and context.email.strip():
            email_html = ('<a href="mailto:%s">%s</a>'
                          % (context.email, context.email))
            contact_items.append(email_html)

        photo = context.get('photo')
        if photo is None:
            thumbnail = get_static_url(request) + '/images/defaultUser.gif'
        else:
            thumbnail = thumb_url(photo, request, (50,50))

        self.display_data = dict(
            contact_html = ' - '.join(contact_items),
            thumbnail = thumbnail,
            )
Exemplo n.º 6
0
def chatter_user_info(context, request, userid=None):
    chatter = find_chatter(context)
    chatter_url = resource_url(chatter, request)
    profiles = find_profiles(context)
    if userid is None:
        userid = request.GET.get('userid')
    if userid is None:
        userid = authenticated_userid(request)
    profile = profiles.get(userid)
    profile_url = profile and resource_url(profile, request) or None
    photo = profile and profile.get('photo') or None
    if photo is not None:
        photo_url = thumb_url(photo, request, CHATTER_THUMB_SIZE)
    else:
        photo_url = get_static_url(request) + "/images/defaultUser.gif"
    posts = sum(1 for p in chatter.recentWithCreators(*[userid]))
    following = sum(1 for u in chatter.listFollowed(userid))
    followers = sum(1 for u in chatter.listFollowing(userid))
    return {'creator': getattr(profile, 'title', 'anonymous'),
            'creator_url': '%s%s' % (chatter_url, userid),
            'creator_profile_url': profile_url,
            'creator_image_url': photo_url,
            'creator_userid': userid,
            'chatter_url': chatter_url,
            'posts': posts,
            'following': following,
            'followers': followers}
Exemplo n.º 7
0
def profile_thumbnail(context, request):
    api = TemplateAPI(context, request, 'Profile thumbnail redirector')
    photo = context.get('photo')
    if photo is not None:
        url = thumb_url(photo, request, PROFILE_THUMB_SIZE)
    else:
        url = api.static_url + "/images/defaultUser.gif"
    return HTTPFound(location=url)
Exemplo n.º 8
0
def profile_thumbnail(context, request):
    api = TemplateAPI(context, request, 'Profile thumbnail redirector')
    photo = context.get('photo')
    if photo is not None:
        url = thumb_url(photo, request, PROFILE_THUMB_SIZE)
    else:
        url = api.static_url + "/images/defaultUser.gif"
    return HTTPFound(location=url)
Exemplo n.º 9
0
 def test_it(self):
     from zope.interface import directlyProvides
     from karl.content.interfaces import IImage
     from karl.utilities.image import thumb_url
     context = karl.testing.DummyModel()
     directlyProvides(context, IImage)
     request = testing.DummyRequest()
     url = thumb_url(context, request, (300, 300))
     self.assertEqual(url, 'http://example.com/thumb/300x300.jpg')
Exemplo n.º 10
0
 def test_it(self):
     from zope.interface import directlyProvides
     from karl.content.interfaces import IImage
     from karl.utilities.image import thumb_url
     context = karl.testing.DummyModel()
     directlyProvides(context, IImage)
     request = testing.DummyRequest()
     url = thumb_url(context, request, (300, 300))
     self.assertEqual(url, 'http://example.com/thumb/300x300.jpg')
Exemplo n.º 11
0
 def test_w_invalid_image(self):
     #from zope.interface import directlyProvides
     #from karl.content.interfaces import IImage
     from karl.utilities.image import thumb_url
     context = karl.testing.DummyModel()
     #directlyProvides(context, IImage)
     request = testing.DummyRequest()
     url = thumb_url(context, request, (300, 300))
     self.failUnless(url.endswith('/images/brokenImage.gif'), url)
Exemplo n.º 12
0
Arquivo: panels.py Projeto: hj91/karl
def personal_tools(context, request):
    profiles = find_profiles(context)
    name = authenticated_userid(request)
    profile = profiles[name]
    photo = profile.get('photo')
    if photo is not None:
        icon_url = thumb_url(photo, request, PROFILE_ICON_SIZE)
    else:
        icon_url = request.static_url('karl.views:static/ux2/img/person.png')
    profile_url = request.resource_url(profile)
    return {'profile_url': profile_url, 'icon_url': icon_url}
Exemplo n.º 13
0
def personal_tools(context, request):
    profiles = find_profiles(context)
    name = authenticated_userid(request)
    profile = profiles[name]
    photo = profile.get('photo')
    if photo is not None:
        icon_url = thumb_url(photo, request, PROFILE_ICON_SIZE)
    else:
        icon_url = request.static_url('karl.views:static/ux2/img/person.png')
    profile_url = request.resource_url(profile)
    return {'profile_url': profile_url,
            'icon_url': icon_url}
Exemplo n.º 14
0
def show_newsitem_view(context, request):
    backto = {
        'href': resource_url(context.__parent__, request),
        'title': context.__parent__.title,
        }

    actions = []
    if has_permission('edit', context, request):
        actions.append(('Edit', 'edit.html'))
    if has_permission('delete', context, request):
        actions.append(('Delete', 'delete.html'))
    if has_permission('administer', context, request):
        actions.append(('Advanced', 'advanced.html'))

    page_title = context.title
    api = TemplateAPI(context, request, page_title)

    previous, next = get_previous_next(context, request)

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

    # Display photo
    photo = context.get('photo')
    if photo is not None:
        photo = {
            "url": thumb_url(photo, request, PHOTO_DISPLAY_SIZE),
        }

    # Get a layout
    layout_provider = get_layout_provider(context, request)
    layout = layout_provider('generic')

    ux2_layout = request.layout_manager.layout
    ux2_layout.section_style = None

    return render_to_response(
        'templates/show_newsitem.pt',
        dict(api=api,
             actions=actions,
             attachments=fetch_attachments(context['attachments'], request),
             formfields=api.formfields,
             head_data=convert_to_script(client_json_data),
             backto=backto,
             previous=previous,
             next=next,
             old_layout=layout,
             photo=photo),
        request=request,
        )
Exemplo n.º 15
0
def show_newsitem_view(context, request):
    backto = {
        'href': resource_url(context.__parent__, request),
        'title': context.__parent__.title,
    }

    actions = []
    if has_permission('edit', context, request):
        actions.append(('Edit', 'edit.html'))
    if has_permission('delete', context, request):
        actions.append(('Delete', 'delete.html'))
    if has_permission('administer', context, request):
        actions.append(('Advanced', 'advanced.html'))

    page_title = context.title
    api = TemplateAPI(context, request, page_title)

    previous, next = get_previous_next(context, request)

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

    # Display photo
    photo = context.get('photo')
    if photo is not None:
        photo = {
            "url": thumb_url(photo, request, PHOTO_DISPLAY_SIZE),
        }

    # Get a layout
    layout_provider = get_layout_provider(context, request)
    layout = layout_provider('generic')

    ux2_layout = request.layout_manager.layout
    ux2_layout.section_style = None

    return render_to_response(
        'templates/show_newsitem.pt',
        dict(api=api,
             actions=actions,
             attachments=fetch_attachments(context['attachments'], request),
             formfields=api.formfields,
             head_data=convert_to_script(client_json_data),
             backto=backto,
             previous=previous,
             next=next,
             old_layout=layout,
             photo=photo),
        request=request,
    )
Exemplo n.º 16
0
def profile_livesearch_result(context, request):
    photo = context.get('photo')
    if photo is None:
        thumbnail = get_static_url(request) + '/images/defaultUser.gif'
    else:
        thumbnail = thumb_url(photo, request, (85,85))
    return livesearch_dict(
        context, request,
        extension=context.extension,
        email=context.email,
        department=context.department,
        type='profile',
        category='profile',
        thumbnail=thumbnail,
        )
Exemplo n.º 17
0
Arquivo: chatter.py Projeto: zagy/karl
def quip_info(request, *quips):
    result = []
    chatter = find_chatter(request.context)
    profiles = find_profiles(request.context)
    chatter_url = resource_url(chatter, request)
    userid = authenticated_userid(request)
    for quip in quips:
        quip_id = quip.__name__
        creator = quip.creator
        reposter = None
        reposter_fullname = ''
        if quip.repost is not None:
            creator = quip.repost
            reposter = quip.creator
            profile = profiles.get(reposter)
            reposter_fullname = profile and profile.title or reposter
        reply = None
        if quip.reply in chatter:
            reply = quip_info(request, *(chatter[quip.reply], ))[0]
        profile = profiles.get(creator)
        photo = profile and profile.get('photo') or None
        creator_fullname = profile and profile.title or creator
        if photo is not None:
            photo_url = thumb_url(photo, request, CHATTER_THUMB_SIZE)
        else:
            photo_url = get_static_url(request) + "/images/defaultUser.gif"
        timeago = str(quip.created.strftime(TIMEAGO_FORMAT))
        info = {
            'text': quip.text,
            'html': quip.html or quip.text,
            'creator': creator,
            'creator_fullname': creator_fullname,
            'creator_url': '%s%s' % (chatter_url, quip.creator),
            'creator_image_url': photo_url,
            'is_current_user': creator == userid,
            'reposter': reposter,
            'reposter_fullname': reposter_fullname,
            'reply': reply,
            'timeago': timeago,
            'names': list(quip.names),
            'communities': list(quip.communities),
            'tags': list(quip.tags),
            'url': resource_url(quip, request),
            'private': bool(getattr(quip, '__acl__', ())),
            'quip_id': quip_id,
        }
        result.append(info)
    return result
Exemplo n.º 18
0
Arquivo: panels.py Projeto: hj91/karl
def comments(context, request):
    profiles = find_profiles(context)
    karldates = request.registry.getUtility(IKarlDates)
    comments = []
    for comment in context['comments'].values():
        profile = profiles.get(comment.creator)
        author_name = profile.title
        author_url = resource_url(profile, request)

        newc = {}
        newc['id'] = comment.__name__
        if has_permission('edit', comment, request):
            newc['edit_url'] = resource_url(comment, request, 'edit.html')
        else:
            newc['edit_url'] = None

        if has_permission('delete', comment, request):
            newc['delete_url'] = resource_url(comment, request, 'delete.html')
        else:
            newc['delete_url'] = None

        if has_permission('administer', comment, request):
            newc['advanced_url'] = resource_url(comment, request,
                                                'advanced.html')
        else:
            newc['advanced_url'] = None

        # Display portrait
        photo = profile.get('photo')
        if photo is not None:
            photo_url = thumb_url(photo, request, PROFILE_THUMB_SIZE)
        else:
            photo_url = request.static_url(
                "karl.views:static/images/defaultUser.gif")
        newc["portrait_url"] = photo_url

        newc['author_url'] = author_url
        newc['author_name'] = author_name

        newc['date'] = karldates(comment.created, 'longform')
        newc['timestamp'] = comment.created
        newc['text'] = comment.text

        # Fetch the attachments info
        newc['attachments'] = fetch_attachments(comment, request)
        comments.append(newc)
    comments.sort(key=lambda c: c['timestamp'])
    return {'comments': comments}
Exemplo n.º 19
0
def profile_livesearch_result(context, request):
    photo = context.get('photo')
    if photo is None:
        thumbnail = get_static_url(request) + '/images/defaultUser.gif'
    else:
        thumbnail = thumb_url(photo, request, (85, 85))
    return livesearch_dict(
        context,
        request,
        extension=context.extension,
        email=context.email,
        department=context.department,
        type='profile',
        category='profile',
        thumbnail=thumbnail,
    )
Exemplo n.º 20
0
def get_comment_data(context, comments_folder, api, request):
    # get comment data to be used to render comments
    profiles = find_profiles(comments_folder)
    karldates = getUtility(IKarlDates)
    comments = []
    for comment in comments_folder.values():
        profile = profiles.get(comment.creator)
        author_name = profile.title
        author_url = resource_url(profile, request)

        newc = {}
        newc['id'] = comment.__name__
        if has_permission('edit', comment, request):
            newc['edit_url'] = resource_url(comment, request, 'edit.html')
        else:
            newc['edit_url'] = None

        if has_permission('delete', comment, request):
            newc['delete_url'] = resource_url(comment, request, 'delete.html')
        else:
            newc['delete_url'] = None

        if has_permission('administer', comment, request):
            newc['advanced_url'] = resource_url(comment, request, 'advanced.html')
        else:
            newc['advanced_url'] = None

        # Display portrait
        photo = profile.get('photo')
        if photo is not None:
            photo_url = thumb_url(photo, request, PROFILE_THUMB_SIZE)
        else:
            photo_url = api.static_url + "/images/defaultUser.gif"
        newc["portrait_url"] = photo_url

        newc['author_url'] = author_url
        newc['author_name'] = author_name

        newc['date'] = karldates(comment.created, 'longform')
        newc['timestamp'] = comment.created
        newc['text'] = comment.text

        # Fetch the attachments info
        newc['attachments'] = fetch_attachments(comment, request)
        comments.append(newc)
    comments.sort(key=lambda c: c['timestamp'])
    return comments
Exemplo n.º 21
0
Arquivo: chatter.py Projeto: hj91/karl
def quip_info(request, *quips):
    result = []
    chatter = find_chatter(request.context)
    profiles = find_profiles(request.context)
    chatter_url = resource_url(chatter, request)
    userid = authenticated_userid(request)
    for quip in quips:
        quip_id = quip.__name__
        creator = quip.creator
        reposter = None
        reposter_fullname = ''
        if quip.repost is not None:
            creator = quip.repost
            reposter = quip.creator
            profile = profiles.get(reposter)
            reposter_fullname = profile and profile.title or reposter
        reply =  None
        if quip.reply in chatter:
            reply = quip_info(request, *(chatter[quip.reply],))[0]
        profile = profiles.get(creator)
        photo = profile and profile.get('photo') or None
        creator_fullname = profile and profile.title or creator
        if photo is not None:
            photo_url = thumb_url(photo, request, CHATTER_THUMB_SIZE)
        else:
            photo_url = get_static_url(request) + "/images/defaultUser.gif"
        timeago = str(quip.created.strftime(TIMEAGO_FORMAT))
        info = {'text': quip.text,
                'html': quip.html or quip.text,
                'creator': creator,
                'creator_fullname': creator_fullname,
                'creator_url': '%s%s' % (chatter_url, quip.creator),
                'creator_image_url': photo_url,
                'is_current_user': creator == userid,
                'reposter': reposter,
                'reposter_fullname': reposter_fullname,
                'reply': reply,
                'timeago': timeago,
                'names': list(quip.names),
                'communities': list(quip.communities),
                'tags': list(quip.tags),
                'url': resource_url(quip, request),
                'private': bool(getattr(quip, '__acl__', ())),
                'quip_id': quip_id,
               }
        result.append(info)
    return result
Exemplo n.º 22
0
def profile_photo_rows(entries, request, api, columns=3):
    """Arrange profiles in a series of rows.

    Produces {'profile', 'photo_url', 'url'} for each profile.
    """
    row = []
    for profile in entries:
        photo = profile.get('photo')
        if photo is not None:
            photo_url = thumb_url(photo, request, PROFILE_THUMB_SIZE)
        else:
            photo_url = api.static_url + "/images/defaultUser.gif"
        url = resource_url(profile, request)
        row.append({'profile': profile, 'photo_url': photo_url, 'url': url})

        if len(row) >= columns:
            yield row
            row = []
    if row:
        yield row
Exemplo n.º 23
0
def profile_photo_rows(entries, request, api, columns=3):
    """Arrange profiles in a series of rows.

    Produces {'profile', 'photo_url', 'url'} for each profile.
    """
    row = []
    for profile in entries:
        photo = profile.get('photo')
        if photo is not None:
            photo_url = thumb_url(photo, request, PROFILE_THUMB_SIZE)
        else:
            photo_url = api.static_url + "/images/defaultUser.gif"
        url = resource_url(profile, request)
        row.append({'profile': profile, 'photo_url': photo_url, 'url': url})

        if len(row) >= columns:
            yield row
            row = []
    if row:
        yield row
Exemplo n.º 24
0
Arquivo: chatter.py Projeto: hj91/karl
def _quippers_from_users(context, request, user_list):
    userid = authenticated_userid(request)
    chatter = find_chatter(context)
    chatter_url = resource_url(chatter, request)
    profiles = find_profiles(context)
    following = []
    for quipper in user_list:
        info = {}
        profile = profiles.get(quipper)
        photo = profile and profile.get('photo') or None
        if photo is not None:
            photo_url = thumb_url(photo, request, CHATTER_THUMB_SIZE)
        else:
            photo_url = get_static_url(request) + "/images/defaultUser.gif"
        info['image_url'] = photo_url
        info['userid'] = quipper
        info['fullname'] = profile and profile.title or None
        info['url'] = '%s%s' % (chatter_url, quipper)
        user_list = chatter.listFollowed(userid)
        info['followed'] = quipper in user_list
        info['same_user'] = userid == quipper
        following.append(info)
    return following
Exemplo n.º 25
0
Arquivo: chatter.py Projeto: zagy/karl
def _quippers_from_users(context, request, user_list):
    userid = authenticated_userid(request)
    chatter = find_chatter(context)
    chatter_url = resource_url(chatter, request)
    profiles = find_profiles(context)
    following = []
    for quipper in user_list:
        info = {}
        profile = profiles.get(quipper)
        photo = profile and profile.get('photo') or None
        if photo is not None:
            photo_url = thumb_url(photo, request, CHATTER_THUMB_SIZE)
        else:
            photo_url = get_static_url(request) + "/images/defaultUser.gif"
        info['image_url'] = photo_url
        info['userid'] = quipper
        info['fullname'] = profile and profile.title or None
        info['url'] = '%s%s' % (chatter_url, quipper)
        user_list = chatter.listFollowed(userid)
        info['followed'] = quipper in user_list
        info['same_user'] = userid == quipper
        following.append(info)
    return following
Exemplo n.º 26
0
def myprofile_ajax_view(context, request):
    results = {}
    # template provision
    if request.params.get('needsTemplate', 'false') in ('true', 'True'):
        # We need the template. So, let's fetch it.
        layout = request.layout_manager.layout
        results['microtemplate'] = layout.microtemplates['myprofile']
        results['partials'] = []
    # Fetch the data

    # 2nd column: my communities (preferred communities)
    communities_folder = find_communities(context)
    communities = get_my_communities(communities_folder, request)
    communities = sorted(communities,
                         key=attrgetter('last_activity_date'),
                         reverse=True)
    communities_info = [
        dict(
            title=community.title,
            description=community.description,
            url=community.url,
            actions=[dict(
                url=community.url + (a_name if a_name != 'overview' else 'view.html'),
                title=a_name.capitalize(),
                last=a_name == 'wiki',
                ) for a_name in ('overview', 'blog', 'calendar', 'files', 'wiki')],
        )
        for community in communities[:5]
    ]

    # 3rd column: My Recent Activity
    recent_items = []
    recent_items_batch = get_catalog_batch(context, request, batch_size=5,
        interfaces=[ICommunityContent], sort_index="modified_date",
        reverse=True, modified_by=authenticated_userid(request),
        allowed={'query': effective_principals(request), 'operator': 'or'})

    for item in recent_items_batch["entries"]:
        adapted = getMultiAdapter((item, request), IGridEntryInfo)
        community = find_community(item)
        if community is not None:
            community_adapter = getMultiAdapter((community, request),
                                                ICommunityInfo)
            community_info = dict(
                url=community_adapter.url,
                title=community_adapter.title,
            )
        else:
            community_info = None
        # Since this is json, we need a real dict...
        recent_items.append(dict(
            title=adapted.title,
            url=adapted.url,
            modified=item.modified.strftime('%Y-%m-%dT%H:%M:%S'),
            creator_title=adapted.creator_title,
            type=adapted.type,
            community=community_info,
            ))

    profiles = find_profiles(request.context)
    userid = authenticated_userid(request)
    profile = profiles.get(userid)

    photo = profile.get('photo')
    if photo is not None:
        icon_url = thumb_url(photo, request, (45,60))
    else:
        icon_url = request.static_url('karl.views:static/images/defaultUser.gif')
    # Assemble the final result.
    results['data'] = {
        'profile_name': profile.title,
        'profile_url': request.resource_url(profile),
        'icon_url': icon_url,
        'logout_url': "%s/logout.html" % request.application_url,
        'department': profile.department,
        'position': profile.position,
        'email': profile.email,
        'extension': profile.extension,
        'phone': profile.phone,
        'panels': [{
            'class': 'mycommunities',
            'title': 'My Active Communities',
            'communities': communities_info,
            }, {
            'class': 'myrecentitems',
            'title': 'My Recent Activity',
            'contexts': recent_items,
            }],
        }

    return results
Exemplo n.º 27
0
Arquivo: blog.py Projeto: disko/karl
def show_blogentry_view(context, request):

    post_url = resource_url(context, request, "comments", "add_comment.html")
    karldates = getUtility(IKarlDates)
    profiles = find_profiles(context)
    workflow = get_workflow(IBlogEntry, 'security', context)

    if workflow is None:
        security_states = []
    else:
        security_states = get_security_states(workflow, context, request)

    # Convert blog comments into a digestable form for the template
    comments = []

    page_title = context.title
    api = TemplateAPI(context, request, page_title)
    for comment in context['comments'].values():
        profile = profiles.get(comment.creator)
        author_name = profile.title
        author_url = resource_url(profile, request)

        newc = {}
        newc['id'] = comment.__name__
        if has_permission('edit', comment, request):
            newc['edit_url'] = resource_url(comment, request, 'edit.html')
        else:
            newc['edit_url'] = None

        if has_permission('delete', comment, request):
            newc['delete_url'] = resource_url(comment, request, 'delete.html')
        else:
            newc['delete_url'] = None

        if has_permission('administer', comment, request):
            newc['advanced_url'] = resource_url(comment, request, 'advanced.html')
        else:
            newc['advanced_url'] = None

        # Display portrait
        photo = profile.get('photo')
        if photo is not None:
            photo_url = thumb_url(photo, request, PROFILE_THUMB_SIZE)
        else:
            photo_url = api.static_url + "/images/defaultUser.gif"
        newc["portrait_url"] = photo_url

        newc['author_url'] = author_url
        newc['author_name'] = author_name

        newc['date'] = karldates(comment.created, 'longform')
        newc['timestamp'] = comment.created
        newc['text'] = comment.text

        # Fetch the attachments info
        newc['attachments'] = fetch_attachments(comment, request)
        comments.append(newc)
    comments.sort(key=lambda c: c['timestamp'])

    client_json_data = dict(
        tagbox = get_tags_client_data(context, request),
        )

    actions = []
    if has_permission('edit', context, request):
        actions.append(('Edit', 'edit.html'))
    if has_permission('edit', context, request):
        actions.append(('Delete', 'delete.html'))
    if has_permission('administer', context, request):
        actions.append(('Advanced', 'advanced.html'))

    api.is_taggable = True

    byline_info = getMultiAdapter((context, request), IBylineInfo)
    blog = find_interface(context, IBlog)
    backto = {
        'href': resource_url(blog, request),
        'title': blog.title,
        }

    # manually construct formish comment form
    controller = AddCommentFormController(context['comments'], request)
    form_schema = schemaish.Structure()
    form_fields = controller.form_fields()
    for fieldname, field in form_fields:
        form_schema.add(fieldname, field)
    form_action_url = '%sadd_comment.html' % resource_url(context['comments'],
                                                       request)
    comment_form = Form(form_schema, add_default_action=False, name='save',
                        action_url=form_action_url)
    form_defaults = controller.form_defaults()
    comment_form.defaults = form_defaults
    request.form_defaults = form_defaults

    form_actions = [FormAction('submit', 'submit'),
                    FormAction('cancel', 'cancel', validate=False)]
    for action in form_actions:
        comment_form.add_action(action.name, action.title)

    widgets = controller.form_widgets(form_fields)
    for name, widget in widgets.items():
        comment_form[name].widget = widget

    # this is for enable imagedrawer for adding blog comments
    api.karl_client_data['text'] = dict(
            enable_imagedrawer_upload = True,
            )

    return dict(
        api=api,
        actions=actions,
        comments=comments,
        attachments=fetch_attachments(
            context['attachments'], request),
        head_data=convert_to_script(client_json_data),
        comment_form=comment_form,
        post_url=post_url,
        byline_info=byline_info,
        backto=backto,
        security_states = security_states,
        )
Exemplo n.º 28
0
def show_members_view(context, request):
    """Default view of community members (with/without pictures)."""

    layout = request.layout_manager.layout
    layout.page_title = 'Community Members'
    api = TemplateAPI(context, request, layout.page_title)

    # Filter the actions based on permission in the **community**
    community = find_interface(context, ICommunity)
    actions = _get_manage_actions(community, request)
    actions_menu = _get_actions_menu(context, request, actions)

    # Did we get the "show pictures" flag?
    list_view = request.view_name == 'list_view.html'
    pictures_href = request.resource_url(context)
    list_href = request.resource_url(context, 'list_view.html')
    submenu = [  # deprecated in ux2
        {'label': 'Show Pictures',
         'href': pictures_href, 'make_link': list_view},
        {'label': 'Hide Pictures',
         'href': list_href, 'make_link': not(list_view)},
        ]

    formats = [   # ux2
        {'name': 'tabular',
         'selected': list_view,
         'bs-icon': 'icon-th-list',
         'url': list_href,
         'title': 'Tabular View',
         'description': 'Show table'},
        {'name': 'picture',
         'selected': not list_view,
         'bs-icon': 'icon-th',
         'url': pictures_href,
         'title': 'Picture View',
         'description': 'Show pictures'}
    ]

    profiles = find_profiles(context)
    member_batch = _member_profile_batch(context, request)
    member_entries = member_batch['entries']
    moderator_names = community.moderator_names

    member_info = []
    for i in range(len(member_entries)):
        derived = {}
        entry = member_entries[i]
        derived['title'] = entry.title
        derived['href'] = resource_url(entry, request)
        derived['position'] = entry.position
        derived['organization'] = entry.organization
        derived['phone'] = entry.phone
        derived['department'] = entry.department
        derived['email'] = entry.email
        derived['city'] = entry.location

        photo = entry.get('photo')
        if photo is not None:
            derived['photo_url'] = thumb_url(photo, request,
                                             PROFILE_THUMB_SIZE)
        else:
            derived['photo_url'] = api.static_url + "/images/defaultUser.gif"

        derived['is_moderator'] = entry.__name__ in moderator_names
        # Chameleon's tal:repeat and repeat variable support for
        # things like index is pretty iffy.  Fix the entry info to
        # supply the CSS class information.
        derived['css_class'] = 'photoProfile'
        if derived['is_moderator']:
            derived['css_class'] += ' moderator'
        member_info.append(derived)

    moderator_info = []
    profiles = find_profiles(context)
    for moderator_name in moderator_names:
        if moderator_name in profiles:
            derived = {}
            profile = profiles[moderator_name]
            if not has_permission('view', profile, request):
                continue
            derived['title'] = profile.title
            derived['href'] = resource_url(profile, request)
            moderator_info.append(derived)

    renderer_data = dict(
        api=api,  # deprecated in ux2
        actions=actions,  # deprecated in ux2
        actions_menu=actions_menu,
        submenu=submenu,  # deprecated in ux2
        formats=formats,
        moderators=moderator_info,  # deprecated in ux2
        members=member_info,  # deprecated in ux2
        batch=member_batch,
        batch_info=member_batch,  # deprecated in ux2
        hide_pictures=list_view)  # deprecated in ux2

    if not list_view:
        renderer_data['rows'] = profile_photo_rows(
            member_batch['entries'], request, api)

    return renderer_data
Exemplo n.º 29
0
def myprofile_ajax_view(context, request):
    results = {}
    # template provision
    if request.params.get('needsTemplate', 'false') in ('true', 'True'):
        # We need the template. So, let's fetch it.
        layout = request.layout_manager.layout
        results['microtemplate'] = layout.microtemplates['myprofile']
        results['partials'] = []
    # Fetch the data

    # 2nd column: my communities (preferred communities)
    communities_folder = find_communities(context)
    communities = get_my_communities(communities_folder, request)
    communities = sorted(communities,
                         key=attrgetter('last_activity_date'),
                         reverse=True)
    communities_info = [
        dict(
            title=community.title,
            description=community.description,
            url=community.url,
            actions=[
                dict(
                    url=community.url +
                    (a_name if a_name != 'overview' else 'view.html'),
                    title=a_name.capitalize(),
                    last=a_name == 'wiki',
                )
                for a_name in ('overview', 'blog', 'calendar', 'files', 'wiki')
            ],
        ) for community in communities[:5]
    ]

    # 3rd column: My Recent Activity
    recent_items = []
    recent_items_batch = get_catalog_batch(
        context,
        request,
        batch_size=5,
        interfaces=[ICommunityContent],
        sort_index="modified_date",
        reverse=True,
        modified_by=authenticated_userid(request),
        allowed={
            'query': effective_principals(request),
            'operator': 'or'
        })

    for item in recent_items_batch["entries"]:
        adapted = getMultiAdapter((item, request), IGridEntryInfo)
        community = find_community(item)
        if community is not None:
            community_adapter = getMultiAdapter((community, request),
                                                ICommunityInfo)
            community_info = dict(
                url=community_adapter.url,
                title=community_adapter.title,
            )
        else:
            community_info = None
        # Since this is json, we need a real dict...
        recent_items.append(
            dict(
                title=adapted.title,
                url=adapted.url,
                modified=item.modified.strftime('%Y-%m-%dT%H:%M:%S'),
                creator_title=adapted.creator_title,
                type=adapted.type,
                community=community_info,
            ))

    profiles = find_profiles(request.context)
    userid = authenticated_userid(request)
    profile = profiles.get(userid)

    photo = profile.get('photo')
    if photo is not None:
        icon_url = thumb_url(photo, request, (45, 60))
    else:
        icon_url = request.static_url(
            'karl.views:static/images/defaultUser.gif')
    # Assemble the final result.
    results['data'] = {
        'profile_name':
        profile.title,
        'profile_url':
        request.resource_url(profile),
        'icon_url':
        icon_url,
        'logout_url':
        "%s/logout.html" % request.application_url,
        'department':
        profile.department,
        'position':
        profile.position,
        'email':
        profile.email,
        'extension':
        profile.extension,
        'phone':
        profile.phone,
        'panels': [{
            'class': 'mycommunities',
            'title': 'My Active Communities',
            'communities': communities_info,
        }, {
            'class': 'myrecentitems',
            'title': 'My Recent Activity',
            'contexts': recent_items,
        }],
    }

    return results
Exemplo n.º 30
0
def show_profile_view(context, request):
    """Show a profile with actions if the current user"""
    page_title = 'View Profile'
    api = TemplateAPI(context, request, page_title)

    # Create display values from model object
    profile = {}
    for name in [name for name in context.__dict__.keys()
                 if not name.startswith("_")]:
        profile_value = getattr(context, name)
        if profile_value is not None:
            # Don't produce u'None'
            profile[name] = unicode(profile_value)
        else:
            profile[name] = None

    if 'fax' not in profile:
        profile['fax'] = '' # BBB

    # 'websites' is a property, so the loop above misses it
    profile["websites"] = context.websites

    # ditto for 'title'
    profile["title"] = context.title

    if profile.has_key("languages"):
        profile["languages"] = context.languages

    if profile.has_key("department"):
        profile["department"] = context.department

    if profile.get("last_login_time"):
        stamp = context.last_login_time.strftime('%Y-%m-%dT%H:%M:%SZ')
        profile["last_login_time"] = stamp

    if profile.has_key("country"):
        # translate from country code to country name
        country_code = profile["country"]
        country = countries.as_dict.get(country_code, u'')
        profile["country"] = country

    # Display portrait
    photo = context.get('photo')
    display_photo = {}
    if photo is not None:
        display_photo["url"] = thumb_url(photo, request, PROFILE_THUMB_SIZE)
    else:
        display_photo["url"] = api.static_url + "/images/defaultUser.gif"
    profile["photo"] = display_photo

    # 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": resource_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})

    # List recently added content
    num, docids, resolver = ICatalogSearch(context)(
        sort_index='creation_date', reverse=True,
        interfaces=[IContent], limit=5, creator=context.__name__,
        allowed={'query': effective_principals(request), 'operator': 'or'},
        )
    recent_items = []
    for docid in docids:
        item = resolver(docid)
        if item is None:
            continue
        adapted = getMultiAdapter((item, request), IGridEntryInfo)
        recent_items.append(adapted)

    return render_to_response(
        'templates/profile.pt',
        dict(api=api,
             profile=profile,
             actions=get_profile_actions(context, request),
             photo=photo,
             head_data=convert_to_script(client_json_data),
             communities=communities,
             my_communities=my_communities,
             preferred_communities=preferred_communities,
             tags=tags,
             recent_items=recent_items),
        request=request,
        )
Exemplo n.º 31
0
def show_members_view(context, request):
    """Default view of community members (with/without pictures)."""

    page_title = 'Community Members'
    api = TemplateAPI(context, request, page_title)

    # Filter the actions based on permission in the **community**
    community = find_interface(context, ICommunity)
    actions = _get_manage_actions(community, request)

    # Did we get the "show pictures" flag?
    hp = request.params.has_key('hide_pictures')
    mu = resource_url(context, request)
    submenu = [
        {'label': 'Show Pictures',
         'href': mu, 'make_link': hp},
        {'label': 'Hide Pictures',
         'href': mu + '?hide_pictures', 'make_link': not(hp)},
        ]

    profiles = find_profiles(context)
    member_batch = _member_profile_batch(context, request)
    member_entries = member_batch['entries']
    moderator_names = community.moderator_names

    member_info = []
    for i in range(len(member_entries)):
        derived = {}
        entry = member_entries[i]
        derived['title'] = entry.title
        derived['href'] = resource_url(entry, request)
        derived['position'] = entry.position
        derived['organization'] = entry.organization
        derived['phone'] = entry.phone
        derived['department'] = entry.department
        derived['email'] = entry.email
        derived['city'] = entry.location

        photo = entry.get('photo')
        if photo is not None:
            derived['photo_url'] = thumb_url(photo, request,
                                             PROFILE_THUMB_SIZE)
        else:
            derived['photo_url'] = api.static_url + "/images/defaultUser.gif"

        derived['is_moderator'] = entry.__name__ in moderator_names
        # Chameleon's tal:repeat and repeat variable support for
        # things like index is pretty iffy.  Fix the entry info to
        # supply the CSS class information.
        derived['css_class'] = 'photoProfile'
        if derived['is_moderator']:
            derived['css_class'] += ' moderator'
        member_info.append(derived)

    moderator_info = []
    profiles = find_profiles(context)
    for moderator_name in moderator_names:
        if moderator_name in profiles:
            derived = {}
            profile = profiles[moderator_name]
            if not has_permission('view', profile, request):
                continue
            derived['title'] = profile.title
            derived['href'] = resource_url(profile, request)
            moderator_info.append(derived)

    return render_to_response(
        'templates/show_members.pt',
        dict(api=api,
             actions=actions,
             submenu=submenu,
             moderators=moderator_info,
             members=member_info,
             batch_info=member_batch,
             hide_pictures=hp),
        request=request,
        )
Exemplo n.º 32
0
def show_blogentry_view(context, request):

    post_url = resource_url(context, request, "comments", "add_comment.html")
    karldates = getUtility(IKarlDates)
    profiles = find_profiles(context)
    workflow = get_workflow(IBlogEntry, 'security', context)

    if workflow is None:
        security_states = []
    else:
        security_states = get_security_states(workflow, context, request)

    # Convert blog comments into a digestable form for the template
    comments = []

    page_title = context.title
    api = TemplateAPI(context, request, page_title)
    for comment in context['comments'].values():
        profile = profiles.get(comment.creator)
        author_name = profile.title
        author_url = resource_url(profile, request)

        newc = {}
        newc['id'] = comment.__name__
        if has_permission('edit', comment, request):
            newc['edit_url'] = resource_url(comment, request, 'edit.html')
        else:
            newc['edit_url'] = None

        if has_permission('delete', comment, request):
            newc['delete_url'] = resource_url(comment, request, 'delete.html')
        else:
            newc['delete_url'] = None

        if has_permission('administer', comment, request):
            newc['advanced_url'] = resource_url(comment, request,
                                                'advanced.html')
        else:
            newc['advanced_url'] = None

        # Display portrait
        photo = profile.get('photo')
        if photo is not None:
            photo_url = thumb_url(photo, request, PROFILE_THUMB_SIZE)
        else:
            photo_url = api.static_url + "/images/defaultUser.gif"
        newc["portrait_url"] = photo_url

        newc['author_url'] = author_url
        newc['author_name'] = author_name

        newc['date'] = karldates(comment.created, 'longform')
        newc['timestamp'] = comment.created
        newc['text'] = comment.text

        # Fetch the attachments info
        newc['attachments'] = fetch_attachments(comment, request)
        comments.append(newc)
    comments.sort(key=lambda c: c['timestamp'])

    client_json_data = dict(tagbox=get_tags_client_data(context, request), )

    actions = []
    if has_permission('edit', context, request):
        actions.append(('Edit', 'edit.html'))
    if has_permission('edit', context, request):
        actions.append(('Delete', 'delete.html'))
    if has_permission('administer', context, request):
        actions.append(('Advanced', 'advanced.html'))

    api.is_taggable = True

    byline_info = getMultiAdapter((context, request), IBylineInfo)
    blog = find_interface(context, IBlog)
    backto = {
        'href': resource_url(blog, request),
        'title': blog.title,
    }

    # manually construct formish comment form
    controller = AddCommentFormController(context['comments'], request)
    form_schema = schemaish.Structure()
    form_fields = controller.form_fields()
    for fieldname, field in form_fields:
        form_schema.add(fieldname, field)
    form_action_url = '%sadd_comment.html' % resource_url(
        context['comments'], request)
    comment_form = Form(form_schema,
                        add_default_action=False,
                        name='save',
                        action_url=form_action_url)
    form_defaults = controller.form_defaults()
    comment_form.defaults = form_defaults
    request.form_defaults = form_defaults

    form_actions = [
        FormAction('submit', 'submit'),
        FormAction('cancel', 'cancel', validate=False)
    ]
    for action in form_actions:
        comment_form.add_action(action.name, action.title)

    widgets = controller.form_widgets(form_fields)
    for name, widget in widgets.items():
        comment_form[name].widget = widget

    # this is for enable imagedrawer for adding blog comments
    api.karl_client_data['text'] = dict(enable_imagedrawer_upload=True, )

    return dict(
        api=api,
        actions=actions,
        comments=comments,
        attachments=fetch_attachments(context['attachments'], request),
        head_data=convert_to_script(client_json_data),
        comment_form=comment_form,
        post_url=post_url,
        byline_info=byline_info,
        backto=backto,
        security_states=security_states,
    )
Exemplo n.º 33
0
Arquivo: members.py Projeto: zagy/karl
def show_members_view(context, request):
    """Default view of community members (with/without pictures)."""

    layout = request.layout_manager.layout
    layout.page_title = 'Community Members'
    api = TemplateAPI(context, request, layout.page_title)

    # Filter the actions based on permission in the **community**
    community = find_interface(context, ICommunity)
    actions = _get_manage_actions(community, request)
    actions_menu = _get_actions_menu(context, request, actions)

    # Did we get the "show pictures" flag?
    list_view = request.view_name == 'list_view.html'
    pictures_href = request.resource_url(context)
    list_href = request.resource_url(context, 'list_view.html')
    submenu = [  # deprecated in ux2
        {
            'label': 'Show Pictures',
            'href': pictures_href,
            'make_link': list_view
        },
        {
            'label': 'Hide Pictures',
            'href': list_href,
            'make_link': not (list_view)
        },
    ]

    formats = [  # ux2
        {
            'name': 'tabular',
            'selected': list_view,
            'bs-icon': 'icon-th-list',
            'url': list_href,
            'title': 'Tabular View',
            'description': 'Show table'
        }, {
            'name': 'picture',
            'selected': not list_view,
            'bs-icon': 'icon-th',
            'url': pictures_href,
            'title': 'Picture View',
            'description': 'Show pictures'
        }
    ]

    profiles = find_profiles(context)
    member_batch = _member_profile_batch(context, request)
    member_entries = member_batch['entries']
    moderator_names = community.moderator_names

    member_info = []
    for i in range(len(member_entries)):
        derived = {}
        entry = member_entries[i]
        derived['title'] = entry.title
        derived['href'] = resource_url(entry, request)
        derived['position'] = entry.position
        derived['organization'] = entry.organization
        derived['phone'] = entry.phone
        derived['department'] = entry.department
        derived['email'] = entry.email
        derived['city'] = entry.location

        photo = entry.get('photo')
        if photo is not None:
            derived['photo_url'] = thumb_url(photo, request,
                                             PROFILE_THUMB_SIZE)
        else:
            derived['photo_url'] = api.static_url + "/images/defaultUser.gif"

        derived['is_moderator'] = entry.__name__ in moderator_names
        # Chameleon's tal:repeat and repeat variable support for
        # things like index is pretty iffy.  Fix the entry info to
        # supply the CSS class information.
        derived['css_class'] = 'photoProfile'
        if derived['is_moderator']:
            derived['css_class'] += ' moderator'
        member_info.append(derived)

    moderator_info = []
    profiles = find_profiles(context)
    for moderator_name in moderator_names:
        if moderator_name in profiles:
            derived = {}
            profile = profiles[moderator_name]
            if not has_permission('view', profile, request):
                continue
            derived['title'] = profile.title
            derived['href'] = resource_url(profile, request)
            moderator_info.append(derived)

    renderer_data = dict(
        api=api,  # deprecated in ux2
        actions=actions,  # deprecated in ux2
        actions_menu=actions_menu,
        submenu=submenu,  # deprecated in ux2
        formats=formats,
        moderators=moderator_info,  # deprecated in ux2
        members=member_info,  # deprecated in ux2
        batch=member_batch,
        batch_info=member_batch,  # deprecated in ux2
        hide_pictures=list_view)  # deprecated in ux2

    if not list_view:
        renderer_data['rows'] = profile_photo_rows(member_batch['entries'],
                                                   request, api)

    return renderer_data
Exemplo n.º 34
0
def show_forum_topic_view(context, request):
    post_url = resource_url(context, request, "comments", "add_comment.html")
    karldates = getUtility(IKarlDates)
    profiles = find_profiles(context)

    # Convert comments into a digestable form for the template
    comments = []

    page_title = context.title

    actions = []
    if has_permission('edit', context, request):
        actions.append(('Edit', 'edit.html'))
    if has_permission('delete', context, request):
        actions.append(('Delete', 'delete.html'))
    if has_permission('administer', context, request):
        actions.append(('Advanced', 'advanced.html'))

    api = TemplateAPI(context, request, page_title)

    for comment in context['comments'].values():
        profile = profiles.get(comment.creator)
        author_name = profile.title
        author_url = resource_url(profile, request)

        newc = {}
        newc['id'] = comment.__name__
        if has_permission('edit', comment, request):
            newc['edit_url'] = resource_url(comment, request, 'edit.html')
        else:
            newc['edit_url'] = None

        if has_permission('delete', comment, request):
            newc['delete_url'] = resource_url(comment, request, 'delete.html')
        else:
            newc['delete_url'] = None

        if has_permission('administer', comment, request):
            newc['advanced_url'] = resource_url(comment, request, 'advanced.html')
        else:
            newc['advanced_url'] = None

        # Display portrait
        photo = profile.get('photo')
        photo_url = {}
        if photo is not None:
            photo_url = thumb_url(photo, request, PROFILE_THUMB_SIZE)
        else:
            photo_url = api.static_url + "/images/defaultUser.gif"
        newc["portrait_url"] = photo_url

        newc['author_url'] = author_url
        newc['author_name'] = author_name

        newc['date'] = karldates(comment.created, 'longform')
        newc['timestamp'] = comment.created
        newc['text'] = comment.text

        # Fetch the attachments info
        newc['attachments'] = fetch_attachments(comment, request)
        comments.append(newc)
    comments.sort(key=lambda x: x['timestamp'])

    byline_info = getMultiAdapter((context, request), IBylineInfo)
    forum = find_interface(context, IForum)
    backto = {
        'href': resource_url(forum, request),
        'title': forum.title,
        }

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

    # Get a layout
    layout_provider = get_layout_provider(context, request)
    old_layout = layout_provider('community')

    if support_attachments(context):
        attachments = fetch_attachments(context['attachments'], request)
    else:
        attachments = ()

    # manually construct formish comment form
    controller = AddCommentFormController(context['comments'], request)
    form_schema = schemaish.Structure()
    form_fields = controller.form_fields()
    for fieldname, field in form_fields:
        form_schema.add(fieldname, field)
    form_action_url = '%sadd_comment.html' % resource_url(context['comments'],
                                                       request)
    comment_form = Form(form_schema, add_default_action=False, name='save',
                        action_url=form_action_url)
    form_defaults = controller.form_defaults()
    comment_form.defaults = form_defaults
    request.form_defaults = form_defaults

    form_actions = [FormAction('submit', 'submit'),
                    FormAction('cancel', 'cancel', validate=False)]
    for action in form_actions:
        comment_form.add_action(action.name, action.title)

    widgets = controller.form_widgets(form_fields)
    for name, widget in widgets.items():
        comment_form[name].widget = widget

    # enable imagedrawer for adding forum replies (comments)
    api.karl_client_data['text'] = dict(
            enable_imagedrawer_upload = True,
            )
    # ux2
    layout = request.layout_manager.layout
    layout.section_style = "none"
    layout.head_data['panel_data']['tinymce'] = api.karl_client_data['text']
    layout.head_data['panel_data']['tagbox'] = client_json_data['tagbox']
    layout.add_portlet('tagbox')

    return render_to_response(
        'templates/show_forum_topic.pt',
        dict(api=api,
             actions=actions,
             comments=comments,
             attachments=attachments,
             formfields=api.formfields,
             post_url=post_url,
             byline_info=byline_info,
             head_data=convert_to_script(client_json_data),
             backto=backto,
             old_layout=old_layout,
             comment_form=comment_form),
        request=request,
        )
Exemplo n.º 35
0
def show_profile_view(context, request):
    """Show a profile with actions if the current user"""
    page_title = "Profile: %s" % context.title
    api = TemplateAPI(context, request, page_title)

    # Create display values from model object
    profile = {}
    for name in [
            name for name in context.__dict__.keys()
            if not name.startswith("_")
    ]:
        profile_value = getattr(context, name)
        if profile_value is not None:
            # Don't produce u'None'
            profile[name] = unicode(profile_value)
        else:
            profile[name] = None

    if 'fax' not in profile:
        profile['fax'] = ''  # BBB

    # 'websites' is a property, so the loop above misses it
    profile["websites"] = context.websites

    # ditto for 'title'
    profile["title"] = context.title

    if profile.has_key("languages"):
        profile["languages"] = context.languages

    if profile.has_key("department"):
        profile["department"] = context.department

    if profile.get("last_login_time"):
        stamp = context.last_login_time.strftime('%Y-%m-%dT%H:%M:%SZ')
        profile["last_login_time"] = stamp

    if profile.has_key("country"):
        # translate from country code to country name
        country_code = profile["country"]
        country = countries.as_dict.get(country_code, u'')
        profile["country"] = country

    # Display portrait
    photo = context.get('photo')
    display_photo = {}
    if photo is not None:
        display_photo["url"] = thumb_url(photo, request, PROFILE_THUMB_SIZE)
    else:
        display_photo["url"] = api.static_url + "/images/defaultUser.gif"
    profile["photo"] = display_photo

    # 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": resource_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})

    # List recently added content
    num, docids, resolver = ICatalogSearch(context)(
        sort_index='creation_date',
        reverse=True,
        interfaces=[IContent],
        limit=5,
        creator=context.__name__,
        allowed={
            'query': effective_principals(request),
            'operator': 'or'
        },
    )
    recent_items = []
    for docid in docids:
        item = resolver(docid)
        if item is None:
            continue
        adapted = getMultiAdapter((item, request), IGridEntryInfo)
        recent_items.append(adapted)
    recent_url = request.resource_url(context, 'recent_content.html')

    return dict(api=api,
                profile=profile,
                actions=get_profile_actions(context, request),
                photo=photo,
                head_data=convert_to_script(client_json_data),
                communities=communities,
                my_communities=my_communities,
                preferred_communities=preferred_communities,
                tags=tags,
                recent_items=recent_items,
                recent_url=recent_url)