Ejemplo n.º 1
0
def nagios(request):
    _validate_monitor_request(request)

    # Summary view of "a couple of things to monitor", at a global level.
    # Note that this monitoring is about the system *itself*, not about conferences etc.

    errors = []

    # Check that there is a jobs runner connected
    if exec_to_scalar("SELECT NOT EXISTS (SELECT 1 FROM pg_stat_activity WHERE application_name='pgeu scheduled job runner' AND datname=current_database())"):
        errors.append('No job scheduler connected to database')

    # Check that there are no outbound emails in the queue
    if exec_to_scalar("SELECT EXISTS (SELECT 1 FROM mailqueue_queuedmail WHERE sendtime < now() - '2 minutes'::interval)"):
        errors.append('Unsent emails are present in the outbound mailqueue')

    # Check that there are no outbound notifications in the queue
    if exec_to_scalar("SELECT EXISTS (SELECT 1 FROM confreg_notificationqueue WHERE time < now() - '10 minutes'::interval)"):
        errors.append('Unsent notifications are present in the outbound queue')

    # Check that there are no outbound social media broadcasts in the queue
    if exec_to_scalar("SELECT EXISTS (SELECT 1 FROM confreg_conferencetweetqueue tq WHERE datetime < now() - '10 minutes'::interval AND approved AND EXISTS (SELECT 1 FROM confreg_conferencetweetqueue_remainingtosend rts WHERE rts.conferencetweetqueue_id=tq.id))"):
        errors.append('Unsent social media broadcasts are present in the outbound queue')

    # Check for email addresses not configured
    errors.extend(check_all_emails(['DEFAULT_EMAIL', 'INVOICE_SENDER_EMAIL', 'INVOICE_NOTIFICATION_RECEIVER', 'SCHEDULED_JOBS_EMAIL', 'SCHEDULED_JOBS_EMAIL_SENDER', 'INVOICE_NOTIFICATION_RECEIVER', 'TREASURER_EMAIL', 'SERVER_EMAIL']))

    if errors:
        return HttpResponse("CRITICAL: {}".format(", ".join(errors)), content_type='text/plain')
    else:
        return HttpResponse("OK", content_type='text/plain')
Ejemplo n.º 2
0
 def clean_bankaccount(self):
     n = exec_to_scalar("SELECT count(1) FROM invoices_invoicepaymentmethod WHERE config->>'bankaccount' = %(account)s AND (id != %(self)s OR %(self)s IS NULL)", {
         'account': self.cleaned_data['bankaccount'],
         'self': self.instance.id,
     })
     if n > 0:
         raise ValidationError("This account is already managed by a different payment method!")
     return self.cleaned_data['bankaccount']
Ejemplo n.º 3
0
 def clean_merchantaccount(self):
     n = exec_to_scalar(
         "SELECT count(1) FROM invoices_invoicepaymentmethod WHERE classname='postgresqleu.util.payment.adyen.AdyenBanktransfer' AND config->>'merchantaccount' = %(account)s AND (id != %(self)s OR %(self)s IS NULL)",
         {
             'account': self.cleaned_data['merchantaccount'],
             'self': self.instance.id,
         })
     if n > 0:
         raise ValidationError(
             "Sorry, there is already a bank transfer entry for this merchant account"
         )
     return self.cleaned_data['merchantaccount']
Ejemplo n.º 4
0
def nagios(request):
    _validate_monitor_request(request)

    # Summary view of "a couple of things to monitor", at a global level.
    # Note that this monitoring is about the system *itself*, not about conferences etc.

    errors = []

    # Check that there is a jobs runner connected
    if exec_to_scalar(
            "SELECT NOT EXISTS (SELECT 1 FROM pg_stat_activity WHERE application_name='pgeu scheduled job runner' AND datname=current_database())"
    ):
        errors.append('No job scheduler connected to database')

    if exec_to_scalar(
            "SELECT EXISTS (SELECT 1 FROM mailqueue_queuedmail WHERE sendtime < now() - '2 minutes'::interval)"
    ):
        errors.append('Unsent emails are present in the outbound mailqueue')

    if errors:
        return HttpResponse("CRITICAL: {}".format(", ".join(errors)),
                            content_type='text/plain')
    else:
        return HttpResponse("OK", content_type='text/plain')
Ejemplo n.º 5
0
def _attendee_email_form(request, conference, query, breadcrumbs):
    if request.method == 'POST':
        idlist = list(map(int, request.POST['idlist'].split(',')))
    else:
        if 'idlist' not in request.GET:
            raise Http404("Mandatory parameter idlist is missing")
        idlist = list(map(int, request.GET['idlist'].split(',')))

    queryparams = {'conference': conference.id, 'idlist': idlist}
    recipients = exec_to_dict(query, queryparams)

    initial = {
        '_from': '{0} <{1}>'.format(conference.conferencename, conference.contactaddr),
        'recipients': escape(", ".join(['{0} <{1}>'.format(x['fullname'], x['email']) for x in recipients])),
        'idlist': ",".join(map(str, idlist)),
        'storeonregpage': True,
    }

    if request.method == 'POST':
        p = request.POST.copy()
        p['recipients'] = initial['recipients']
        form = BackendSendEmailForm(conference, data=p, initial=initial)
        if form.is_valid():
            with transaction.atomic():
                if form.cleaned_data['storeonregpage']:
                    mailid = exec_to_scalar("INSERT INTO confreg_attendeemail (conference_id, sentat, subject, message, tocheckin, tovolunteers) VALUES (%(confid)s, CURRENT_TIMESTAMP, %(subject)s, %(message)s, false, false) RETURNING id", {
                        'confid': conference.id,
                        'subject': form.cleaned_data['subject'],
                        'message': form.cleaned_data['message'],
                    })
                for r in recipients:
                    send_conference_mail(conference,
                                         r['email'],
                                         form.cleaned_data['subject'],
                                         'confreg/mail/attendee_mail.txt',
                                         {
                                             'body': form.cleaned_data['message'],
                                             'linkback': form.cleaned_data['storeonregpage'],
                                         },
                                         receivername=r['fullname'],
                    )

                    if form.cleaned_data['storeonregpage']:
                        if r['regid']:
                            # Existing registration, so attach directly to attendee
                            exec_no_result("INSERT INTO confreg_attendeemail_registrations (attendeemail_id, conferenceregistration_id) VALUES (%(mailid)s, %(reg)s)", {
                                'mailid': mailid,
                                'reg': r['regid'],
                            })
                        else:
                            # No existing registration, so queue it up in case the attendee
                            # might register later. We have the userid...
                            exec_no_result("INSERT INTO confreg_attendeemail_pending_regs (attendeemail_id, user_id) VALUES (%(mailid)s, %(userid)s)", {
                                'mailid': mailid,
                                'userid': r['user_id'],
                            })
                if form.cleaned_data['storeonregpage']:
                    messages.info(request, "Email sent to %s attendees, and added to their registration pages when possible" % len(recipients))
                else:
                    messages.info(request, "Email sent to %s attendees" % len(recipients))

            return HttpResponseRedirect('../')
    else:
        form = BackendSendEmailForm(conference, initial=initial)

    return render(request, 'confreg/admin_backend_form.html', {
        'conference': conference,
        'basetemplate': 'confreg/confadmin_base.html',
        'form': form,
        'what': 'new email',
        'savebutton': 'Send email',
        'cancelurl': '../',
        'breadcrumbs': breadcrumbs,
    })
Ejemplo n.º 6
0
def signup_admin_sendmail(request, urlname, signupid):
    conference = get_authenticated_conference(request, urlname)

    signup = get_object_or_404(Signup, conference=conference, pk=signupid)

    optionstrings = signup.options.split(',')
    additional_choices = [('r_{0}'.format(r), 'Recipients who responded {0}'.format(optionstrings[r])) for r in range(len(optionstrings))]

    if request.method == 'POST':
        params = {'confid': conference.id, 'signup': signup.id}
        rr = request.POST['recipients']
        if signup.public:
            qq = "FROM confreg_conferenceregistration r WHERE payconfirmedat IS NOT NULL AND canceledat IS NULL AND conference_id=%(confid)s"
        else:
            qq = "FROM confreg_conferenceregistration r WHERE payconfirmedat IS NOT NULL AND canceledat IS NULL AND conference_id=%(confid)s AND (regtype_id IN (SELECT registrationtype_id FROM confwiki_signup_regtypes srt WHERE srt.signup_id=%(signup)s) OR id IN (SELECT conferenceregistration_id FROM confwiki_signup_attendees WHERE signup_id=%(signup)s))"

        if rr == 'responded':
            qq += " AND EXISTS (SELECT 1 FROM confwiki_attendeesignup was WHERE was.signup_id=%(signup)s AND was.attendee_id=r.id)"
        elif rr == 'noresp':
            qq += " AND NOT EXISTS (SELECT 1 FROM confwiki_attendeesignup was WHERE was.signup_id=%(signup)s AND was.attendee_id=r.id)"

        elif rr.startswith('r_'):
            optnum = int(rr[2:])
            qq += " AND EXISTS (SELECT 1 FROM confwiki_attendeesignup was WHERE was.signup_id=%(signup)s AND was.attendee_id=r.id AND choice=%(choice)s)"
            params['choice'] = optionstrings[optnum]

        numtosend = exec_to_scalar("SELECT count(*) {0}".format(qq), params)

        form = SignupSendmailForm(conference, additional_choices, data=request.POST, num=numtosend)
        if form.is_valid():
            towhat = next(v for k, v in form.recipient_choices if k == rr)
            recipients = exec_to_list("SELECT firstname || ' ' || lastname, email {0}".format(qq), params)
            for n, e in recipients:
                send_simple_mail(conference.contactaddr,
                                 e,
                                 "[{0}] {1}".format(conference.conferencename, form.cleaned_data['subject']),
                                 "{0}\n\nTo view the signup, please see {1}/events/{2}/register/signup/{3}-{4}/".format(
                                     form.cleaned_data['body'],
                                     settings.SITEBASE, conference.urlname, slugify(signup.title), signup.id),
                                 sendername=conference.conferencename,
                                 receivername=n)
            send_simple_mail(conference.notifyaddr,
                             conference.notifyaddr,
                             'Email sent to signup {0}'.format(signup.title),
                             """An email was sent to recipients of the signup "{0}"\nIt was sent to {1}, leading to {2} recipients.\n\nSubject:{3}\nBody:\n{4}\n""".format(
                                 signup.title,
                                 towhat,
                                 numtosend,
                                 form.cleaned_data['subject'],
                                 form.cleaned_data['body'],
                             ),
                             sendername=conference.conferencename,
            )
            messages.info(request, "E-mail delivered to {0} recipients.".format(numtosend))
            return HttpResponseRedirect('../')
        else:
            if signup.public and rr == 'all':
                messages.warning(request, "Since this is a public signup and you are sending to all attendees, you should probably consider using regular mail send instead of signup mail send, so it gets delivered to future attendees as well!")
    else:
        form = SignupSendmailForm(conference, additional_choices)
        numtosend = None

    return render(request, 'confwiki/signup_sendmail_form.html', {
        'conference': conference,
        'form': form,
        'signup': signup,
        'numtosend': numtosend,
        'breadcrumbs': (
            ('/events/admin/{0}/signups/'.format(conference.urlname), 'Signups'),
            ('/events/admin/{0}/signups/{1}/'.format(conference.urlname, signup.id), signup.title),
        ),
        'helplink': 'signups',
    })