Ejemplo n.º 1
0
def form_detail(request, slug, template="forms/form_detail.html"):
    """
    Display a built form and handle submission.
    """
    published = Form.objects.published(for_user=request.user)
    form = get_object_or_404(published, slug=slug)

    if not has_view_perm(request.user, 'forms.view_form', form):
        raise Http403

    # If form has a recurring payment, make sure the user is logged in
    if form.recurring_payment:
        [email_field] = form.fields.filter(
            field_type__iexact='EmailVerificationField')[:1] or [None]
        if request.user.is_anonymous and not email_field:
            # anonymous user - if we don't have the email field, redirect to login
            response = redirect('auth_login')
            response['Location'] += '?next=%s' % form.get_absolute_url()
            return response
        if request.user.is_superuser and not email_field:
            messages.add_message(
                request, messages.WARNING,
                'Please edit the form to include an email field ' +
                'as it is required for setting up a recurring ' +
                'payment for anonymous users.')

    if form.custom_payment and not form.recurring_payment:
        billing_form = BillingForm(request.POST or None)
        if request.user.is_authenticated:
            billing_form.initial = {
                'first_name': request.user.first_name,
                'last_name': request.user.last_name,
                'email': request.user.email
            }
    else:
        billing_form = None

    form_for_form = FormForForm(form, request.user, request.session,
                                request.POST or None, request.FILES or None)

    if get_setting('site', 'global', 'captcha'):  # add captcha
        if billing_form:
            # append the captcha to the end of the billing form
            captcha_field = CustomCatpchaField(label=_('Type the code below'))
            if 'captcha' in form_for_form.fields:
                form_for_form.fields.pop('captcha')
            billing_form.fields['captcha'] = captcha_field

    for field in form_for_form.fields:
        field_default = request.GET.get(field, None)
        if field_default:
            form_for_form.fields[field].initial = field_default

    if request.method == "POST":
        if form_for_form.is_valid() and (not billing_form
                                         or billing_form.is_valid()):
            entry = form_for_form.save()
            entry.entry_path = request.POST.get("entry_path", "")
            if request.user.is_anonymous:
                entry.creator = entry.check_and_create_user()
            else:
                entry.creator = request.user
            entry.save()
            entry.set_group_subscribers()

            # Email
            subject = generate_email_subject(form, entry)
            email_headers = {}  # content type specified below
            if form.email_from:
                email_headers.update({'Reply-To': form.email_from})

            # Email to submitter
            # fields aren't included in submitter body to prevent spam
            submitter_body = generate_submitter_email_body(
                entry, form_for_form)
            email_from = form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form_for_form.email_to()
            is_spam = Email.is_blocked(email_to)
            if is_spam:
                # log the spam
                description = "Email \"{0}\" blocked because it is listed in email_blocks.".format(
                    email_to)
                EventLog.objects.log(instance=form, description=description)

                if form.completion_url:
                    return HttpResponseRedirect(form.completion_url)
                return redirect("form_sent", form.slug)

            email = Email()
            email.subject = subject
            email.reply_to = form.email_from

            if email_to and form.send_email and form.email_text:
                # Send message to the person who submitted the form.
                email.recipient = email_to
                email.body = submitter_body
                email.send(fail_silently=getattr(settings,
                                                 'EMAIL_FAIL_SILENTLY', True))
                # log an event
                EventLog.objects.log(
                    instance=form,
                    description='Confirmation email sent to {}'.format(
                        email_to))

            # Email copies to admin
            admin_body = generate_admin_email_body(entry,
                                                   form_for_form,
                                                   user=request.user)
            email_from = email_to or email_from  # Send from the email entered.
            email_headers = {}  # Reset the email_headers
            email_headers.update({'Reply-To': email_from})
            email_copies = [
                e.strip() for e in form.email_copies.split(',') if e.strip()
            ]

            subject = subject.encode(errors='ignore')
            email_recipients = entry.get_function_email_recipients()
            # reply_to of admin emails goes to submitter
            email.reply_to = email_to

            if email_copies or email_recipients:
                # prepare attachments
                attachments = []
                # Commenting out the attachment block to not add attachments to the email for the reason below:
                # According to SES message quotas https://docs.aws.amazon.com/ses/latest/DeveloperGuide/quotas.html,
                # the maximum message size (including attachments) is 10 MB per message (after base64 encoding)
                # which means the actual size should be less than 7.5 MB or so because text after encoded with the BASE64
                # algorithm increases its size by 1/3. But the allowed upload size is much larger than 7.5 MB.
                #                 try:
                #                     for f in form_for_form.files.values():
                #                         f.seek(0)
                #                         attachments.append((f.name, f.read()))
                #                 except ValueError:
                #                     attachments = []
                #                     for field_entry in entry.fields.all():
                #                         if field_entry.field.field_type == 'FileField':
                #                             try:
                #                                 f = default_storage.open(field_entry.value)
                #                             except IOError:
                #                                 pass
                #                             else:
                #                                 f.seek(0)
                #                                 attachments.append((f.name.split('/')[-1], f.read()))

                fail_silently = getattr(settings, 'EMAIL_FAIL_SILENTLY', True)
                # Send message to the email addresses listed in the copies
                if email_copies:
                    email.body = admin_body
                    email.recipient = email_copies
                    #                     if request.user.is_anonymous or not request.user.is_active:
                    #                         email.content_type = 'text'
                    email.send(fail_silently=fail_silently,
                               attachments=attachments)

                # Email copies to recipient list indicated in the form
                if email_recipients:
                    email.body = admin_body
                    email.recipient = email_recipients
                    email.send(fail_silently=fail_silently,
                               attachments=attachments)

            # payment redirect
            if (form.custom_payment
                    or form.recurring_payment) and entry.pricing:
                # get the pricing's price, custom or otherwise
                price = entry.pricing.price or form_for_form.cleaned_data.get(
                    'custom_price')

                if form.recurring_payment:
                    if request.user.is_anonymous:
                        rp_user = entry.creator
                    else:
                        rp_user = request.user
                    billing_start_dt = datetime.datetime.now()
                    trial_period_start_dt = None
                    trial_period_end_dt = None
                    if entry.pricing.has_trial_period:
                        trial_period_start_dt = datetime.datetime.now()
                        trial_period_end_dt = trial_period_start_dt + datetime.timedelta(
                            1)
                        billing_start_dt = trial_period_end_dt
                    # Create recurring payment
                    rp = RecurringPayment(
                        user=rp_user,
                        description=form.title,
                        billing_period=entry.pricing.billing_period,
                        billing_start_dt=billing_start_dt,
                        num_days=entry.pricing.num_days,
                        due_sore=entry.pricing.due_sore,
                        payment_amount=price,
                        taxable=entry.pricing.taxable,
                        tax_rate=entry.pricing.tax_rate,
                        has_trial_period=entry.pricing.has_trial_period,
                        trial_period_start_dt=trial_period_start_dt,
                        trial_period_end_dt=trial_period_end_dt,
                        trial_amount=entry.pricing.trial_amount,
                        creator=rp_user,
                        creator_username=rp_user.username,
                        owner=rp_user,
                        owner_username=rp_user.username,
                    )
                    rp.save()
                    if rp.platform == 'authorizenet':
                        rp.add_customer_profile()

                    # redirect to recurring payments
                    messages.add_message(request, messages.SUCCESS,
                                         _('Successful transaction.'))
                    return redirect('recurring_payment.view_account', rp.id,
                                    rp.guid)
                else:
                    # create the invoice
                    invoice = make_invoice_for_entry(entry, custom_price=price)

                    update_invoice_for_entry(invoice, billing_form)

                    # log an event for invoice add
                    EventLog.objects.log(instance=form)

                    # redirect to online payment
                    if invoice.balance > 0:
                        if (entry.payment_method.machine_name
                            ).lower() == 'credit-card':
                            return redirect('payment.pay_online', invoice.id,
                                            invoice.guid)
                        # redirect to invoice page
                        return redirect('invoice.view', invoice.id,
                                        invoice.guid)

            # default redirect
            if form.completion_url:
                completion_url = form.completion_url.strip().replace(
                    '[entry_id]', str(entry.id))
                return HttpResponseRedirect(completion_url)
            return redirect("form_sent", form.slug)

    # set form's template to forms/base.html if no template or template doesn't exist
    if not form.template or not template_exists(form.template):
        form.template = "forms/base.html"

    context = {
        "form": form,
        'billing_form': billing_form,
        "form_for_form": form_for_form,
        'form_template': form.template,
    }
    return render_to_resp(request=request,
                          template_name=template,
                          context=context)
Ejemplo n.º 2
0
def form_detail(request, slug, template="forms/form_detail.html"):
    """
    Display a built form and handle submission.
    """
    published = Form.objects.published(for_user=request.user)
    form = get_object_or_404(published, slug=slug)

    if not has_view_perm(request.user,'forms.view_form',form):
        raise Http403

    # If form has a recurring payment, make sure the user is logged in
    if form.recurring_payment:
        [email_field] = form.fields.filter(field_type__iexact='EmailVerificationField')[:1] or [None]
        if request.user.is_anonymous and not email_field:
            # anonymous user - if we don't have the email field, redirect to login
            response = redirect('auth_login')
            response['Location'] += '?next=%s' % form.get_absolute_url()
            return response
        if request.user.is_superuser and not email_field:
            messages.add_message(request, messages.WARNING,
                    'Please edit the form to include an email field ' +
                    'as it is required for setting up a recurring ' +
                    'payment for anonymous users.')

    form_for_form = FormForForm(form, request.user, request.POST or None, request.FILES or None)
    if form.custom_payment and not form.recurring_payment:
        billing_form = BillingForm(request.POST or None)
        if request.user.is_authenticated:
            billing_form.initial = {
                        'first_name':request.user.first_name,
                        'last_name':request.user.last_name,
                        'email':request.user.email}
    else:
        billing_form = None

    for field in form_for_form.fields:
        field_default = request.GET.get(field, None)
        if field_default:
            form_for_form.fields[field].initial = field_default

    if request.method == "POST":
        if form_for_form.is_valid() and (not billing_form or billing_form.is_valid()):
            entry = form_for_form.save()
            entry.entry_path = request.POST.get("entry_path", "")
            if request.user.is_anonymous:
                if entry.get_email_address():
                    emailfield = entry.get_email_address()
                    firstnamefield = entry.get_first_name()
                    lastnamefield = entry.get_last_name()
                    phonefield = entry.get_phone_number()
                    password = ''
                    for i in range(0, 10):
                        password += random.choice(string.ascii_lowercase + string.ascii_uppercase)

                    user_list = User.objects.filter(email=emailfield).order_by('-last_login')
                    if user_list:
                        anonymous_creator = user_list[0]
                    else:
                        anonymous_creator = User(username=emailfield[:30], email=emailfield,
                                                 first_name=firstnamefield, last_name=lastnamefield)
                        anonymous_creator.set_password(password)
                        anonymous_creator.is_active = False
                        anonymous_creator.save()
                        anonymous_profile = Profile(user=anonymous_creator, owner=anonymous_creator,
                                                    creator=anonymous_creator, phone=phonefield)
                        anonymous_profile.save()
                    entry.creator = anonymous_creator
            else:
                entry.creator = request.user
            entry.save()
            entry.set_group_subscribers()

            # Email
            subject = generate_email_subject(form, entry)
            email_headers = {}  # content type specified below
            if form.email_from:
                email_headers.update({'Reply-To':form.email_from})

            # Email to submitter
            # fields aren't included in submitter body to prevent spam
            submitter_body = generate_submitter_email_body(entry, form_for_form)
            email_from = form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form_for_form.email_to()
            is_spam = Email.is_blocked(email_to)
            if is_spam:
                # log the spam
                description = "Email \"{0}\" blocked because it is listed in email_blocks.".format(email_to)
                EventLog.objects.log(instance=form, description=description)

                if form.completion_url:
                    return HttpResponseRedirect(form.completion_url)
                return redirect("form_sent", form.slug)

            email = Email()
            email.subject = subject
            email.reply_to = form.email_from

            if email_to and form.send_email and form.email_text:
                # Send message to the person who submitted the form.
                email.recipient = email_to
                email.body = submitter_body
                email.send(fail_silently=True)

            # Email copies to admin
            admin_body = generate_admin_email_body(entry, form_for_form)
            email_from = email_to or email_from # Send from the email entered.
            email_headers = {}  # Reset the email_headers
            email_headers.update({'Reply-To':email_from})
            email_copies = [e.strip() for e in form.email_copies.split(',') if e.strip()]

            subject = subject.encode(errors='ignore')
            email_recipients = entry.get_function_email_recipients()
            # reply_to of admin emails goes to submitter
            email.reply_to = email_to

            if email_copies or email_recipients:
                # prepare attachments
                attachments = []
                try:
                    for f in form_for_form.files.values():
                        f.seek(0)
                        attachments.append((f.name, f.read()))
                except ValueError:
                    attachments = []
                    for field_entry in entry.fields.all():
                        if field_entry.field.field_type == 'FileField':
                            try:
                                f = default_storage.open(field_entry.value)
                            except IOError:
                                pass
                            else:
                                f.seek(0)
                                attachments.append((f.name.split('/')[-1], f.read()))

                # Send message to the email addresses listed in the copies
                if email_copies:
                    email.body = admin_body
                    email.recipient = email_copies
                    email.send(fail_silently=True, attachments=attachments)

                # Email copies to recipient list indicated in the form
                if email_recipients:
                    email.body = admin_body
                    email.recipient = email_recipients
                    email.send(fail_silently=True, attachments=attachments)

            # payment redirect
            if (form.custom_payment or form.recurring_payment) and entry.pricing:
                # get the pricing's price, custom or otherwise
                price = entry.pricing.price or form_for_form.cleaned_data.get('custom_price')

                if form.recurring_payment:
                    if request.user.is_anonymous:
                        rp_user = entry.creator
                    else:
                        rp_user = request.user
                    billing_start_dt = datetime.datetime.now()
                    trial_period_start_dt = None
                    trial_period_end_dt = None
                    if entry.pricing.has_trial_period:
                        trial_period_start_dt = datetime.datetime.now()
                        trial_period_end_dt = trial_period_start_dt + datetime.timedelta(1)
                        billing_start_dt = trial_period_end_dt
                    # Create recurring payment
                    rp = RecurringPayment(
                             user=rp_user,
                             description=form.title,
                             billing_period=entry.pricing.billing_period,
                             billing_start_dt=billing_start_dt,
                             num_days=entry.pricing.num_days,
                             due_sore=entry.pricing.due_sore,
                             payment_amount=price,
                             taxable=entry.pricing.taxable,
                             tax_rate=entry.pricing.tax_rate,
                             has_trial_period=entry.pricing.has_trial_period,
                             trial_period_start_dt=trial_period_start_dt,
                             trial_period_end_dt=trial_period_end_dt,
                             trial_amount=entry.pricing.trial_amount,
                             creator=rp_user,
                             creator_username=rp_user.username,
                             owner=rp_user,
                             owner_username=rp_user.username,
                         )
                    rp.save()
                    if rp.platform == 'authorizenet':
                        rp.add_customer_profile()

                    # redirect to recurring payments
                    messages.add_message(request, messages.SUCCESS, _('Successful transaction.'))
                    return redirect('recurring_payment.view_account', rp.id, rp.guid)
                else:
                    # create the invoice
                    invoice = make_invoice_for_entry(entry, custom_price=price)

                    update_invoice_for_entry(invoice, billing_form)

                    # log an event for invoice add
                    EventLog.objects.log(instance=form)

                    # redirect to online payment
                    if (entry.payment_method.machine_name).lower() == 'credit-card':
                        return redirect('payment.pay_online', invoice.id, invoice.guid)
                    # redirect to invoice page
                    return redirect('invoice.view', invoice.id, invoice.guid)

            # default redirect
            if form.completion_url:
                return HttpResponseRedirect(form.completion_url.strip())
            return redirect("form_sent", form.slug)

    # set form's template to forms/base.html if no template or template doesn't exist
    if not form.template or not template_exists(form.template):
        form.template = "forms/base.html"

    context = {
        "form": form,
        'billing_form': billing_form,
        "form_for_form": form_for_form,
        'form_template': form.template,
    }
    return render_to_resp(request=request, template_name=template, context=context)
Ejemplo n.º 3
0
def send_now(users, label, extra_context=None, on_site=True, *args, **kwargs):
    """
    Creates a new notice.

    This is intended to be how other apps create new notices.

    notification.send(user, 'friends_invite_sent', {
        'spam': 'eggs',
        'foo': 'bar',
    )

    You can pass in on_site=False to prevent the notice emitted from being
    displayed on the site.
    """

    send = kwargs.get('send', False)

    if extra_context is None:
        extra_context = {}

    try:
        notice_type = NoticeType.objects.get(label=label)
    except (NoticeType.DoesNotExist, NoticeType.MultipleObjectsReturned):
        notice_type = None

    if notice_type:

        protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
        current_site = Site.objects.get_current()

        notices_url = u"%s://%s%s" % (
            protocol,
            str(current_site),
            reverse("notification_notices"),
        )

        current_language = get_language()

        formats = (
            'full.html',
            'short.txt',
            'notice.html',
        )  # TODO make formats configurable

        for user in users:
            if not user.email or Email.is_blocked(user.email):
                continue

            recipients = []
            headers = {}
            # get user language for user from language store defined in
            # NOTIFICATION_LANGUAGE_MODULE setting
            try:
                language = get_notification_language(user)
            except LanguageStoreNotAvailable:
                language = None

            if language is not None:
                # activate the user's language
                activate(language)

            extra_context.update({
                "user": user,
                "notice": gettext(notice_type.display),
                "notices_url": notices_url,
                "current_site": current_site,
            })

            # test for request in the extra_context
            if 'request' in extra_context:
                request = extra_context['request']
            else:
                request = None

            # get prerendered format messages
            messages = get_formatted_messages(formats, label, extra_context)

            # Strip newlines from subject
            extra_context.update({'message': mark_safe(messages['short'])})
            subject = ''.join(render_to_string(template_name='notification/email_subject.txt',
                context=extra_context, request=request).splitlines())

            extra_context.update({'message': mark_safe(messages['full'])})
            body = render_to_string(template_name='notification/email_body.txt',
                context=extra_context, request=request)

            Notice.objects.create(user=user,
                                  message=messages['notice'][0],
                                  notice_type=notice_type,
                                  on_site=on_site)
            if should_send(user, notice_type, "1", send=send) and user.email:  # Email
                recipients.append(user.email)

            if messages['full'][1] == '.html':
                # headers = {'Content-Type': 'text/html'}
                content_type = 'html'
            else:
                # headers = {'Content-Type': 'text/plain'}
                content_type = 'text'

            email = EmailMessage(subject, add_tendenci_footer(body), settings.DEFAULT_FROM_EMAIL, recipients, headers=headers)
            email.content_subtype = content_type
            email.send()

        # reset environment to original language
        activate(current_language)
Ejemplo n.º 4
0
def send_emails(emails, label, extra_context=None, on_site=True):
    """
    This method accepts a list of email addresses
    as opposed to a list of users. This is a custom method
    as opposed to send(), send_now(), and queue()

    Just send the notice to a list of emails immediately.
    No new notice created here
    notification.send_emails(email_list, 'friends_invite_sent', {
        'spam': 'eggs',
        'foo': 'bar',
    )
    """
    # exclude blocked emails
    emails = [e for e in emails if not Email.is_blocked(e)]
    if not emails:
        return
    
    if extra_context is None:
        extra_context = {}

    try:
        notice_type = NoticeType.objects.get(label=label)
    except NoticeType.DoesNotExist as err:
        logger.warning('Skipping notification send for "{label}": {err}'.format(
            label=label, err=err))
        # Stop here because we need a notice_type
        return None

    headers = {}
    protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
    current_site = Site.objects.get_current()

    notices_url = u"%s://%s%s" % (
        protocol,
        str(current_site),
        reverse("notification_notices"),
    )

    formats = (
        'full.html',
        'short.txt',
        'notice.html',
    )  # TODO make formats configurable

    extra_context.update({
        "notice": gettext(notice_type.display),
        "notices_url": notices_url,
        "current_site": current_site,
        'SITE_GLOBAL_SITEURL': get_setting('site', 'global', 'siteurl'),
        'SITE_GLOBAL_SITEDISPLAYNAME': get_setting('site', 'global', 'sitedisplayname'),
    })

    # test for request in the extra_context
    if 'request' in extra_context:
        request = extra_context['request']
    else:
        request = None

    # get prerendered format messages
    messages = get_formatted_messages(formats, label, extra_context)

    if 'admin' in label:
        subject = messages['short']
        body = messages['full']

    else:
        extra_context.update({'message': mark_safe(messages['short'])})
        subject = render_to_string(
            template_name='notification/email_subject.txt',
            context=extra_context, request=request)

        extra_context.update({'message': mark_safe(messages['full'])})
        body = render_to_string(
            template_name='notification/email_body.txt',
            context=extra_context, request=request)

    if 'reply_to' in extra_context:
        reply_to = extra_context['reply_to']
        if reply_to:
            headers['Reply-To'] = reply_to
    else:
        reply_to = ''

    sender = extra_context.get('sender', '')
    if not sender:
        sender = get_setting('site', 'global', 'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL
        if not sender:
            sender = settings.DEFAULT_FROM_EMAIL

    sender_display = extra_context.get('sender_display', '')
    # Add quotes around display name to prevent errors on sending
    # when display name contains comma or other control characters, - jennyq
    from_display = '"%s" <%s>' % (sender_display, sender)

    if sender_display:
        headers['From'] = from_display

    recipient_bcc = extra_context.get('recipient_bcc') or []
    content_type = 'html'

    # removing newlines
    subject = ''.join(subject.splitlines())
    body = add_tendenci_footer(body)

    for email_addr in emails:
        if validate_email(email_addr):
            recipients = [email_addr]

            if recipient_bcc:
                email = EmailMessage(subject, body, sender,
                                     recipients, recipient_bcc, headers=headers)
            else:
                email = EmailMessage(subject, body, sender,
                                     recipients, headers=headers)
            email.content_subtype = content_type
    
            try:
                email.send(fail_silently=True)  # should we raise exception or not?
            except UnicodeError:
                pass

    to = ','.join(emails)
    bcc = ','.join(recipient_bcc)
    reply_to = reply_to or str()

    NoticeEmail.objects.create(
        emails=to,
        sender=sender,
        bcc=bcc,
        title=subject,
        content=body,
        reply_to=reply_to,
        from_display=from_display,
        notice_type=notice_type
    )
Ejemplo n.º 5
0
def form_detail(request, slug, template="forms/form_detail.html"):
    """
    Display a built form and handle submission.
    """
    published = Form.objects.published(for_user=request.user)
    form = get_object_or_404(published, slug=slug)

    if not has_view_perm(request.user, 'forms.view_form', form):
        raise Http403

    # If form has a recurring payment, make sure the user is logged in
    if form.recurring_payment:
        [email_field] = form.fields.filter(
            field_type__iexact='EmailVerificationField')[:1] or [None]
        if request.user.is_anonymous() and not email_field:
            # anonymous user - if we don't have the email field, redirect to login
            response = redirect('auth_login')
            response['Location'] += '?next=%s' % form.get_absolute_url()
            return response
        if request.user.is_superuser and not email_field:
            messages.add_message(
                request, messages.WARNING,
                'Please edit the form to include an email field ' +
                'as it is required for setting up a recurring ' +
                'payment for anonymous users.')

    form_for_form = FormForForm(form, request.user, request.POST or None,
                                request.FILES or None)
    if form.custom_payment and not form.recurring_payment:
        billing_form = BillingForm(request.POST or None)
        if request.user.is_authenticated():
            billing_form.initial = {
                'first_name': request.user.first_name,
                'last_name': request.user.last_name,
                'email': request.user.email
            }
    else:
        billing_form = None

    for field in form_for_form.fields:
        field_default = request.GET.get(field, None)
        if field_default:
            form_for_form.fields[field].initial = field_default

    if request.method == "POST":
        if form_for_form.is_valid() and (not billing_form
                                         or billing_form.is_valid()):
            entry = form_for_form.save()
            entry.entry_path = request.POST.get("entry_path", "")
            if request.user.is_anonymous():
                if entry.get_email_address():
                    emailfield = entry.get_email_address()
                    firstnamefield = entry.get_first_name()
                    lastnamefield = entry.get_last_name()
                    phonefield = entry.get_phone_number()
                    password = ''
                    for i in range(0, 10):
                        password += random.choice(string.ascii_lowercase +
                                                  string.ascii_uppercase)

                    user_list = User.objects.filter(
                        email=emailfield).order_by('-last_login')
                    if user_list:
                        anonymous_creator = user_list[0]
                    else:
                        anonymous_creator = User(username=emailfield[:30],
                                                 email=emailfield,
                                                 first_name=firstnamefield,
                                                 last_name=lastnamefield)
                        anonymous_creator.set_password(password)
                        anonymous_creator.is_active = False
                        anonymous_creator.save()
                        anonymous_profile = Profile(user=anonymous_creator,
                                                    owner=anonymous_creator,
                                                    creator=anonymous_creator,
                                                    phone=phonefield)
                        anonymous_profile.save()
                    entry.creator = anonymous_creator
            else:
                entry.creator = request.user
            entry.save()
            entry.set_group_subscribers()

            # Email
            subject = generate_email_subject(form, entry)
            email_headers = {}  # content type specified below
            if form.email_from:
                email_headers.update({'Reply-To': form.email_from})

            # Email to submitter
            # fields aren't included in submitter body to prevent spam
            submitter_body = generate_submitter_email_body(
                entry, form_for_form)
            email_from = form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form_for_form.email_to()
            is_spam = Email.is_blocked(email_to)
            if is_spam:
                # log the spam
                description = "Email \"{0}\" blocked because it is listed in email_blocks.".format(
                    email_to)
                EventLog.objects.log(instance=form, description=description)

                if form.completion_url:
                    return HttpResponseRedirect(form.completion_url)
                return redirect("form_sent", form.slug)

            email = Email()
            email.subject = subject
            email.reply_to = form.email_from

            if email_to and form.send_email and form.email_text:
                # Send message to the person who submitted the form.
                email.recipient = email_to
                email.body = submitter_body
                email.send(fail_silently=True)

            # Email copies to admin
            admin_body = generate_admin_email_body(entry, form_for_form)
            email_from = email_to or email_from  # Send from the email entered.
            email_headers = {}  # Reset the email_headers
            email_headers.update({'Reply-To': email_from})
            email_copies = [
                e.strip() for e in form.email_copies.split(',') if e.strip()
            ]

            subject = subject.encode(errors='ignore')
            email_recipients = entry.get_function_email_recipients()
            # reply_to of admin emails goes to submitter
            email.reply_to = email_to

            if email_copies or email_recipients:
                # prepare attachments
                attachments = []
                try:
                    for f in form_for_form.files.values():
                        f.seek(0)
                        attachments.append((f.name, f.read()))
                except ValueError:
                    attachments = []
                    for field_entry in entry.fields.all():
                        if field_entry.field.field_type == 'FileField':
                            try:
                                f = default_storage.open(field_entry.value)
                            except IOError:
                                pass
                            else:
                                f.seek(0)
                                attachments.append(
                                    (f.name.split('/')[-1], f.read()))

                # Send message to the email addresses listed in the copies
                if email_copies:
                    email.body = admin_body
                    email.recipient = email_copies
                    email.send(fail_silently=True, attachments=attachments)

                # Email copies to recipient list indicated in the form
                if email_recipients:
                    email.body = admin_body
                    email.recipient = email_recipients
                    email.send(fail_silently=True, attachments=attachments)

            # payment redirect
            if (form.custom_payment
                    or form.recurring_payment) and entry.pricing:
                # get the pricing's price, custom or otherwise
                price = entry.pricing.price or form_for_form.cleaned_data.get(
                    'custom_price')

                if form.recurring_payment:
                    if request.user.is_anonymous():
                        rp_user = entry.creator
                    else:
                        rp_user = request.user
                    billing_start_dt = datetime.datetime.now()
                    trial_period_start_dt = None
                    trial_period_end_dt = None
                    if entry.pricing.has_trial_period:
                        trial_period_start_dt = datetime.datetime.now()
                        trial_period_end_dt = trial_period_start_dt + datetime.timedelta(
                            1)
                        billing_start_dt = trial_period_end_dt
                    # Create recurring payment
                    rp = RecurringPayment(
                        user=rp_user,
                        description=form.title,
                        billing_period=entry.pricing.billing_period,
                        billing_start_dt=billing_start_dt,
                        num_days=entry.pricing.num_days,
                        due_sore=entry.pricing.due_sore,
                        payment_amount=price,
                        taxable=entry.pricing.taxable,
                        tax_rate=entry.pricing.tax_rate,
                        has_trial_period=entry.pricing.has_trial_period,
                        trial_period_start_dt=trial_period_start_dt,
                        trial_period_end_dt=trial_period_end_dt,
                        trial_amount=entry.pricing.trial_amount,
                        creator=rp_user,
                        creator_username=rp_user.username,
                        owner=rp_user,
                        owner_username=rp_user.username,
                    )
                    rp.save()
                    if rp.platform == 'authorizenet':
                        rp.add_customer_profile()

                    # redirect to recurring payments
                    messages.add_message(request, messages.SUCCESS,
                                         _('Successful transaction.'))
                    return redirect('recurring_payment.view_account', rp.id,
                                    rp.guid)
                else:
                    # create the invoice
                    invoice = make_invoice_for_entry(entry, custom_price=price)

                    update_invoice_for_entry(invoice, billing_form)

                    # log an event for invoice add
                    EventLog.objects.log(instance=form)

                    # redirect to online payment
                    if (entry.payment_method.machine_name
                        ).lower() == 'credit-card':
                        return redirect('payment.pay_online', invoice.id,
                                        invoice.guid)
                    # redirect to invoice page
                    return redirect('invoice.view', invoice.id, invoice.guid)

            # default redirect
            form.completion_url = form.completion_url.strip(' ')
            if form.completion_url:
                return HttpResponseRedirect(form.completion_url)
            return redirect("form_sent", form.slug)

    # set form's template to forms/base.html if no template or template doesn't exist
    if not form.template or not template_exists(form.template):
        form.template = "forms/base.html"

    context = {
        "form": form,
        'billing_form': billing_form,
        "form_for_form": form_for_form,
        'form_template': form.template,
    }
    return render_to_response(template, context, RequestContext(request))
Ejemplo n.º 6
0
def send_now(users, label, extra_context=None, on_site=True, *args, **kwargs):
    """
    Creates a new notice.

    This is intended to be how other apps create new notices.

    notification.send(user, 'friends_invite_sent', {
        'spam': 'eggs',
        'foo': 'bar',
    )

    You can pass in on_site=False to prevent the notice emitted from being
    displayed on the site.
    """

    send = kwargs.get('send', False)

    if extra_context is None:
        extra_context = {}

    try:
        notice_type = NoticeType.objects.get(label=label)
    except (NoticeType.DoesNotExist, NoticeType.MultipleObjectsReturned):
        notice_type = None

    if notice_type:

        protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
        current_site = Site.objects.get_current()

        notices_url = u"%s://%s%s" % (
            protocol,
            unicode(current_site),
            reverse("notification_notices"),
        )

        current_language = get_language()

        formats = (
            'full.html',
            'short.txt',
            'notice.html',
        )  # TODO make formats configurable

        for user in users:
            if not user.email or Email.is_blocked(user.email):
                continue

            recipients = []
            headers = {}
            # get user language for user from language store defined in
            # NOTIFICATION_LANGUAGE_MODULE setting
            try:
                language = get_notification_language(user)
            except LanguageStoreNotAvailable:
                language = None

            if language is not None:
                # activate the user's language
                activate(language)

            # test for request in the extra_context
            if 'request' in extra_context.keys():
                context = RequestContext(extra_context['request'])
                extra_context.update({
                    "user": user,
                    "notice": ugettext(notice_type.display),
                    "notices_url": notices_url,
                    "current_site": current_site,
                })
                context.update(extra_context)
            else:
                # update context with user specific translations
                context = Context({
                    "user": user,
                    "notice": ugettext(notice_type.display),
                    "notices_url": notices_url,
                    "current_site": current_site,
                })
                context.update(extra_context)

            # get prerendered format messages
            messages = get_formatted_messages(formats, label, context)

            # Strip newlines from subject
            subject = ''.join(render_to_string('notification/email_subject.txt', {
                'message': messages['short'][0],
            }, context).splitlines())

            body = render_to_string('notification/email_body.txt', {
                'message': messages['full'][0],
            }, context)

            Notice.objects.create(user=user,
                                  message=messages['notice'][0],
                                  notice_type=notice_type,
                                  on_site=on_site)
            if should_send(user, notice_type, "1", send=send) and user.email:  # Email
                recipients.append(user.email)

            if messages['full'][1] == '.html':
                # headers = {'Content-Type': 'text/html'}
                content_type = 'html'
            else:
                # headers = {'Content-Type': 'text/plain'}
                content_type = 'text'

            email = EmailMessage(subject, body, settings.DEFAULT_FROM_EMAIL, recipients, headers=headers)
            email.content_subtype = content_type
            email.send()

        # reset environment to original language
        activate(current_language)