Ejemplo n.º 1
0
Archivo: blog.py Proyecto: lslaz1/karl
def show_blogentry_view(context, request):
    post_url = resource_url(context, request, "comments", "add_comment.html")
    workflow = get_workflow(IBlogEntry, 'security', context)

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

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

    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,
        }

    comments = get_comment_data(context, context['comments'], api, request)
    comment_form = get_comment_form(context, context['comments'], api, request)

    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,
        )
Ejemplo n.º 2
0
def show_blogentry_view(context, request):
    post_url = resource_url(context, request, "comments", "add_comment.html")
    workflow = get_workflow(IBlogEntry, 'security', context)

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

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

    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,
    }

    comments = get_comment_data(context, context['comments'], api, request)
    comment_form = get_comment_form(context, context['comments'], api, request)

    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,
    )
Ejemplo n.º 3
0
def edit_comment_view(context, request):

    form = EditCommentForm()
    workflow = get_workflow(IComment, 'security', context)

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

    if security_states:
        form.add_field('security_state', security_state_field)

    if 'form.cancel' in request.POST:
        return HTTPFound(location=model_url(context.__parent__, request))

    if 'form.submitted' in request.POST:
        try:
            converted = form.validate(request.POST)
            form.is_valid = True

            # *will be* modified event
            objectEventNotify(ObjectWillBeModifiedEvent(context))
            if workflow is not None:
                if 'security_state' in converted:
                    workflow.transition_to_state(context, request,
                                                 converted['security_state'])

            context.text  = converted['add_comment']
            context.description = extract_description(context.text)

            creator = authenticated_userid(request)
            if support_attachments(context):
                store_attachments(context, request.params, creator)

            context.modified_by = authenticated_userid(request)
            objectEventNotify(ObjectModifiedEvent(context))

            location = model_url(context, request)
            return HTTPFound(location=location)

        except Invalid, e:
            fielderrors = e.error_dict
            fill_values = form.convert(request.POST)
Ejemplo n.º 4
0
 def _get_security_states(self):
     return get_security_states(self.workflow, self.context, self.request)
Ejemplo n.º 5
0
 def _callFUT(self, workflow, context=None, request=None):
     from karl.security.workflow import get_security_states
     return get_security_states(workflow, context, request)
Ejemplo n.º 6
0
def show_blog_view(context, request):
    if 'year' in request.GET and 'month' in request.GET:
        year = int(request.GET['year'])
        month = int(request.GET['month'])

        def filter_func(name, item):
            created = item.created
            return created.year == year and created.month == month

        dt = datetime.date(year, month, 1).strftime('%B %Y')
        page_title = 'Blog: %s' % dt
    else:
        filter_func = None
        page_title = 'Blog'

    api = TemplateAPI(context, request, page_title)

    actions = []
    if has_permission('create', context, request):
        actions.append(('Add Blog Entry',
                        request.resource_url(context, 'add_blogentry.html')), )

    batch = get_container_batch(context,
                                request,
                                filter_func=filter_func,
                                interfaces=[IBlogEntry],
                                sort_index='creation_date',
                                reverse=True)

    # Unpack into data for the template
    entries = []
    profiles = find_profiles(context)
    karldates = getUtility(IKarlDates)
    fmt0 = '<a href="%s#addcomment">Add a Comment</a>'
    fmt1 = '<a href="%s#comments">1 Comment</a>'
    fmt2 = '<a href="%s#comments">%i Comments</a>'

    for entry in batch['entries']:
        profile = profiles[entry.creator]
        byline_info = getMultiAdapter((entry, request), IBylineInfo)
        entry_url = resource_url(entry, request)

        # Get information about comments on this entry to display in
        # the last line of the entry
        comment_count = len(entry['comments'])
        if comment_count == 0:
            comments_blurb = fmt0 % entry_url
        elif comment_count == 1:
            comments_blurb = fmt1 % entry_url
        else:
            comments_blurb = fmt2 % (entry_url, comment_count)
        info = {
            'title': entry.title,
            'href': resource_url(entry, request),
            'description': entry.description,
            'creator_title': profile.title,
            'creator_href': entry_url,
            'long_date': karldates(entry.created, 'longform'),
            'byline_info': byline_info,
            'comments_blurb': comments_blurb,
        }
        entries.append(info)

    feed_url = "%satom.xml" % resource_url(context, request)
    workflow = get_workflow(IBlogEntry, 'security', context)
    if workflow is None:
        security_states = []
    else:
        security_states = get_security_states(workflow, None, request)

    system_email_domain = get_setting(context, "system_email_domain")
    return dict(
        api=api,
        actions=actions,
        entries=entries,
        system_email_domain=system_email_domain,
        feed_url=feed_url,
        batch_info=batch,
        security_states=security_states,
    )
Ejemplo n.º 7
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,
    )
Ejemplo n.º 8
0
def edit_calendarevent_view(context, request):

    tags_list = request.POST.getall('tags')
    form = EditCalendarEventForm(tags_list=tags_list)
    workflow = get_workflow(ICalendarEvent, 'security', context)

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

    if security_states:
        form.add_field('security_state', security_state_field)

    if 'form.cancel' in request.POST:
        return HTTPFound(location=model_url(context, request))

    if 'form.submitted' in request.POST:
        try:
            if 'calendar_category' not in request.POST:
                # FormEncode doesn't let us mark certain keys as being missable
                # Either any key can be missing from form or none, so we just
                # manually massage calendar_category, which may be missing,
                # before performing validation.
                request.POST['calendar_category'] = None

            converted = form.validate(request.POST)

            # *will be* modified event
            objectEventNotify(ObjectWillBeModifiedEvent(context))
            if workflow is not None:
                if 'security_state' in converted:
                    workflow.transition_to_state(context, request,
                                                 converted['security_state'])

            context.title = converted['title']
            context.startDate = converted['startDate']
            context.endDate = converted['endDate']
            context.text = converted['text']
            context.location = converted['location']
            context.attendees = converted['attendees']
            context.contact_name = converted['contact_name']
            context.contact_email = converted['contact_email']
            context.calendar_category = converted['calendar_category']
            context.description = extract_description(converted['text'])

            # Save the tags on it
            set_tags(context, request, converted['tags'])

            # Save new attachments
            creator = authenticated_userid(request)
            store_attachments(context['attachments'], request.params, creator)

            # Modified
            context.modified_by = authenticated_userid(request)
            objectEventNotify(ObjectModifiedEvent(context))

            location = model_url(context, request)
            msg = "?status_message=Calendar%20Event%20edited"
            return HTTPFound(location=location+msg)

        except Invalid, e:
            fielderrors = e.error_dict
            fill_values = form.convert(request.POST)
Ejemplo n.º 9
0
Archivo: blog.py Proyecto: disko/karl
 def _get_security_states(self):
     return get_security_states(self.workflow, None, self.request)
Ejemplo n.º 10
0
 def _get_security_states(self):
     return get_security_states(self.workflow, self.context, self.request)
Ejemplo n.º 11
0
def show_blogentry_view(context, request):

    post_url = model_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 = model_url(profile, request)

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

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

        # Display portrait
        photo = profile.get_photo()
        photo_url = {}
        if photo is not None:
            photo_url = model_url(photo, request)
        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'))

    api.is_taggable = True

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

    return render_template_to_response(
        'templates/show_blogentry.pt',
        api=api,
        actions=actions,
        comments=comments,
        attachments=fetch_attachments(context['attachments'], request),
        head_data=convert_to_script(client_json_data),
        formfields=api.formfields,
        post_url=post_url,
        byline_info=byline_info,
        backto=backto,
        security_states = security_states,
        )
Ejemplo n.º 12
0
def add_comment_view(context, request):
    # This is NOT a self-posting form.  The BlogEntry has the form
    # that submits to this view.  Thus, we only need to handle
    # submission requests, then redirect back to the parent (the blog
    # entry).

    # Handle the Add Comment form
    #post_url = model_url(context, request, "comments/add_comment.html")
    form = AddCommentForm()
    # add the security state field if appropriate for the context
    workflow = get_workflow(IComment, 'security', context)

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

    if security_states:
        form.add_field('security_state', security_state_field)

    if 'form.cancel' in request.POST:
        return HTTPFound(location=model_url(context.__parent__, request))

    if 'form.submitted' in request.POST:
        converted = form.validate(request.POST)
        form.is_valid = True
        parent = context.__parent__
        creator = authenticated_userid(request)
        c = create_content(
            IComment,
            'Re: %s' % parent.title,
            converted['add_comment'],
            extract_description(converted['add_comment']),
            creator,
            )
        next_id = parent['comments'].next_id
        parent['comments'][next_id] = c
        if workflow is not None:
            workflow.initialize(c)
            if 'security_state' in converted:
                workflow.transition_to_state(c, request,
                                             converted['security_state'])

        if support_attachments(c):
            store_attachments(c, request.params, creator)
        relocate_temp_images(c, request)

        url = model_url(parent, request)
        msg = 'Comment added'
        url = url + '?status_message=%s' % urllib.quote(msg)

        blogentry = find_interface(context, IBlogEntry)
        if converted['sendalert']:
            alerts = queryUtility(IAlerts, default=Alerts())
            alerts.emit(c, request)

        return HTTPFound(location=url)

    # XXX Need different flow of control here, since it isn't
    # self-posting.

    else:
        raise Invalid('This is not a self-posting form. It is submit only.',
                      None, None)
Ejemplo n.º 13
0
Archivo: blog.py Proyecto: iotest3/new
def show_blog_view(context, request):
    if 'year' in request.GET and 'month' in request.GET:
        year = int(request.GET['year'])
        month = int(request.GET['month'])
        dt = datetime.date(year, month, 1).strftime('%B %Y')
        page_title = 'Blog: %s' % dt
        where_month = ("and state->>'created' like '%.4d-%.2d%%%%'" %
                       (year, month))
    else:
        page_title = 'Blog'
        where_month = ''

    from newt.db import search
    community = find_community(context)
    community_cond = qbe.sql(context._p_jar, dict(community=community))
    results = search.search(
        context._p_jar,
        """
        select * from newt natural join karlex where
        class_name = 'karl.content.models.blog.BlogEntry'
        and """ + community_cond + """
        and newt_can_view(state, %s)
        """ + where_month + """
        order by state->>'created' desc
        """,
        effective_principals(request),
    )

    api = TemplateAPI(context, request, page_title)

    actions = []
    if has_permission('create', context, request):
        actions.append(('Add Blog Entry',
                        request.resource_url(context, 'add_blogentry.html')), )

    batch = get_simple_batch(results, context, request)

    # Unpack into data for the template
    entries = []
    profiles = find_profiles(context)
    karldates = getUtility(IKarlDates)
    fmt0 = '<a href="%s#addcomment">Add a Comment</a>'
    fmt1 = '<a href="%s#comments">1 Comment</a>'
    fmt2 = '<a href="%s#comments">%i Comments</a>'

    for entry in batch['entries']:
        profile = profiles[entry.creator]
        byline_info = getMultiAdapter((entry, request), IBylineInfo)
        entry_url = resource_url(entry, request)

        # Get information about comments on this entry to display in
        # the last line of the entry
        comment_count = len(entry['comments'])
        if comment_count == 0:
            comments_blurb = fmt0 % entry_url
        elif comment_count == 1:
            comments_blurb = fmt1 % entry_url
        else:
            comments_blurb = fmt2 % (entry_url, comment_count)
        info = {
            'title': entry.title,
            'href': resource_url(entry, request),
            'description': entry.description,
            'creator_title': profile.title,
            'creator_href': entry_url,
            'long_date': karldates(entry.created, 'longform'),
            'byline_info': byline_info,
            'comments_blurb': comments_blurb,
        }
        entries.append(info)

    feed_url = "%satom.xml" % resource_url(context, request)
    workflow = get_workflow(IBlogEntry, 'security', context)
    if workflow is None:
        security_states = []
    else:
        security_states = get_security_states(workflow, None, request)

    system_email_domain = get_setting(context, "system_email_domain")
    return dict(
        api=api,
        actions=actions,
        entries=entries,
        system_email_domain=system_email_domain,
        feed_url=feed_url,
        batch_info=batch,
        security_states=security_states,
    )
Ejemplo n.º 14
0
def show_blog_view(context, request):
    community = find_community(context)
    stmt = """SELECT docid FROM pgtextindex
              WHERE content_type='IBlogEntry' and community_docid='%s'
              """
    if 'year' in request.GET and 'month' in request.GET:
        year = int(request.GET['year'])
        month = int(request.GET['month'])
        dt = datetime.date(year, month, 1).strftime('%B %Y')
        page_title = 'Blog: %s' % dt
        stmt += """AND creation_date >= '%d-%02d-01' AND
                   creation_date < '%d-%02d-01'::date +
                   interval '1 month' """ % (
                    year, month, year, month)
    else:
        page_title = 'Blog'
    stmt += "\nORDER BY creation_date DESC"
    catalog = find_catalog(context)
    index = catalog['texts']
    results = index.get_sql_catalog_results(stmt % community.docid)

    api = TemplateAPI(context, request, page_title)

    actions = []
    if has_permission('create', context, request):
        actions.append(
            ('Add Blog Entry',
             request.resource_url(context, 'add_blogentry.html')),
            )

    batch = get_simple_batch(results, context, request)

    # Unpack into data for the template
    entries = []
    profiles = find_profiles(context)
    karldates = getUtility(IKarlDates)
    fmt0 = '<a href="%s#addcomment">Add a Comment</a>'
    fmt1 = '<a href="%s#comments">1 Comment</a>'
    fmt2 = '<a href="%s#comments">%i Comments</a>'

    for page_entry in batch['entries']:
        path = catalog.document_map.address_for_docid(page_entry[0])
        try:
            entry = find_resource(context, path)
        except KeyError:
            continue
        if not has_permission('view', entry, request):
            continue
        profile = profiles[entry.creator]
        byline_info = getMultiAdapter((entry, request), IBylineInfo)
        entry_url = resource_url(entry, request)

        # Get information about comments on this entry to display in
        # the last line of the entry
        comment_count = len(entry['comments'])
        if comment_count == 0:
            comments_blurb = fmt0 % entry_url
        elif comment_count == 1:
            comments_blurb = fmt1 % entry_url
        else:
            comments_blurb = fmt2 % (entry_url, comment_count)
        info = {
            'title': entry.title,
            'href': resource_url(entry, request),
            'description': entry.description,
            'creator_title': profile.title,
            'creator_href': entry_url,
            'long_date': karldates(entry.created, 'longform'),
            'byline_info': byline_info,
            'comments_blurb': comments_blurb,
            }
        entries.append(info)

    feed_url = "%satom.xml" % resource_url(context, request)
    workflow = get_workflow(IBlogEntry, 'security', context)
    if workflow is None:
        security_states = []
    else:
        security_states = get_security_states(workflow, None, request)

    system_email_domain = get_setting(context, "system_email_domain")
    return dict(
        api=api,
        actions=actions,
        entries=entries,
        system_email_domain=system_email_domain,
        feed_url=feed_url,
        batch_info = batch,
        security_states=security_states,
        )
Ejemplo n.º 15
0
Archivo: acl.py Proyecto: Falmarri/karl
def edit_acl_view(context, request):

    acl = original_acl = getattr(context, '__acl__', [])
    if acl and acl[-1] == NO_INHERIT:
        acl = acl[:-1]
        epilog = [NO_INHERIT]
    else:
        epilog = []

    if 'form.move_up' in request.POST:
        index = int(request.POST['index'])
        if index > 0:
            new = acl[:]
            new[index-1], new[index] = new[index], new[index-1]
            acl = new

    elif 'form.move_down' in request.POST:
        index = int(request.POST['index'])
        if index < len(acl) - 1:
            new = acl[:]
            new[index+1], new[index] = new[index], new[index+1]
            acl = new

    elif 'form.remove' in request.POST:
        index = int(request.POST['index'])
        new = acl[:]
        del new[index]
        acl = new

    elif 'form.add' in request.POST:
        verb = request.POST['verb']
        principal = request.POST['principal']
        permissions = tuple(filter(None,
                              COMMA_WS.split(request.POST['permissions'])))
        new = acl[:]
        new.append((verb, principal, permissions))
        acl = new

    elif 'form.inherit' in request.POST:
        no_inherit = request.POST['inherit'] == 'disabled'
        if no_inherit:
            epilog = [NO_INHERIT]
        else:
            epilog = []

    elif 'form.security_state' in request.POST:
        new_state = request.POST['security_state']
        if new_state != 'CUSTOM':
            workflow = get_context_workflow(context)
            if hasattr(context, '__custom_acl__'):
                workflow.reset(context)
                del context.__custom_acl__
            workflow.transition_to_state(context, request, new_state)

    acl = acl + epilog

    if acl != original_acl:
        context.__custom_acl__ = acl # added so we can find customized obs later
        context.__acl__ = acl
        catalog = find_catalog(context)
        if catalog is not None:
            allowed = catalog.get('allowed')
            if allowed is not None:
                for node in postorder(context):
                    allowed.reindex_doc(node.docid, node)
                catalog.invalidate()

    workflow = get_context_workflow(context)
    if workflow is not None:
        if hasattr(context, '__custom_acl__'):
            security_state = 'CUSTOM'
            security_states = [s['name'] for s in
                               workflow.state_info(context, request)]
            security_states.insert(0, 'CUSTOM')
        else:
            security_state = workflow.state_of(context)
            security_states = [s['name'] for s in
                               get_security_states(workflow, context, request)]

    else:
        security_state = None
        security_states = None

    parent = context.__parent__
    parent_acl = []
    while parent is not None:
        p_acl = getattr(parent, '__acl__', ())
        stop = False
        for ace in p_acl:
            if ace == NO_INHERIT:
                stop = True
            else:
                parent_acl.append(ace)
        if stop:
            break
        parent = parent.__parent__

    local_acl = []
    inheriting = 'enabled'
    l_acl = getattr(context, '__acl__', ())
    for l_ace in l_acl:
        if l_ace == NO_INHERIT:
            inheriting = 'disabled'
            break
        local_acl.append(l_ace)


    return render_to_response(
        'templates/edit_acl.pt',
        dict(parent_acl=parent_acl or (),
             local_acl=local_acl,
             inheriting=inheriting,
             security_state=security_state,
             security_states=security_states),
        request=request,
        )
Ejemplo n.º 16
0
 def _get_security_states(self):
     return get_security_states(self.workflow, None, self.request)
Ejemplo n.º 17
0
Archivo: acl.py Proyecto: zagy/karl
def edit_acl_view(context, request):

    acl = original_acl = getattr(context, '__acl__', [])
    if acl and acl[-1] == NO_INHERIT:
        acl = acl[:-1]
        epilog = [NO_INHERIT]
    else:
        epilog = []

    if 'form.move_up' in request.POST:
        index = int(request.POST['index'])
        if index > 0:
            new = acl[:]
            new[index - 1], new[index] = new[index], new[index - 1]
            acl = new

    elif 'form.move_down' in request.POST:
        index = int(request.POST['index'])
        if index < len(acl) - 1:
            new = acl[:]
            new[index + 1], new[index] = new[index], new[index + 1]
            acl = new

    elif 'form.remove' in request.POST:
        index = int(request.POST['index'])
        new = acl[:]
        del new[index]
        acl = new

    elif 'form.add' in request.POST:
        verb = request.POST['verb']
        principal = request.POST['principal']
        permissions = tuple(
            filter(None, COMMA_WS.split(request.POST['permissions'])))
        new = acl[:]
        new.append((verb, principal, permissions))
        acl = new

    elif 'form.inherit' in request.POST:
        no_inherit = request.POST['inherit'] == 'disabled'
        if no_inherit:
            epilog = [NO_INHERIT]
        else:
            epilog = []

    elif 'form.security_state' in request.POST:
        new_state = request.POST['security_state']
        if new_state != 'CUSTOM':
            workflow = get_context_workflow(context)
            if hasattr(context, '__custom_acl__'):
                workflow.reset(context)
                del context.__custom_acl__
            workflow.transition_to_state(context, request, new_state)

    acl = acl + epilog

    if acl != original_acl:
        context.__custom_acl__ = acl  # added so we can find customized obs later
        context.__acl__ = acl
        catalog = find_catalog(context)
        if catalog is not None:
            allowed = catalog.get('allowed')
            if allowed is not None:
                for node in postorder(context):
                    allowed.reindex_doc(node.docid, node)
                catalog.invalidate()

    workflow = get_context_workflow(context)
    if workflow is not None:
        if hasattr(context, '__custom_acl__'):
            security_state = 'CUSTOM'
            security_states = [
                s['name'] for s in workflow.state_info(context, request)
            ]
            security_states.insert(0, 'CUSTOM')
        else:
            security_state = workflow.state_of(context)
            security_states = [
                s['name']
                for s in get_security_states(workflow, context, request)
            ]

    else:
        security_state = None
        security_states = None

    parent = context.__parent__
    parent_acl = []
    while parent is not None:
        p_acl = getattr(parent, '__acl__', ())
        stop = False
        for ace in p_acl:
            if ace == NO_INHERIT:
                stop = True
            else:
                parent_acl.append(ace)
        if stop:
            break
        parent = parent.__parent__

    local_acl = []
    inheriting = 'enabled'
    l_acl = getattr(context, '__acl__', ())
    for l_ace in l_acl:
        if l_ace == NO_INHERIT:
            inheriting = 'disabled'
            break
        local_acl.append(l_ace)

    return render_to_response(
        'templates/edit_acl.pt',
        dict(parent_acl=parent_acl or (),
             local_acl=local_acl,
             inheriting=inheriting,
             security_state=security_state,
             security_states=security_states),
        request=request,
    )
Ejemplo n.º 18
0
Archivo: blog.py Proyecto: 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,
        )
Ejemplo n.º 19
0
Archivo: tests.py Proyecto: lslaz1/karl
 def _callFUT(self, workflow, context=None, request=None):
     from karl.security.workflow import get_security_states
     return get_security_states(workflow, context, request)
Ejemplo n.º 20
0
Archivo: blog.py Proyecto: disko/karl
def show_blog_view(context, request):
    if 'year' in request.GET and 'month' in request.GET:
        year = int(request.GET['year'])
        month = int(request.GET['month'])
        def filter_func(name, item):
            created = item.created
            return created.year == year and created.month == month
        dt = datetime.date(year, month, 1).strftime('%B %Y')
        page_title = 'Blog: %s' % dt
    else:
        filter_func = None
        page_title = 'Blog'

    api = TemplateAPI(context, request, page_title)

    actions = []
    if has_permission('create', context, request):
        actions.append(
            ('Add Blog Entry',
             request.resource_url(context, 'add_blogentry.html')),
            )

    batch = get_container_batch(
        context, request, filter_func=filter_func, interfaces=[IBlogEntry],
        sort_index='creation_date', reverse=True)

    # Unpack into data for the template
    entries = []
    profiles = find_profiles(context)
    karldates = getUtility(IKarlDates)
    fmt0 = '<a href="%s#addcomment">Add a Comment</a>'
    fmt1 = '<a href="%s#comments">1 Comment</a>'
    fmt2 = '<a href="%s#comments">%i Comments</a>'

    for entry in batch['entries']:
        profile = profiles[entry.creator]
        byline_info = getMultiAdapter((entry, request), IBylineInfo)
        entry_url = resource_url(entry, request)

        # Get information about comments on this entry to display in
        # the last line of the entry
        comment_count = len(entry['comments'])
        if comment_count == 0:
            comments_blurb = fmt0 % entry_url
        elif comment_count == 1:
            comments_blurb = fmt1 % entry_url
        else:
            comments_blurb = fmt2 % (entry_url, comment_count)
        info = {
            'title': entry.title,
            'href': resource_url(entry, request),
            'description': entry.description,
            'creator_title': profile.title,
            'creator_href': entry_url,
            'long_date': karldates(entry.created, 'longform'),
            'byline_info': byline_info,
            'comments_blurb': comments_blurb,
            }
        entries.append(info)

    feed_url = "%satom.xml" % resource_url(context, request)
    workflow = get_workflow(IBlogEntry, 'security', context)
    if workflow is None:
        security_states = []
    else:
        security_states = get_security_states(workflow, None, request)

    system_email_domain = get_setting(context, "system_email_domain")
    return dict(
        api=api,
        actions=actions,
        entries=entries,
        system_email_domain=system_email_domain,
        feed_url=feed_url,
        batch_info = batch,
        security_states=security_states,
        )
Ejemplo n.º 21
0
def add_calendarevent_view(context, request):

    tags_list=request.POST.getall('tags')
    form = AddCalendarEventForm(tags_list=tags_list)
    workflow = get_workflow(ICalendarEvent, 'security', context)

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

    if security_states:
        form.add_field('security_state', security_state_field)

    if 'form.cancel' in request.POST:
        return HTTPFound(location=model_url(context, request))

    if 'form.submitted' in request.POST:
        try:
            if 'calendar_category' not in request.POST:
                # FormEncode doesn't let us mark certain keys as being missable
                # Either any key can be missing from form or none, so we just
                # manually massage calendar_category, which may be missing,
                # before performing validation.
                request.POST['calendar_category'] = None

            converted = form.validate(request.POST)

            creator = authenticated_userid(request)
            if converted['contact_email'] is None:
                # Couldn't convince the email validator to call
                # _to_python
                converted['contact_email'] = u''
            calendarevent = create_content(ICalendarEvent,
                                           converted['title'],
                                           converted['startDate'],
                                           converted['endDate'],
                                           creator,
                                           converted['text'],
                                           converted['location'],
                                           converted['attendees'],
                                           converted['contact_name'],
                                           converted['contact_email'],
                                           calendar_category=
                                            converted['calendar_category'],
                                           )
            calendarevent.description = extract_description(converted['text'])

            calname = make_unique_name(context, calendarevent.title)
            context[calname] = calendarevent

            # Set up workflow
            if workflow is not None:
                workflow.initialize(calendarevent)
                if 'security_state' in converted:
                    workflow.transition_to_state(calendarevent, request,
                                                 converted['security_state'])

            # Save the tags on it.
            set_tags(calendarevent, request, converted['tags'])
            store_attachments(calendarevent['attachments'],
                              request.params, creator)

            if converted['sendalert']:
                alerts = queryUtility(IAlerts, default=Alerts())
                alerts.emit(calendarevent, request)

            location = model_url(calendarevent, request)
            return HTTPFound(location=location)

        except Invalid, e:
            fielderrors = e.error_dict
            fill_values = form.convert(request.POST)
            tags_field = dict(
                records = [dict(tag=t) for t in request.POST.getall('tags')]
                )