示例#1
0
def print_assignment(request, assignment_id=None):
    response = HttpResponse(mimetype='application/pdf')
    filename = u'filename=%s.pdf;' % _("Elections")
    response['Content-Disposition'] = filename.encode('utf-8')
    doc = SimpleDocTemplate(response)
    doc.title = None
    story = []
    
    if assignment_id is None:  #print all applications
        title = config_get("assignment_pdf_title")
        story.append(Paragraph(title, stylesheet['Heading1']))
        preamble = config_get("assignment_pdf_preamble")
        if preamble:
            story.append(Paragraph("%s" % preamble.replace('\r\n','<br/>'), stylesheet['Paragraph']))
        story.append(Spacer(0,0.75*cm))
        # List of assignments
        for assignment in Assignment.objects.order_by('name'):
            story.append(Paragraph(assignment.name, stylesheet['Heading3']))
        # Assignment details (each assignment on single page)
        for assignment in Assignment.objects.order_by('name'):
            story.append(PageBreak())
            story = get_assignment(assignment, story)
    else:  # print selected assignment
        assignment = Assignment.objects.get(id=assignment_id)
        filename = u'filename=%s-%s.pdf;' % (_("Assignment"), assignment.name.replace(' ','_'))
        response['Content-Disposition'] = filename.encode('utf-8')
        story = get_assignment(assignment, story)

    doc.build(story, onFirstPage=firstPage, onLaterPages=firstPage)
    return response
示例#2
0
def overview(request):
    """
    Shows an overview of all items.
    """
    if request.method == 'POST':
        for item in Item.objects.all():
            form = ElementOrderForm(request.POST, prefix="i%d" % item.id)
            if form.is_valid():
                try:
                    item.parent = Item.objects.get( \
                                       id=form.cleaned_data['parent'])
                except Item.DoesNotExist:
                    item.parent = None
                item.weight = form.cleaned_data['weight']
                item.save()

    items = children_list(Item.objects.filter(parent=None).exclude(hidden=True).order_by('weight'))
    items_hidden = children_list(Item.objects.filter(parent=None).exclude(hidden=False).order_by('weight'))
    try:
        overview = is_summary() and not get_active_item()
    except Item.DoesNotExist:
        overview = True
    return {
        'items': items,
        'items_hidden': items_hidden,
        'overview': overview,
        'summary': is_summary(),
        'countdown_visible': config_get('countdown_visible'),
        'countdown_time': config_get('agenda_countdown_time'),
        }
示例#3
0
def overview(request):
    """
    View all applications
    """
    query = Application.objects
    if 'number' in request.GET:
        query = query.filter(number=None)
    if 'status' in request.GET:
        if 'statusvalue' in request.GET and 'on' in request.GET['status']:
            query = query.filter(status__iexact=request.GET['statusvalue'])
    try:
        sort = request.GET['sort']
        if sort in ['number', 'supporter', 'status', 'submitter', \
                    'aversion__time', 'aversion__title']:
            query = query.order_by(sort)
    except KeyError:
        query = query.order_by("number")
    if 'reverse' in request.GET:
        query = query.reverse()
    if 'needsup' in request.GET:
        applications = []
        for application in query.all():
            if not application.enough_supporters:
                applications.append(application)
    else:
        applications = query.all()
    return {
        'applications': applications,
        'min_supporters': int(config_get('application_min_supporters')),
    }
示例#4
0
def beamer_edit(request, direction):
    if direction == 'bigger':
        config_set('bigger', int(config_get('bigger', 100)) + 10)
    elif direction == 'smaller':
        config_set('bigger', int(config_get('bigger', 100)) - 10)
    elif direction == 'up':
        config_set('up', int(config_get('up', 0)) - 10)
    elif direction == 'down':
        config_set('up', int(config_get('up', 0)) + 10)
    elif direction == 'clean':
        config_set('up', 0)
        config_set('bigger', 100)

    if request.is_ajax():
        return ajax_request({})
    return redirect(reverse('item_overview'))
示例#5
0
def print_application_poll(request, poll_id=None):
    poll = Poll.objects.get(id=poll_id)
    response = HttpResponse(mimetype='application/pdf')
    filename = u'filename=%s%s_%s.pdf;' % (_("Application"), str(poll.application.number), _("Poll"))
    response['Content-Disposition'] = filename.encode('utf-8')
    doc = SimpleDocTemplate(response, pagesize=A4, topMargin=-6, bottomMargin=-6, leftMargin=0, rightMargin=0, showBoundary=False)
    story = [Spacer(0,0*cm)]

    imgpath = os.path.join(SITE_ROOT, 'static/images/circle.png')
    circle = "<img src='%s' width='15' height='15'/>&nbsp;&nbsp;" % imgpath
    cell = []
    cell.append(Spacer(0,0.8*cm))
    cell.append(Paragraph(_("Application No.")+" "+str(poll.application.number), stylesheet['Ballot_title']))
    cell.append(Paragraph(poll.application.title, stylesheet['Ballot_subtitle']))
    cell.append(Paragraph(str(poll.ballot)+". "+_("Vote"), stylesheet['Ballot_description']))
    cell.append(Spacer(0,0.5*cm))
    cell.append(Paragraph(circle+_("Yes"), stylesheet['Ballot_option']))
    cell.append(Paragraph(circle+_("No"), stylesheet['Ballot_option']))
    cell.append(Paragraph(circle+_("Abstention"), stylesheet['Ballot_option']))

    data= []
    number = 1
    # get ballot papers config values
    ballot_papers_selection = config_get("application_pdf_ballot_papers_selection")
    ballot_papers_number = config_get("application_pdf_ballot_papers_number")
    # set number of ballot papers
    if ballot_papers_selection == "1":
        number = User.objects.filter(profile__type__iexact="delegate").count()
    if ballot_papers_selection == "2":
        number = int(User.objects.count() - 1)
    if ballot_papers_selection == "0":
        number = int(ballot_papers_number)
    # print ballot papers
    for user in xrange(number/2):
        data.append([cell,cell])
    rest = number % 2
    if rest:
        data.append([cell,''])
    t=Table(data, 10.5*cm, 7.42*cm)
    t.setStyle(TableStyle([ ('GRID', (0,0), (-1,-1), 0.25, colors.grey),
                            ('VALIGN', (0,0), (-1,-1), 'TOP'),
                          ]))
    story.append(t)
    doc.build(story)
    return response
示例#6
0
    def has_perm(self, user_obj, perm, obj=None):
        """
        Check if the user as a specific permission
        """
        if not user_obj.is_anonymous() or obj is not None or \
           not config_get('system_enable_anonymous', False):
            return False

        return (perm in self.get_all_permissions(user_obj))
示例#7
0
 def enough_supporters(self):
     """
     Return True, if the application has enough supporters
     """
     min_supporters = int(config_get('application_min_supporters'))
     if self.status == "pub":
         return self.supporter.count() >= min_supporters
     else:
         return True
示例#8
0
def beamerhome(request):
    """
    Shows a active Slide.
    """
    data = {'ajax': 'on'}
    template = ''
    try:
        item = get_active_item()
        votes = assignment_votes(item)
        polls = assignment_polls(item)
        if is_summary():
            items = item.children.filter(hidden=False)
            data['items'] = items
            data['title'] = item.title
            template = 'beamer/overview.html'
        else:
            data['item'] = item.cast()
            data['title'] = item.title
            data['votes'] = votes
            data['polls'] = polls
            template = 'beamer/%shome.html' % (item.type)
    except Item.DoesNotExist:
        items = Item.objects.filter(parent=None).filter(hidden=False)\
        .order_by('weight')
        data['items'] = items
        data['title'] = _("Agenda")
        template = 'beamer/overview.html'

    if request.is_ajax():
        content = render_block_to_string(template, 'content', data)
        jsondata = {'content': content,
                    'title': data['title'],
                    'time': datetime.now().strftime('%H:%M'),
                    'bigger': config_get('bigger'),
                    'up': config_get('up'),
                    'countdown_visible': config_get('countdown_visible'),
                    'countdown_time': config_get('agenda_countdown_time'),
                    'countdown_control': config_get('countdown_control'),
                    }
        return ajax_request(jsondata)
    else:
        return render_to_response(template,
            data,
            context_instance=RequestContext(request))
示例#9
0
 def missing_supporters(self):
     """
     Return number of missing supporters
     """
     min_supporters = int(config_get('application_min_supporters'))
     delta = min_supporters - self.supporter.count()
     if delta > 0:
         return delta
     else:
         return 0
示例#10
0
def print_passwords(request):
    response = HttpResponse(mimetype='application/pdf')
    filename = u'filename=%s.pdf;' % _("passwords")
    response['Content-Disposition'] = filename.encode('utf-8')
    doc = SimpleDocTemplate(response, pagesize=A4, topMargin=-6, bottomMargin=-6, leftMargin=0, rightMargin=0, showBoundary=False)
    story = [Spacer(0,0*cm)]

    data= []
    system_url = config_get("system_url")
    system_welcometext = config_get("system_welcometext")
    for user in User.objects.all().order_by('last_name'):
        try:
            user.get_profile()
            cell = []
            cell.append(Spacer(0,0.8*cm))
            cell.append(Paragraph(_("Your Account for OpenSlides"), stylesheet['Ballot_title']))
            cell.append(Paragraph(_("for %s") % (user.profile), stylesheet['Ballot_subtitle']))
            cell.append(Spacer(0,0.5*cm))
            cell.append(Paragraph(_("User: %s") % (user.username), stylesheet['Ballot_option']))
            cell.append(Paragraph(_("Password: %s") % (user.profile.firstpassword), stylesheet['Ballot_option']))
            cell.append(Spacer(0,0.5*cm))
            cell.append(Paragraph(_("URL: %s") % (system_url), stylesheet['Ballot_option']))
            cell.append(Spacer(0,0.5*cm))
            cell2 = []
            cell2.append(Spacer(0,0.8*cm))
            if system_welcometext is not None:
                cell2.append(Paragraph(system_welcometext.replace('\r\n','<br/>'), stylesheet['Ballot_subtitle']))

            data.append([cell,cell2])
        except Profile.DoesNotExist:
            pass

    t=Table(data, 10.5*cm, 7.42*cm)
    t.setStyle(TableStyle([ ('LINEBELOW', (0,0), (-1,0), 0.25, colors.grey),
                            ('LINEBELOW', (0,1), (-1,1), 0.25, colors.grey),
                            ('LINEBELOW', (0,1), (-1,-1), 0.25, colors.grey),
                            ('VALIGN', (0,0), (-1,-1), 'TOP'),
                          ]))
    story.append(t)
    doc.build(story)
    return response
示例#11
0
def is_summary():
    """
    True, if a summery shall be displayed
    """
    from agenda.models import Item
    try:
        get_active_item()
    except Item.DoesNotExist:
        return True
    if config_get('summary', False):
        return True
    return False
示例#12
0
    def has_module_perm(self, user_obj, app_label):
        """
        Check if the user has permissions on the module app_label
        """
        if not user_obj.is_anonymous() or \
           not config_get('system_enable_anonymous', False):
            return False

        for perm in self.get_all_permissions(user_obj):
            if perm[:perm.index('.')] == app_label:
                return True
        return False
示例#13
0
def print_application(request, application_id=None):
    response = HttpResponse(mimetype='application/pdf')
    filename = u'filename=%s.pdf;' % _("Applications")
    response['Content-Disposition'] = filename.encode('utf-8')
    doc = SimpleDocTemplate(response)
    doc.title = None
    story = []
    
    if application_id is None:  #print all applications
        title = config_get("application_pdf_title")
        story.append(Paragraph(title, stylesheet['Heading1']))
        preamble = config_get("application_pdf_preamble")
        if preamble:
            story.append(Paragraph("%s" % preamble.replace('\r\n','<br/>'), stylesheet['Paragraph']))
        story.append(Spacer(0,0.75*cm))
        # List of applications
        for application in Application.objects.order_by('number'):
            if application.number:
                story.append(Paragraph(_("Application No.")+" %s: %s" % (application.number, application.title), stylesheet['Heading3']))
            else:
                story.append(Paragraph(_("Application No.")+"&nbsp;&nbsp;&nbsp;: %s" % (application.title), stylesheet['Heading3']))
        # Applications details (each application on single page)
        for application in Application.objects.order_by('number'):
            story.append(PageBreak())
            story = get_application(application, story)
    else:  # print selected application
        application = Application.objects.get(id=application_id)
        if application.number:
            number = application.number
        else:
            number = ""
        filename = u'filename=%s%s.pdf;' % (_("Application"), str(number))
        response['Content-Disposition'] = filename.encode('utf-8')
        story = get_application(application, story)

    doc.build(story, onFirstPage=firstPage, onLaterPages=firstPage)
    return response
示例#14
0
    def get_group_permissions(self, user_obj, obj=None):
        """
        Return the permissions a user is graneted by his group membership(s).

        - try to return  the permissions for the 'Anonymous' group
        """
        if not user_obj.is_anonymous() or obj is not None or \
           not config_get('system_enable_anonymous', False):
            return set()

        perms = Permission.objects.filter(group__name='Anonymous')
        if perms is None:
            return set()
        perms = perms.values_list('content_type__app_label', 'codename').order_by()
        return set([u'%s.%s' % (ct, name) for ct, name in perms])
示例#15
0
def get_active_item(only_id=False):
    """
    Returns the active Item. If no item is active, or it can not find an Item,
    it raise Item.DoesNotExist

    if only_id is True, returns only the id of this item. Returns None if not Item
    is active. Does not Raise Item.DoesNotExist
    """
    from agenda.models import Item
    id = config_get("presentation", None)
    if only_id:
        if id is None:
            return None
        return int(id)
    return Item.objects.get(pk=id)
示例#16
0
def view(request, application_id, newest=False):
    """
    View one application.
    """
    application = Application.objects.get(pk=application_id)
    if newest:
        version = application.last_version
    else:
        version = application.public_version
    revisions = application.versions
    actions = application.get_allowed_actions(user=request.user)

    return {
        'application': application,
        'revisions': revisions,
        'actions': actions,
        'min_supporters': int(config_get('application_min_supporters')),
        'version': version,
        'results': application.results
    }
示例#17
0
def beamer_countdown(request, command, time=60):
    if command == 'show':
        config_set('countdown_visible', True)
    elif command == 'hide':
        config_set('countdown_visible', False)
    elif command == 'reset':
        config_set('countdown_control', 'reset')
    elif command == 'start':
        config_set('countdown_control', 'start')
    elif command == 'stop':
        config_set('countdown_control', 'stop')

    if request.is_ajax():
        if command == "show":
            link = reverse('countdown_close')
        else:
            link = reverse('countdown_open')
        return ajax_request({'countdown_visible': config_get('countdown_visible'),
                             'link': link})
    return redirect(reverse('item_overview'))
示例#18
0
def print_assignment_poll(request, poll_id=None):
    poll = Poll.objects.get(id=poll_id)
    response = HttpResponse(mimetype='application/pdf')
    filename = u'filename=%s-%s-#%s.pdf;' % (_("Election"), poll.assignment.name.replace(' ','_'), poll.ballot)
    response['Content-Disposition'] = filename.encode('utf-8')
    doc = SimpleDocTemplate(response, pagesize=A4, topMargin=-6, bottomMargin=-6, leftMargin=0, rightMargin=0, showBoundary=False)
    story = [Spacer(0,0*cm)]

    imgpath = os.path.join(SITE_ROOT, 'static/images/circle.png')
    circle = "<img src='%s' width='15' height='15'/>&nbsp;&nbsp;" % imgpath
    cell = []
    cell.append(Spacer(0,0.8*cm))
    cell.append(Paragraph(_("Election") + ": " + poll.assignment.name, stylesheet['Ballot_title']))
    cell.append(Paragraph(poll.description, stylesheet['Ballot_subtitle']))
    options = poll.get_options().order_by('user__user__first_name')
    cell.append(Paragraph(str(poll.ballot)+". "+_("ballot")+", "+str(len(options))+" "+ ungettext("candidate", "candidates", len(options))+", "+str(poll.assignment.posts)+" "+_("available posts"), stylesheet['Ballot_description']))
    cell.append(Spacer(0,0.4*cm))

    data= []
    # get ballot papers config values
    number = 1
    ballot_papers_selection = config_get("assignment_pdf_ballot_papers_selection")
    ballot_papers_number = config_get("assignment_pdf_ballot_papers_number")
    if poll.optiondecision:
        for option in options:
            o = str(option).split("(",1)
            cell.append(Paragraph(o[0], stylesheet['Ballot_option_name']))
            if len(o) > 1:
                cell.append(Paragraph("("+o[1], stylesheet['Ballot_option_group']))
            else:
                cell.append(Paragraph("&nbsp;", stylesheet['Ballot_option_group']))
            cell.append(Paragraph(circle+_("Yes")+"&nbsp; &nbsp; &nbsp; "+circle+_("No")+"&nbsp; &nbsp; &nbsp; "+circle+_("Abstention"), stylesheet['Ballot_option_YNA']))
        # set number of ballot papers
        if ballot_papers_selection == "1":
            number = User.objects.filter(profile__type__iexact="delegate").count()
        if ballot_papers_selection == "2":
            number = int(User.objects.count() - 1)
        if ballot_papers_selection == "0":
            number = int(ballot_papers_number)
        # print ballot papers
        for user in xrange(number/2):
            data.append([cell,cell])
        rest = number % 2
        if rest:
            data.append([cell,''])
        
        if len(options) <= 2:
            t=Table(data, 10.5*cm, 7.42*cm)
        elif len(options) <= 5:
            t=Table(data, 10.5*cm, 14.84*cm)
        else:
            t=Table(data, 10.5*cm, 29.7*cm)
    else:
        for option in options:
            o = str(option).split("(",1)
            cell.append(Paragraph(circle+o[0], stylesheet['Ballot_option_name']))
            if len(o) > 1:
                cell.append(Paragraph("("+o[1], stylesheet['Ballot_option_group_right']))
            else:
                cell.append(Paragraph("&nbsp;", stylesheet['Ballot_option_group_right']))
        # set number of ballot papers
        if ballot_papers_selection == "1":
            number = User.objects.filter(profile__type__iexact="delegate").count()
        if ballot_papers_selection == "2":
            number = int(User.objects.count() - 1)
        if ballot_papers_selection == "0":
            number = int(ballot_papers_number)
        # print ballot papers
        for user in xrange(number/2):
            data.append([cell,cell])
        rest = number % 2
        if rest:
            data.append([cell,''])
        
        if len(options) <= 4:
            t=Table(data, 10.5*cm, 7.42*cm)
        elif len(options) <= 8:
            t=Table(data, 10.5*cm, 14.84*cm)
        else:
            t=Table(data, 10.5*cm, 29.7*cm)

    t.setStyle(TableStyle([ ('GRID', (0,0), (-1,-1), 0.25, colors.grey),
                            ('VALIGN', (0,0), (-1,-1), 'TOP'),
                          ]))
    story.append(t)
    doc.build(story)
    return response
示例#19
0
stylesheet.add(ParagraphStyle(name = 'Ballot_option_YNA',
                              parent = stylesheet['Normal'],
                              fontSize = 12,
                              leading = 15,
                              leftIndent = 49,
                              spaceAfter = 18),
               )
stylesheet.add(ParagraphStyle(name = 'Ballot_option_group_right',
                              parent = stylesheet['Normal'],
                              fontSize = 8,
                              leading = 16,
                              leftIndent = 49),
               )

# set event information
event_name = config_get("event_name")
event_description = config_get("event_description")
event_date = config_get("event_date")
event_location = config_get("event_location")
event_organizer = config_get("event_organizer")

# set print time
time = datetime.now().strftime(str(_("%Y-%m-%d %H:%Mh")))


def firstPage(canvas, doc):
    canvas.saveState()
    # page header (with event information)
    canvas.setFont('Ubuntu',10)
    canvas.setFillGray(0.4)
    canvas.drawString(2.75*cm, 28*cm, "%s | %s" % (event_name, event_description))
示例#20
0
def anonymous_context_additions(RequestContext):
    """
    Add a variable to the request context that will indicate
    if anonymous login is possible at all.
    """
    return { 'os_enable_anonymous_login' : config_get('system_enable_anonymous', False) }
示例#21
0
def edit(request, application_id=None):
    """
    View a form to edit or create a application.
    """
    if request.user.has_perm('application.can_manage_application'):
        is_manager = True
    else:
        is_manager = False

    if not is_manager \
    and not request.user.has_perm('application.can_create_application'):
        messages.error(request, _("You have not the necessary rights to create or edit applications."))
        return redirect(reverse('application_overview'))
    if application_id is not None:
        application = Application.objects.get(id=application_id)
        if not request.user == application.submitter and not is_manager:
            messages.error(request, _("You can not edit this application. You are not the submitter."))
            return redirect(reverse('application_view', args=[application.id]))
    else:
        application = None

    if request.method == 'POST':
        dataform = ApplicationForm(request.POST, prefix="data")
        valid = dataform.is_valid()

        if is_manager:
            managerform = ApplicationManagerForm(request.POST, \
                            instance=application, \
                            prefix="manager")
            valid = valid and managerform.is_valid()
        else:
            managerform = None

        if valid:
            del_supporters = True
            original_supporters = []
            if is_manager:
                if application:
                    for s in application.supporter.all():
                        original_supporters.append(s)
                application = managerform.save()
            elif application_id is None:
                application = Application(submitter=request.user)
            application.title = dataform.cleaned_data['title']
            application.text = dataform.cleaned_data['text']
            application.reason = dataform.cleaned_data['reason']
            application.save(request.user, trivial_change=dataform.cleaned_data['trivial_change'])
            if is_manager:
                # log added supporters
                supporters_added = []
                for s in application.supporter.all():
                    if s not in original_supporters:
                        try:
                            supporters_added.append(unicode(s.profile))
                        except Profile.DoesNotExist:
                            pass
                if len(supporters_added) > 0:
                    log_added = ", ".join(supporters_added)
                    application.writelog(_("Supporter: +%s") % log_added, request.user)
                # log removed supporters
                supporters_removed = []
                for s in original_supporters:
                    if s not in application.supporter.all():
                        try:
                            supporters_removed.append(unicode(s.profile))
                        except Profile.DoesNotExist:
                            pass
                if len(supporters_removed) > 0:
                    log_removed = ", ".join(supporters_removed)
                    application.writelog(_("Supporter: -%s") % log_removed, request.user)
            if application_id is None:
                messages.success(request, _('New application was successfully created.'))
            else:
                messages.success(request, _('Application was successfully modified.'))

            if not 'apply' in request.POST:
                return redirect(reverse('application_view', args=[application.id]))
            if application_id is None:
                return redirect(reverse('application_edit', args=[application.id]))
    else:
        if application_id is None:
            initial = {'text': config_get('application_preamble')}
        else:
            if application.status == "pub" and application.supporter.count() > 0:
                if request.user.has_perm('application.can_manage_application'):
                    messages.warning(request, _("Attention: Do you really want to edit this application? The supporters will <b>not</b> be removed automatically because you can manage applications. Please check if the supports are valid after your changing!"))
                else:
                    messages.warning(request, _("Attention: Do you really want to edit this application? All <b>%s</b> supporters will be removed! Try to convince the supporters again.") % application.supporter.count() )
            initial = {'title': application.title,
                       'text': application.text,
                       'reason': application.reason}

        dataform = ApplicationForm(initial=initial, prefix="data")
        if is_manager:
            if application_id is None:
                initial = {'submitter': str(request.user.id)}
            else:
                initial = {}
            managerform = ApplicationManagerForm(initial=initial, \
                                                 instance=application, \
                                                 prefix="manager")
        else:
            managerform = None
    return {
        'form': dataform,
        'managerform': managerform,
        'application': application,
    }