Exemplo n.º 1
0
    def check_and_create_user(self):
        """
        Check and create a new user if needed (only if payment is involved or 
            "Subscribe to Group" functionality is selected).
        Return the user created or None.
        """
        from tendenci.apps.profiles.models import Profile
        emailfield = self.get_email_address()
        anonymous_creator = None

        if emailfield:
            user_list = User.objects.filter(email=emailfield).order_by('-last_login')
            if user_list:
                anonymous_creator = user_list[0]
            else:
                # Create a new user only if payment is involved or 
                # "Subscribe to Group" functionality selected
                if get_setting('module', 'forms', 'form_submission_create_user') or \
                         self.form.custom_payment or self.form.recurring_payment or \
                         self.fields.filter(field__field_function__in=["GroupSubscription",
                                                                       "GroupSubscriptionAuto"],
                                            ).exclude(value='').exists():
                    anonymous_creator = User(username=emailfield[:30], email=emailfield,
                                             first_name=self.get_first_name(), last_name=self.get_last_name())
                    anonymous_creator.set_unusable_password()
                    anonymous_creator.is_active = False
                    anonymous_creator.save()
                    anonymous_profile = Profile(user=anonymous_creator, owner=anonymous_creator,
                                                creator=anonymous_creator, phone=self.get_phone_number())
                    anonymous_profile.save()

        return anonymous_creator
Exemplo n.º 2
0
    def check_and_create_user(self):
        """
        Check and create a new user if needed (only if payment is involved or
            "Subscribe to Group" functionality is selected).
        Return the user created or None.
        """
        from tendenci.apps.profiles.models import Profile
        emailfield = self.get_email_address()
        anonymous_creator = None

        if emailfield:
            user_list = User.objects.filter(
                email__iexact=emailfield).order_by('-last_login')
            if user_list:
                anonymous_creator = user_list[0]
            else:
                # Create a new user only if payment is involved or
                # "Subscribe to Group" functionality selected
                if get_setting('module', 'forms', 'form_submission_create_user') or \
                         self.form.custom_payment or self.form.recurring_payment or \
                         self.fields.filter(field__field_function__in=["GroupSubscription",
                                                                       "GroupSubscriptionAuto"],
                                            ).exclude(value='').exists():
                    first_name = self.get_first_name()
                    last_name = self.get_last_name()
                    if not (first_name and last_name):
                        full_name = self.get_full_name()
                        if full_name:
                            name_list = full_name.split(" ", 1)
                            first_name = name_list[0]
                            last_name = name_list[1] if len(
                                name_list) > 1 else ""

                    anonymous_creator = User(username=emailfield[:30],
                                             email=emailfield,
                                             first_name=first_name,
                                             last_name=last_name)
                    anonymous_creator.set_unusable_password()
                    anonymous_creator.is_active = False
                    anonymous_creator.save()

                    anonymous_profile = Profile(
                        user=anonymous_creator,
                        owner=anonymous_creator,
                        creator=anonymous_creator,
                        phone=self.get_phone_number(),
                        address=self.get_address(),
                        company=self.get_company(),
                        city=self.get_city(),
                        region=self.get_region(),
                        state=self.get_state(),
                        zipcode=self.get_zipcode(),
                        position_title=self.get_position_title(),
                        referral_source=self.get_referral_source(),
                        notes=self.get_notes(),
                    )
                    anonymous_profile.save()

        return anonymous_creator
Exemplo n.º 3
0
 def process_request(self, request):
     from tendenci.apps.profiles.models import Profile
     if request.user.is_anonymous():
         request.user.profile = Profile(status=False, status_detail="inactive", user=User(is_staff=False, is_superuser=False, is_active=False))
     else:
         try:
             profile = request.user.profile
         except Profile.DoesNotExist:
             profile = Profile.objects.create_profile(user=request.user)
Exemplo n.º 4
0
    def forwards(self, orm):
        from django.contrib.auth.models import User
        from tendenci.apps.profiles.models import Profile
        from tendenci.apps.subscribers.models import GroupSubscription, SubscriberData
        from tendenci.apps.user_groups.models import GroupMembership

        phone_labels = ["Phone", "phone", "Phone Number", "phone number", "Home Phone", "Cell Phone"]
        for sub in GroupSubscription.objects.all():
            sub_email = sub.email

            if sub_email:
                if sub.subscriber and sub.subscriber.creator:
                    user = sub.subscriber.creator
                else:
                    if User.objects.filter(email=sub_email).exists():
                        user = User.objects.filter(email=sub_email).order_by('last_login')[0]
                    elif User.objects.filter(username=sub_email).exists():
                        user = User.objects.filter(username=sub_email).order_by('last_login')[0]
                    else:
                        user = User(username=sub_email[:30], email=sub_email, is_active=False)
                        if SubscriberData.objects.filter(field_label="First Name", subscription=sub):
                            user.first_name = SubscriberData.objects.filter(field_label="First Name", subscription=sub)[0].value
                        if SubscriberData.objects.filter(field_label="Last Name", subscription=sub):
                            user.last_name = SubscriberData.objects.filter(field_label="Last Name", subscription=sub)[0].value
                        user.save()
                        profile = Profile(user=user, owner=user, creator=user)
                        if SubscriberData.objects.filter(field_label__in=phone_labels, subscription=sub):
                            profile.phone = SubscriberData.objects.filter(field_label__in=phone_labels, subscription=sub)[0].value
                        profile.save()
                try:
                    group_membership = GroupMembership.objects.get(group=sub.group, member=user)
                except GroupMembership.DoesNotExist:
                    group_membership = GroupMembership(group=sub.group, member=user)
                    group_membership.creator_id = user.id
                    group_membership.creator_username = user.username
                    group_membership.role = 'subscriber'
                    group_membership.owner_id = user.id
                    group_membership.owner_username = user.username
                    group_membership.save()
    def save(self, *args, **kwargs):
        relief = super(ReliefAssessmentForm, self).save(commit=False)

        user, created = Profile.get_or_create_user(**{
            'email': self.cleaned_data.get('email'),
            'first_name': self.cleaned_data.get('first_name'),
            'last_name': self.cleaned_data.get('last_name'),
        })

        if created:
            profile = user.profile
            profile.initials = self.cleaned_data.get('initials')
            profile.phone = self.cleaned_data.get('phone')
            profile.phone2 = self.cleaned_data.get('phone2')
            profile.email2 = self.cleaned_data.get('email2')
            profile.dob = self.cleaned_data.get('dob')
            profile.company = self.cleaned_data.get('company')
            profile.position_title = self.cleaned_data.get('position_title')
            profile.education = self.cleaned_data.get('education')
            profile.save()

        relief.user = user
        relief.save()
Exemplo n.º 6
0
    def save(self, *args, **kwargs):
        relief = super(ReliefAssessmentForm, self).save(commit=False)

        user, created = Profile.get_or_create_user(**{
            'email': self.cleaned_data.get('email'),
            'first_name': self.cleaned_data.get('first_name'),
            'last_name': self.cleaned_data.get('last_name'),
        })

        if created:
            profile = user.profile
            profile.initials = self.cleaned_data.get('initials')
            profile.phone = self.cleaned_data.get('phone')
            profile.phone2 = self.cleaned_data.get('phone2')
            profile.email2 = self.cleaned_data.get('email2')
            profile.dob = self.cleaned_data.get('dob')
            profile.company = self.cleaned_data.get('company')
            profile.position_title = self.cleaned_data.get('position_title')
            profile.education = self.cleaned_data.get('education')
            profile.save()

        relief.user = user
        relief.save()
Exemplo n.º 7
0
 def save(self, profile_callback=None, event=None):
     # 
     #new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],
     #                                                            password=self.cleaned_data['password1'],
     # create inactive user                                                           email=self.cleaned_data['email'])
     new_user = User.objects.create_user(self.cleaned_data['username'],
                                         self.cleaned_data['email'],
                                         self.cleaned_data['password1'])
     
     new_user.first_name = self.cleaned_data['first_name']
     new_user.last_name = self.cleaned_data['last_name']
     new_user.is_active = False
     new_user.save()
     # create registration profile
     registration_profile = RegistrationProfile.objects.create_profile(new_user)
     send_registration_activation_email(new_user, registration_profile, event=event)
     
     new_profile = Profile(user=new_user, 
                           company=self.cleaned_data['company'],
                           phone=self.cleaned_data['phone'],
                           address=self.cleaned_data['address'],
                           city=self.cleaned_data['city'],
                           state=self.cleaned_data['state'],
                           country=self.cleaned_data['country'],
                           zipcode=self.cleaned_data['zipcode'],
                           )
     user_hide_default = get_setting('module', 'users', 'usershidedefault')
     if user_hide_default:
         new_profile.hide_in_search = 1
         new_profile.hide_address = 1
         new_profile.hide_email = 1
         new_profile.hide_phone = 1 
       
     new_profile.creator = new_user
     new_profile.creator_username = new_user.username
     new_profile.owner = new_user
     new_profile.owner_username = new_user.username
     new_profile.save()
                 
     return new_user
Exemplo n.º 8
0
    def save(self, profile_callback=None, event=None):
        #
        #new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],
        #                                                            password=self.cleaned_data['password1'],
        # create inactive user                                                           email=self.cleaned_data['email'])
        new_user = User.objects.create_user(self.cleaned_data['username'],
                                            self.cleaned_data['email'],
                                            self.cleaned_data['password1'])

        new_user.first_name = self.cleaned_data['first_name']
        new_user.last_name = self.cleaned_data['last_name']
        new_user.is_active = False
        new_user.save()
        # create registration profile
        registration_profile = RegistrationProfile.objects.create_profile(
            new_user)
        send_registration_activation_email(new_user,
                                           registration_profile,
                                           event=event)

        new_profile = Profile(
            user=new_user,
            company=self.cleaned_data['company'],
            phone=self.cleaned_data['phone'],
            address=self.cleaned_data['address'],
            city=self.cleaned_data['city'],
            state=self.cleaned_data['state'],
            country=self.cleaned_data['country'],
            zipcode=self.cleaned_data['zipcode'],
        )
        user_hide_default = get_setting('module', 'users', 'usershidedefault')
        if user_hide_default:
            new_profile.hide_in_search = 1
            new_profile.hide_address = 1
            new_profile.hide_email = 1
            new_profile.hide_phone = 1

        new_profile.creator = new_user
        new_profile.creator_username = new_user.username
        new_profile.owner = new_user
        new_profile.owner_username = new_user.username
        new_profile.save()
        sf_id = create_salesforce_contact(new_profile)

        return new_user
Exemplo n.º 9
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)
    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():
            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()
            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()
            
            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()
                    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)
                    # log an event for invoice add

                    EventLog.objects.log(instance=form)

                    # redirect to billing form
                    return redirect('form_entry_payment', invoice.id, invoice.guid)

            # default redirect
            if form.completion_url:
                return HttpResponseRedirect(form.completion_url)
            return redirect("form_sent", form.slug)
    # set form's template to default if no template or template doesn't exist
    if not form.template or not template_exists(form.template):
        form.template = "default.html"
    context = {
        "form": form,
        "form_for_form": form_for_form,
        'form_template': form.template,
    }
    return render_to_response(template, context, RequestContext(request))
Exemplo n.º 10
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 and request.user.is_anonymous():
        response = redirect('auth_login')
        response['Location'] += '?next=%s' % form.get_absolute_url()
        return response

    form_for_form = FormForForm(form, request.user, request.POST or None, request.FILES or 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():
            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()

            # 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
            sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
            email_to = form_for_form.email_to()
            if email_to and form.send_email and form.email_text:
                # Send message to the person who submitted the form.
                msg = EmailMessage(subject, submitter_body, sender, [email_to], headers=email_headers)
                msg.content_subtype = 'html'

                try:
                    msg.send(fail_silently=True)
                except:
                    pass

            # 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()]
            if email_copies:
                # Send message to the email addresses listed in the copies.
                msg = EmailMessage(subject, admin_body, sender, email_copies, headers=email_headers)
                msg.content_subtype = 'html'
                for f in form_for_form.files.values():
                    try:
                        f.open()
                        f.seek(0)
                        msg.attach(f.name, f.read())
                        f.close()
                    except Exception:
                        pass

                try:
                    msg.send(fail_silently=True)
                except:
                    pass

            # Email copies to recipient list indicated in the form
            email_recipients = entry.get_function_email_recipients()
            if email_recipients:
                # Send message to the email addresses selected in the form.
                msg = EmailMessage(subject, admin_body, sender, email_recipients, headers=email_headers)
                msg.content_subtype = 'html'
                for f in form_for_form.files.values():
                    f.seek(0)
                    msg.attach(f.name, f.read())
                msg.send()

            # 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:
                    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=request.user,
                             description=entry.pricing.label,
                             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=request.user,
                             creator_username=request.user.username,
                             owner=request.user,
                             owner_username=request.user.username,
                         )
                    rp.save()
                    rp.add_customer_profile()

                    # redirect to recurring payments
                    messages.add_message(request, messages.SUCCESS, 'Successful transaction.')
                    return redirect('recurring_payment.my_accounts')
                else:
                    # create the invoice
                    invoice = make_invoice_for_entry(entry, custom_price=price)
                    # log an event for invoice add

                    EventLog.objects.log(instance=form)

                    # redirect to billing form
                    return redirect('form_entry_payment', invoice.id, invoice.guid)

            # default redirect
            if form.completion_url:
                return redirect(form.completion_url)
            return redirect("form_sent", form.slug)
    # set form's template to default if no template or template doesn't exist
    if not form.template or not template_exists(form.template):
        form.template = "default.html"
    context = {
        "form": form,
        "form_for_form": form_for_form,
        'form_template': form.template,
    }
    return render_to_response(template, context, RequestContext(request))
Exemplo n.º 11
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)
    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():
            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()
            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()

            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()
                    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)
                    # log an event for invoice add

                    EventLog.objects.log(instance=form)

                    # redirect to billing form
                    return redirect('form_entry_payment', invoice.id,
                                    invoice.guid)

            # default redirect
            if form.completion_url:
                return HttpResponseRedirect(form.completion_url)
            return redirect("form_sent", form.slug)
    # set form's template to default if no template or template doesn't exist
    if not form.template or not template_exists(form.template):
        form.template = "default.html"
    context = {
        "form": form,
        "form_for_form": form_for_form,
        'form_template': form.template,
    }
    return render_to_response(template, context, RequestContext(request))
Exemplo n.º 12
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 and request.user.is_anonymous():
        response = redirect('auth_login')
        response['Location'] += '?next=%s' % form.get_absolute_url()
        return response

    form_for_form = FormForForm(form, request.user, request.POST or None, request.FILES or 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():
            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()

            # 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
            sender = get_setting('site', 'global', 'siteemailnoreplyaddress')
            email_to = form_for_form.email_to()
            if email_to and form.send_email and form.email_text:
                # Send message to the person who submitted the form.
                msg = EmailMessage(subject, submitter_body, sender, [email_to], headers=email_headers)
                msg.content_subtype = 'html'
                msg.send()

            # 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.update({'Reply-To':email_from})
            email_copies = [e.strip() for e in form.email_copies.split(",")
                if e.strip()]
            if email_copies:
                # Send message to the email addresses listed in the copies.
                msg = EmailMessage(subject, admin_body, sender, email_copies, headers=email_headers)
                msg.content_subtype = 'html'
                for f in form_for_form.files.values():
                    f.seek(0)
                    msg.attach(f.name, f.read())
                msg.send()

            # 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:
                    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=request.user,
                             description=entry.pricing.label,
                             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=request.user,
                             creator_username=request.user.username,
                             owner=request.user,
                             owner_username=request.user.username,
                         )
                    rp.save()
                    rp.add_customer_profile()

                    # redirect to recurring payments
                    messages.add_message(request, messages.SUCCESS, 'Successful transaction.')
                    return redirect('recurring_payment.my_accounts')
                else:
                    # create the invoice
                    invoice = make_invoice_for_entry(entry, custom_price=price)
                    # log an event for invoice add

                    EventLog.objects.log(instance=form)

                    # redirect to billing form
                    return redirect('form_entry_payment', invoice.id, invoice.guid)

            # default redirect
            if form.completion_url:
                return redirect(form.completion_url)
            return redirect("form_sent", form.slug)
    # set form's template to default if no template or template doesn't exist
    if not form.template or not template_exists(form.template):
        form.template = "default.html"
    context = {
        "form": form,
        "form_for_form": form_for_form,
        'form_template': form.template,
    }
    return render_to_response(template, context, RequestContext(request))
Exemplo n.º 13
0
def index(request, form_class=SubmitContactForm, template_name="form.html"):

    if request.method == "GET":
        # event-log view
        EventLog.objects.log(instance=Contact(), action='viewed')

    if request.method == "POST":
        event_log_dict = {}
        form = form_class(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            first_name = form.cleaned_data.get('first_name')
            last_name = form.cleaned_data.get('last_name')

            if listed_in_email_block(email):
                # listed in the email blocks - it's a spam email we want to block
                # log the spam
                EventLog.objects.log()

                # redirect normally so they don't suspect
                return HttpResponseRedirect(reverse('form.confirmation'))

            address = form.cleaned_data.get('address')
            city = form.cleaned_data.get('city')
            state = form.cleaned_data.get('state')
            zipcode = form.cleaned_data.get('zipcode')
            country = form.cleaned_data.get('country')
            phone = form.cleaned_data.get('phone')
            url = form.cleaned_data.get('url')
            message = form.cleaned_data.get('message')

            exists = User.objects.filter(
                first_name__iexact=first_name,
                last_name__iexact=last_name,
                email__iexact=email,
            ).exists()

            if request.user.is_anonymous():
                username = first_name.replace(' ', '')
                if last_name:
                    username = username + '_' + last_name.replace(' ', '')
                username = username.lower()
                try:
                    User.objects.get(username=username)
                    x = User.objects.filter(first_name=first_name).count()
                    username = username + '_' + unicode(x)
                except User.DoesNotExist:
                    pass

                contact_user = User(
                    username=username,
                    email=email,
                    first_name=first_name,
                    last_name=last_name,
                )

                contact_user.is_active = False
                contact_user.save()
                profile = Profile(user=contact_user, owner=contact_user, creator=User.objects.get(pk=1),
                                  address=address, country=country, city=city, state=state,
                                  url=url, phone=phone, zipcode=zipcode)
                profile.save()
                sf_id = create_salesforce_contact(profile)

                # if exists:
                #     event_log_dict['description'] = 'logged-out submission as existing user'
                # else:
                event_log_dict['description'] = 'logged-out submission as new user'

            else:  # logged in user
                self_submit = all([
                    request.user.first_name.lower().strip() == first_name.lower().strip(),
                    request.user.last_name.lower().strip() == last_name.lower().strip(),
                    request.user.email.lower().strip() == email.lower().strip(),
                ])

                contact_user = request.user

                if exists:
                    if self_submit:
                        event_log_dict['description'] = 'logged-in submission as self'
                    else:
                        event_log_dict['description'] = 'logged-in submission as existing user'
                else:
                    event_log_dict['description'] = 'logged-in submission as non-existing user'

            contact_kwargs = {
                'first_name': first_name,
                'last_name': last_name,
                'message': message,
                'user': contact_user,
            }

            contact = Contact(**contact_kwargs)
            contact.allow_anonymous_view = False
            contact.save()

            if address or city or state or zipcode or country:
                address_kwargs = {
                    'address': address,
                    'city': city,
                    'state': state,
                    'zipcode': zipcode,
                    'country': country,
                }
                obj_address = Address(**address_kwargs)
                obj_address.save()  # saves object
                contact.addresses.add(obj_address)  # saves relationship

            if phone:
                obj_phone = Phone(number=phone)
                obj_phone.save()  # saves object
                contact.phones.add(obj_phone)  # saves relationship

            if email:
                obj_email = Email(email=email)
                obj_email.save()  # saves object
                contact.emails.add(obj_email)  # saves relationship

            if url:
                obj_url = URL(url=url)
                obj_url.save()  # saves object
                contact.urls.add(obj_url)  # saves relationship

            site_name = get_setting('site', 'global', 'sitedisplayname')
            message_link = get_setting('site', 'global', 'siteurl')

            # send notification to administrators
            # get admin notice recipients
            recipients = get_notice_recipients('module', 'contacts', 'contactrecipients')
            if recipients:
                if notification:
                    extra_context = {
                    'reply_to': email,
                    'contact': contact,
                    'first_name': first_name,
                    'last_name': last_name,
                    'address': address,
                    'city': city,
                    'state': state,
                    'zipcode': zipcode,
                    'country': country,
                    'phone': phone,
                    'email': email,
                    'url': url,
                    'message': message,
                    'message_link': message_link,
                    'site_name': site_name,
                    }
                    notification.send_emails(recipients, 'contact_submitted', extra_context)

            # event-log (logged in)
            event_log = EventLog.objects.log(
                instance=contact,
                user=contact_user,
                action='submitted',
                **event_log_dict
            )

            event_log.url = contact.get_absolute_url()
            event_log.save()

            return HttpResponseRedirect(reverse('form.confirmation'))
        else:
            return render_to_response(template_name, {'form': form},
                context_instance=RequestContext(request))

    form = form_class()
    return render_to_response(template_name, {'form': form},
        context_instance=RequestContext(request))
Exemplo n.º 14
0
    def handle(self, *args, **options):
        """
        Converts subscribers to users, maintains group memberships, removes subscribers.
        """
        from tendenci.apps.subscribers.models import SubscriberData, GroupSubscription
        from tendenci.apps.user_groups.models import GroupMembership
        from tendenci.apps.profiles.models import Profile

        if GroupSubscription.objects.exists():
            for sub in GroupSubscription.objects.all():
                sub_email = sub.email

                if sub_email:        
                    if not User.objects.filter(email=sub_email).exists():
                        print "Creating new user for group subscription %s." % sub.id
                        if len(sub_email) <= 30:
                            username = sub_email
                        else:
                            username = sub_email.split("@")[0]
            
                        user = User(
                            username = username,
                            email = sub_email,
                            is_active = False
                        )
                        
                        if sub.subscriber_id:
                            user.first_name = sub.subscriber.get_first_name() 
                            user.last_name = sub.subscriber.get_last_name()
                            phone = sub.subscriber.get_phone_number()
                        else:
                            if SubscriberData.objects.filter(field_label="First Name").filter(subscription_id=sub.id):
                                user.first_name = SubscriberData.objects.filter(field_label="First Name").filter(subscription_id=sub.id)[0].value
                            if SubscriberData.objects.filter(field_label="Last Name").filter(subscription_id=sub.id):
                                user.last_name = SubscriberData.objects.filter(field_label="Last Name").filter(subscription_id=sub.id)[0].value
                            if SubscriberData.objects.filter(field_label__in=["Phone", "phone", "Phone Number", "phone number", "Home Phone", "Cell Phone"]).filter(subscription_id=sub.id):
                                phone = SubscriberData.objects.filter(field_label__in=["Phone", "phone", "Phone Number", "phone number", "Home Phone", "Cell Phone"]).filter(subscription_id=sub.id)[0].value
                            else:
                                phone = ''
                        
                        user.save()
                        
                        profile = Profile(
                            user = user,
                            creator = user,
                            creator_username = user.username,
                            owner = user,
                            owner_username = user.username,
                            phone = phone,
                            allow_anonymous_view = False
                        )
                        
                        profile.save()
            
                    else:
                        print "User with matching email found for group subscription %s."  % sub.id
            
                    user = User.objects.filter(email=sub_email).order_by('last_login')[0]

                    if not GroupMembership.objects.filter(group_id=sub.group_id).filter(member_id=user.id).exists():
                        print "Creating a group membership for user %s and group %s." % (user.id, sub.group_id)
                        gm = GroupMembership(
                            group_id = sub.group_id,
                            member_id = user.id,
                            role = "subscriber"
                        )
                        gm.save()
                    else:
                        print "Group membership already exists for user %s and group %s." % (user.id, sub.group_id)

                    print "Deleting group subscription %s." % sub.id
                    sub.delete()
                else:
                    print "No email field found for subscriber %s." % sub.id
        else:
            print "No group subscriptions exist."
Exemplo n.º 15
0
    def handle(self, *args, **options):
        """
        Converts subscribers to users, maintains group memberships, removes subscribers.
        """
        from tendenci.apps.subscribers.models import SubscriberData, GroupSubscription
        from tendenci.apps.user_groups.models import GroupMembership
        from tendenci.apps.profiles.models import Profile

        if GroupSubscription.objects.exists():
            for sub in GroupSubscription.objects.all():
                sub_email = sub.email

                if sub_email:
                    if not User.objects.filter(email=sub_email).exists():
                        print "Creating new user for group subscription %s." % sub.id
                        if len(sub_email) <= 30:
                            username = sub_email
                        else:
                            username = sub_email.split("@")[0]

                        user = User(username=username,
                                    email=sub_email,
                                    is_active=False)

                        if sub.subscriber_id:
                            user.first_name = sub.subscriber.get_first_name()
                            user.last_name = sub.subscriber.get_last_name()
                            phone = sub.subscriber.get_phone_number()
                        else:
                            if SubscriberData.objects.filter(
                                    field_label="First Name").filter(
                                        subscription_id=sub.id):
                                user.first_name = SubscriberData.objects.filter(
                                    field_label="First Name").filter(
                                        subscription_id=sub.id)[0].value
                            if SubscriberData.objects.filter(
                                    field_label="Last Name").filter(
                                        subscription_id=sub.id):
                                user.last_name = SubscriberData.objects.filter(
                                    field_label="Last Name").filter(
                                        subscription_id=sub.id)[0].value
                            if SubscriberData.objects.filter(field_label__in=[
                                    "Phone", "phone", "Phone Number",
                                    "phone number", "Home Phone", "Cell Phone"
                            ]).filter(subscription_id=sub.id):
                                phone = SubscriberData.objects.filter(
                                    field_label__in=[
                                        "Phone", "phone", "Phone Number",
                                        "phone number", "Home Phone",
                                        "Cell Phone"
                                    ]).filter(subscription_id=sub.id)[0].value
                            else:
                                phone = ''

                        user.save()

                        profile = Profile(user=user,
                                          creator=user,
                                          creator_username=user.username,
                                          owner=user,
                                          owner_username=user.username,
                                          phone=phone,
                                          allow_anonymous_view=False)

                        profile.save()

                    else:
                        print "User with matching email found for group subscription %s." % sub.id

                    user = User.objects.filter(
                        email=sub_email).order_by('last_login')[0]

                    if not GroupMembership.objects.filter(
                            group_id=sub.group_id).filter(
                                member_id=user.id).exists():
                        print "Creating a group membership for user %s and group %s." % (
                            user.id, sub.group_id)
                        gm = GroupMembership(group_id=sub.group_id,
                                             member_id=user.id,
                                             role="subscriber")
                        gm.save()
                    else:
                        print "Group membership already exists for user %s and group %s." % (
                            user.id, sub.group_id)

                    print "Deleting group subscription %s." % sub.id
                    sub.delete()
                else:
                    print "No email field found for subscriber %s." % sub.id
        else:
            print "No group subscriptions exist."
Exemplo n.º 16
0
def index(request, form_class=SubmitContactForm, template_name="form.html"):

    if request.method == "POST":
        form = form_class(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            first_name = form.cleaned_data.get('first_name')
            last_name = form.cleaned_data.get('last_name')

            if listed_in_email_block(email):
                # listed in the email blocks - it's a spam email we want to block
                # log the spam
                EventLog.objects.log()

                # redirect normally so they don't suspect
                return HttpResponseRedirect(reverse('form.confirmation'))

            address = form.cleaned_data.get('address')
            city = form.cleaned_data.get('city')
            state = form.cleaned_data.get('state')
            zipcode = form.cleaned_data.get('zipcode')
            country = form.cleaned_data.get('country')
            phone = form.cleaned_data.get('phone')
            url = form.cleaned_data.get('url')
            message = form.cleaned_data.get('message')

            if request.user.is_anonymous():
                username = first_name.replace(' ', '')
                if last_name:
                    username = username + '_' + last_name.replace(' ', '')
                username = username.lower()
                try:
                    User.objects.get(username=username)
                    x = User.objects.filter(first_name=first_name).count()
                    username = username + '_' + unicode(x)
                except User.DoesNotExist:
                    pass

                contact_user = User(
                    username=username,
                    email=email,
                    first_name=first_name,
                    last_name=last_name,
                )

                contact_user.is_active = False
                contact_user.save()
                profile = Profile(user=contact_user, owner=contact_user, creator=User.objects.get(pk=1),
                                  address=address, country=country, city=city, state=state,
                                  url=url, phone=phone, zipcode=zipcode)
                profile.save()
            else:
                contact_user = request.user

            contact_kwargs = {
                'first_name': first_name,
                'last_name': last_name,
                'message': message,
                'user': contact_user,
            }

            contact = Contact(**contact_kwargs)
            contact.creator_id = 1  # TODO: decide if we should use tendenci base model
            contact.owner_id = 1  # TODO: decide if we should use tendenci base model
            contact.allow_anonymous_view = False
            contact.save()

            if address or city or state or zipcode or country:
                address_kwargs = {
                    'address': address,
                    'city': city,
                    'state': state,
                    'zipcode': zipcode,
                    'country': country,
                }
                obj_address = Address(**address_kwargs)
                obj_address.save()  # saves object
                contact.addresses.add(obj_address)  # saves relationship

            if phone:
                obj_phone = Phone(number=phone)
                obj_phone.save() # saves object
                contact.phones.add(obj_phone) # saves relationship

            if email:
                obj_email = Email(email=email)
                obj_email.save() # saves object
                contact.emails.add(obj_email) # saves relationship

            if url:
                obj_url = URL(url=url)
                obj_url.save() # saves object
                contact.urls.add(obj_url) # saves relationship

            site_name = get_setting('site', 'global', 'sitedisplayname')
            message_link = get_setting('site', 'global', 'siteurl')

            # send notification to administrators
            # get admin notice recipients
            recipients = get_notice_recipients('module', 'contacts', 'contactrecipients')
            if recipients:
                if notification:
                    extra_context = {
                    'reply_to': email,
                    'contact':contact,
                    'first_name':first_name,
                    'last_name':last_name,
                    'address':address,
                    'city':city,
                    'state':state,
                    'zipcode':zipcode,
                    'country':country,
                    'phone':phone,
                    'email':email,
                    'url':url,
                    'message':message,
                    'message_link':message_link,
                    'site_name':site_name,
                    }
                    notification.send_emails(recipients,'contact_submitted', extra_context)

            try: user = User.objects.filter(email=email)[0]
            except: user = None

            EventLog.objects.log(instance=contact)

            return HttpResponseRedirect(reverse('form.confirmation'))
        else:
            return render_to_response(template_name, {'form': form}, 
                context_instance=RequestContext(request))

    form = form_class()
    return render_to_response(template_name, {'form': form}, 
        context_instance=RequestContext(request))
Exemplo n.º 17
0
def index(request, form_class=SubmitContactForm, template_name="form.html"):

    if request.method == "GET":
        # event-log view
        EventLog.objects.log(instance=Contact(), action='viewed')

    if request.method == "POST":
        event_log_dict = {}
        form = form_class(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            first_name = form.cleaned_data.get('first_name')
            last_name = form.cleaned_data.get('last_name')

            if listed_in_email_block(email):
                # listed in the email blocks - it's a spam email we want to block
                # log the spam
                EventLog.objects.log()

                # redirect normally so they don't suspect
                return HttpResponseRedirect(reverse('form.confirmation'))

            address = form.cleaned_data.get('address')
            city = form.cleaned_data.get('city')
            state = form.cleaned_data.get('state')
            zipcode = form.cleaned_data.get('zipcode')
            country = form.cleaned_data.get('country')
            phone = form.cleaned_data.get('phone')
            url = form.cleaned_data.get('url')
            message = form.cleaned_data.get('message')

            exists = User.objects.filter(
                first_name__iexact=first_name,
                last_name__iexact=last_name,
                email__iexact=email,
            ).exists()

            if request.user.is_anonymous():
                username = first_name.replace(' ', '')
                if last_name:
                    username = username + '_' + last_name.replace(' ', '')
                username = username.lower()
                try:
                    User.objects.get(username=username)
                    x = User.objects.filter(first_name=first_name).count()
                    username = username + '_' + unicode(x)
                except User.DoesNotExist:
                    pass

                contact_user = User(
                    username=username,
                    email=email,
                    first_name=first_name,
                    last_name=last_name,
                )

                contact_user.is_active = False
                contact_user.save()
                profile = Profile(user=contact_user,
                                  owner=contact_user,
                                  creator=User.objects.get(pk=1),
                                  address=address,
                                  country=country,
                                  city=city,
                                  state=state,
                                  url=url,
                                  phone=phone,
                                  zipcode=zipcode)
                profile.save()
                sf_id = create_salesforce_contact(profile)

                # if exists:
                #     event_log_dict['description'] = 'logged-out submission as existing user'
                # else:
                event_log_dict[
                    'description'] = 'logged-out submission as new user'

            else:  # logged in user
                self_submit = all([
                    request.user.first_name.lower().strip() ==
                    first_name.lower().strip(),
                    request.user.last_name.lower().strip() ==
                    last_name.lower().strip(),
                    request.user.email.lower().strip() ==
                    email.lower().strip(),
                ])

                contact_user = request.user

                if exists:
                    if self_submit:
                        event_log_dict[
                            'description'] = 'logged-in submission as self'
                    else:
                        event_log_dict[
                            'description'] = 'logged-in submission as existing user'
                else:
                    event_log_dict[
                        'description'] = 'logged-in submission as non-existing user'

            contact_kwargs = {
                'first_name': first_name,
                'last_name': last_name,
                'message': message,
                'user': contact_user,
            }

            contact = Contact(**contact_kwargs)
            contact.allow_anonymous_view = False
            contact.save()

            if address or city or state or zipcode or country:
                address_kwargs = {
                    'address': address,
                    'city': city,
                    'state': state,
                    'zipcode': zipcode,
                    'country': country,
                }
                obj_address = Address(**address_kwargs)
                obj_address.save()  # saves object
                contact.addresses.add(obj_address)  # saves relationship

            if phone:
                obj_phone = Phone(number=phone)
                obj_phone.save()  # saves object
                contact.phones.add(obj_phone)  # saves relationship

            if email:
                obj_email = Email(email=email)
                obj_email.save()  # saves object
                contact.emails.add(obj_email)  # saves relationship

            if url:
                obj_url = URL(url=url)
                obj_url.save()  # saves object
                contact.urls.add(obj_url)  # saves relationship

            site_name = get_setting('site', 'global', 'sitedisplayname')
            message_link = get_setting('site', 'global', 'siteurl')

            # send notification to administrators
            # get admin notice recipients
            recipients = get_notice_recipients('module', 'contacts',
                                               'contactrecipients')
            if recipients:
                if notification:
                    extra_context = {
                        'reply_to': email,
                        'contact': contact,
                        'first_name': first_name,
                        'last_name': last_name,
                        'address': address,
                        'city': city,
                        'state': state,
                        'zipcode': zipcode,
                        'country': country,
                        'phone': phone,
                        'email': email,
                        'url': url,
                        'message': message,
                        'message_link': message_link,
                        'site_name': site_name,
                    }
                    notification.send_emails(recipients, 'contact_submitted',
                                             extra_context)

            # event-log (logged in)
            event_log = EventLog.objects.log(instance=contact,
                                             user=contact_user,
                                             action='submitted',
                                             **event_log_dict)

            event_log.url = contact.get_absolute_url()
            event_log.save()

            return HttpResponseRedirect(reverse('form.confirmation'))
        else:
            return render_to_response(template_name, {'form': form},
                                      context_instance=RequestContext(request))

    form = form_class()
    return render_to_response(template_name, {'form': form},
                              context_instance=RequestContext(request))