Ejemplo n.º 1
0
def prepare_paypal_form(request, payment):
    amount = "%.2f" % payment.amount
    image_url = get_setting('site', 'global', 'merchantlogo')
    site_url = get_setting('site', 'global', 'siteurl')
    notify_url = '%s%s' % (site_url, reverse('paypal.ipn'))
    currency_code = get_setting('site', 'global', 'currency')
    if not currency_code:
        currency_code = 'USD'
    params = {
              'business': settings.PAYPAL_MERCHANT_LOGIN,
              'image_url': image_url,
              'amount': amount,
              'notify_url': notify_url,
              'currency_code': currency_code,
              'invoice': payment.id,
              'item_name': payment.description,
              'first_name': payment.first_name,
              'last_name': payment.last_name,
              'email': payment.email,
              'address1': payment.address,
              'address2': payment.address2,
              'city': payment.city,
              'state': payment.state,
              'country': payment.country,
              'zip': payment.zip,
              'night_phone_a': payment.phone,
        }
    form = PayPalPaymentForm(initial=params)
    form.fields['return'] = forms.CharField(max_length=100,
                            widget=forms.HiddenInput,
                            initial=payment.response_page)

    return form
Ejemplo n.º 2
0
    def get_gravatar_url(self, size):
        # Use old avatar, if exists, as the default
        default = ''
        if get_setting('module', 'users', 'useoldavatarasdefault'):
            c = connection.cursor()
            try:
                c.execute("select avatar from avatar_avatar where \"primary\"='t' and user_id=%d" % self.user.id)
                row = c.fetchone()
                if row and os.path.exists(os.path.join(settings.MEDIA_ROOT, row[0])):
                    default = '%s%s%s' %  (get_setting('site', 'global', 'siteurl'),
                                       settings.MEDIA_URL,
                                       row[0])
            except ProgrammingError:
                pass

            c.close()

        if not default:
            default = '%s%s%s' %  (get_setting('site', 'global', 'siteurl'),
                                   getattr(settings, 'STATIC_URL', ''),
                                   settings.GAVATAR_DEFAULT_URL)

        gravatar_url = "//www.gravatar.com/avatar/" + self.getMD5() + "?"
        gravatar_url += urllib.urlencode({'d':default, 's':str(size)})
        return gravatar_url
Ejemplo n.º 3
0
 def __init__(self, user, *args, **kwargs):
     super(MakePaymentForm, self).__init__(*args, **kwargs)
     self.initial['country'] = get_setting('site', 'global', 'defaultcountry')
     self.fields['reference_number'].label = get_setting('module',
                                                         'make_payment',
                                                         'referencenumberlabel') or _('Reference #')
     # populate the user fields
     if user and user.id:
         if 'captcha' in self.fields:
             self.fields.pop('captcha')
         self.fields['first_name'].initial = user.first_name
         self.fields['last_name'].initial = user.last_name
         self.fields['email'].initial = user.email
         try:
             profile = user.profile
             if profile:
                 self.fields['company'].initial = profile.company
                 self.fields['address'].initial = profile.address
                 self.fields['address2'].initial = profile.address2
                 self.fields['city'].initial = profile.city
                 self.fields['state'].initial = profile.state
                 self.fields['zip_code'].initial = profile.zipcode
                 self.fields['country'].initial = profile.country
                 self.fields['phone'].initial = profile.phone
         except:
             pass
Ejemplo n.º 4
0
    def save(self, *args, **kwargs):
        if not self.id:
            self.guid = str(uuid.uuid1())

        # match allow_anonymous_view with opposite of hide_in_search
        if self.hide_in_search:
            self.allow_anonymous_view = False
        else:
            self.allow_anonymous_view = get_setting('module', 'users', 'allowanonymoususersearchuser')
            
        self.allow_user_view =  get_setting('module', 'users', 'allowusersearch')
        if get_setting('module', 'memberships', 'memberprotection') == 'private':
            self.allow_member_view = False
        else:
            self.allow_member_view = True
        

        super(Profile, self).save(*args, **kwargs)

        try:
            from tendenci.apps.campaign_monitor.utils import update_subscription
            if hasattr(self, 'old_email') and getattr(self, 'old_email') != self.user.email:
                update_subscription(self, self.old_email)
                del self.old_email
        except ImportError:
            pass
Ejemplo n.º 5
0
    def __init__(self, *args, **kwargs):
        if 'user' in kwargs:
            self.user = kwargs.pop('user', None)
        else:
            self.user = None
        super(DonationForm, self).__init__(*args, **kwargs)
        # populate the user fields
        if self.user and self.user.id:
            self.fields['first_name'].initial = self.user.first_name
            self.fields['last_name'].initial = self.user.last_name
            self.fields['email'].initial = self.user.email
            try:
                profile = self.user.profile
                if profile:
                    self.fields['company'].initial = profile.company
                    self.fields['address'].initial = profile.address
                    self.fields['address2'].initial = profile.address2
                    self.fields['city'].initial = profile.city
                    self.fields['state'].initial = profile.state
                    self.fields['zip_code'].initial = profile.zipcode
                    self.fields['country'].initial = profile.country
                    self.fields['phone'].initial = profile.phone
            except:
                pass

        self.fields['payment_method'].widget = forms.RadioSelect(choices=get_payment_method_choices(self.user))
        allocation_str = get_setting('module', 'donations', 'donationsallocations')
        if allocation_str:
            self.fields['allocation'].choices = get_allocation_choices(self.user, allocation_str)
        else:
            del self.fields['allocation']
        preset_amount_str = (get_setting('module', 'donations', 'donationspresetamounts')).strip('')
        if preset_amount_str:
            self.fields['donation_amount'] = forms.ChoiceField(choices=get_preset_amount_choices(preset_amount_str))
Ejemplo n.º 6
0
    def get_keywords(self):
        object = self.object

        ### Assign variables -----------------------
        dynamic_keywords = generate_meta_keywords(object.body)
        geo_location = get_setting('site','global','sitegeographiclocation')
        site_name = get_setting('site','global','sitedisplayname')


        ### Build string -----------------------
        value = ''

        list = [
            'Photos',
            geo_location,
            site_name,
        ]

        # remove blank items
        for item in list:
            if not item.strip():
                list.remove(item)

        value = '%s %s, %s' % (value, ', '.join(list), dynamic_keywords)


        return value
Ejemplo n.º 7
0
    def get_description(self):
        object = self.object

        ### Assign variables -----------------------
        site_name = get_setting('site','global','sitedisplayname')
        geo_location = get_setting('site','global','sitegeographiclocation')

        if object.description:
            content = object.description

        content = strip_tags(content) #strips HTML tags
        content = unescape_entities(content)
        content = content.replace("\n","").replace("\r","")
        content = truncate_words(content, 50) # ~ about 250 chars

        ### Build string -----------------------
        value = object.name

        value = '%s : %s' % (value, content)

        value = '%s Photo Sets for %s, %s' % (
            value, site_name, geo_location)

        value = value.strip()

        return value
Ejemplo n.º 8
0
    def __init__(self, *args, **kwargs):
        super(ModelSearchForm, self).__init__(*args, **kwargs)

        # Check to see if users should be included in global search
        include_users = False

        if kwargs['user'].profile.is_superuser or get_setting('module', 'users', 'allowanonymoususersearchuser') \
        or (kwargs['user'].is_authenticated() and get_setting('module', 'users', 'allowusersearch')):
            include_users = True

        if include_users:
            for app in registered_apps:
                if app['verbose_name'].lower() == 'user':
                    registered_apps_models.append(app['model'])
                    registered_apps_names.append(app['model']._meta.model_name)
        else:
            for app in registered_apps:
                if app['verbose_name'].lower() == 'user':
                    try:
                        models_index = registered_apps_models.index(app['model'])
                        registered_apps_models.pop(models_index)
                        names_index = registered_apps_names.index(app['model']._meta.model_name)
                        registered_apps_names.pop(names_index)
                    except Exception as e:
                        pass

        self.models = registered_apps_models
        self.fields['models'] = forms.MultipleChoiceField(choices=model_choices(), required=False, label=_('Search In'), widget=forms.CheckboxSelectMultiple)
Ejemplo n.º 9
0
def get_theme():
    request = get_current_request()
    if request:
        theme = request.session.get('theme', get_setting('module', 'theme_editor', 'theme'))
    else:
        theme = get_setting('module', 'theme_editor', 'theme')
    return theme
Ejemplo n.º 10
0
def prepare_paypal_form(request, payment):
    amount = "%.2f" % payment.amount
    image_url = get_setting("site", "global", "MerchantLogo")
    site_url = get_setting("site", "global", "siteurl")
    notify_url = "%s/%s" % (site_url, reverse("paypal.ipn"))
    currency_code = get_setting("site", "global", "currency")
    if not currency_code:
        currency_code = "USD"
    params = {
        "business": settings.PAYPAL_MERCHANT_LOGIN,
        "image_url": image_url,
        "amount": amount,
        "notify_url": notify_url,
        "currency_code": currency_code,
        "invoice": payment.id,
        "item_name": payment.description,
        "first_name": payment.first_name,
        "last_name": payment.last_name,
        "email": payment.email,
        "address1": payment.address,
        "address2": payment.address2,
        "city": payment.city,
        "state": payment.state,
        "country": payment.country,
        "zip": payment.zip,
        "night_phone_a": payment.phone,
    }
    form = PayPalPaymentForm(initial=params)
    form.fields["return"] = forms.CharField(max_length=100, widget=forms.HiddenInput, initial=payment.response_page)

    return form
Ejemplo n.º 11
0
def send_registration_activation_email(user, registration_profile, **kwargs):
    """
        this function sends the activation email to the self registrant.
        modified based on the block in create_inactive_user in registration/models.py
    """
    from django.core.mail import send_mail
    from django.template.loader import render_to_string
    from django.conf import settings
    from tendenci.apps.site_settings.utils import get_setting

    event = kwargs.pop('event', None)
    event_url = None
    if event: event_url = event.get_absolute_url()

    next = kwargs.pop('next', '')

    site_url = get_setting('site', 'global', 'siteurl')
    subject = render_to_string('registration/activation_email_subject.txt',
                                       { 'site_url': site_url })

    # Email subject *must not* contain newlines
    subject = ''.join(subject.splitlines())
    message = render_to_string('registration/activation_email.txt',
                               { 'activation_key': registration_profile.activation_key,
                                 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                                 'event_url': event_url,
                                 'site_url': site_url,
                                 'next': next })

    from_email = get_setting('site', 'global', 'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL

    send_mail(subject, message, from_email, [user.email])
Ejemplo n.º 12
0
 def enabled(cls):
     """Return backend enabled status by checking Setting Model"""
     try:
         FACEBOOK_APP_ID = get_setting(scope='module', scope_category='users', name='facebook_app_id')
         FACEBOOK_API_SECRET = get_setting(scope='module', scope_category='users', name='facebook_api_secret')
     except Setting.DoesNotExist:
         return False
     return True
Ejemplo n.º 13
0
    def get_title(self):
        obj = self.object

        ### Assign variables -----------------------
        primary_keywords = get_setting('site', 'global', 'siteprimarykeywords')
        geo_location = get_setting('site', 'global', 'sitegeographiclocation')
        #site_name = get_setting('site', 'global', 'sitedisplayname')  # Not currently used
        category_set = obj.category_set
        category = category_set.get('category', '')
        subcategory = category_set.get('sub_category', '')

        contact_name = '%s %s' % (
            obj.first_name,
            obj.last_name
        )
        contact_name = contact_name.strip()

        ### Build string -----------------------
        values_list = []
        if obj.headline:
            values_list.append(obj.headline)

        if obj.headline and obj.release_dt:
            values_list.append('-')
        if obj.release_dt:
            values_list.append(obj.release_dt.strftime('%m-%d-%Y'))

        if primary_keywords:
            if values_list:
                values_list.append(':')
                values_list.append(primary_keywords)
        else:
            if category and subcategory:
                values_list.append('category')
                values_list.append(':')
                values_list.append('subcategory')
            elif category:
                values_list.append('category')

        if contact_name:
            values_list.append('contact: %s' % contact_name)

        if geo_location:
            values_list.append('in %s' % geo_location)
        # commenting out to avoid the duplicates - the site name
        # is included on base.html already.
#        if site_name:
#            if values_list:
#                values_list.append('|')
#            values_list.append(site_name)

        title = ' '.join(values_list)
        # truncate the meta title to 100 characters
        max_length = 100
        if len(title) > max_length:
            title = '%s...' % title[:(max_length - 3)]

        return title
Ejemplo n.º 14
0
    def clean_password1(self):
        password1 = self.cleaned_data.get('password1')
        password_regex = get_setting('module', 'users', 'password_requirements_regex')
        password_requirements = get_setting('module', 'users', 'password_text')
        if password_regex:
            if not re.match(password_regex, password1):
                raise forms.ValidationError(mark_safe(_("The password does not meet the requirements: %(p)s" % {'p': password_requirements })))

        return password1
Ejemplo n.º 15
0
    def get_title(self):
        obj = self.object

        ### Assign variables -----------------------
        primary_keywords = get_setting('site','global','siteprimarykeywords')
        geo_location = get_setting('site','global','sitegeographiclocation')
        site_name = get_setting('site','global','sitedisplayname')
        category = Category.objects.get_for_object(obj, 'category')
        subcategory = Category.objects.get_for_object(obj, 'subcategory')

        contact_name = '%s %s' % (
            obj.first_name,
            obj.last_name
        )
        contact_name = contact_name.strip()

        ### Build string -----------------------
        values_list = []
        if obj.headline:
            values_list.append(obj.headline)

        if obj.headline and obj.release_dt:
            values_list.append('-')
        if obj.release_dt:
            values_list.append(obj.release_dt.strftime('%m-%d-%Y'))

        if primary_keywords:
            if values_list:
                values_list.append(':')
                values_list.append(primary_keywords)
        else:
            if category and subcategory:
                values_list.append('category')
                values_list.append(':')
                values_list.append('subcategory')
            elif category:
                values_list.append('category')

        if site_name:
            if values_list:
                values_list.append('news for')
            values_list.append(site_name)

        if contact_name:
            values_list.append('contact: %s' % contact_name)

        if geo_location:
            values_list.append('in %s' % geo_location)

        title = ' '.join(values_list)
        # truncate the meta title to 100 characters
        max_length = 100
        if len(title) > max_length:
            title = '%s...' % title[:(max_length - 3)]

        return title
Ejemplo n.º 16
0
def robots_txt(request):
    options = ['base/robots_private.txt', 'base/robots_public.txt', 'robots.txt']
    template_name = "robots.txt"

    robots_setting = get_setting('site', 'global', 'robotstxt')
    if robots_setting in options:
        template_name = robots_setting

    site_url = get_setting('site', 'global', 'siteurl')
    return render_to_response(template_name, {'site_url': site_url}, context_instance=RequestContext(request), content_type="text/plain")
 def get_admin_emails():
     admin_emails = get_setting('module', 'corporate_memberships',
                                'corporatemembershiprecipients').strip()
     if admin_emails:
         admin_emails = admin_emails.split(',')
     if not admin_emails:
         admin_emails = (get_setting('site', 'global',
                                     'admincontactemail'
                                     ).strip()).split(',')
     return admin_emails
Ejemplo n.º 18
0
    def get_title(self):
        object = self.object

        ### Assign variables -----------------------
        primary_keywords = get_setting('site','global','siteprimarykeywords')
        geo_location = get_setting('site','global','sitegeographiclocation')
        site_name = get_setting('site','global','sitedisplayname')
        category_set = object.category_set
        category = category_set.get('category', '')
        subcategory = category_set.get('sub_category', '')

        creator_name = ''
        if object.creator:
            creator_name = '%s %s' % (
                object.creator.first_name,
                object.creator.last_name
            )
        creator_name = creator_name.strip()

        ### Build string -----------------------
        value = '%s - %s' % (object.headline, object.activation_dt)
        value = value.strip()

        value = ''

        # start w/ headline
        if object.headline:
            value += object.headline

        # contact activation
        if object.headline and object.activation_dt:
            value += ' - %s' % object.activation_dt.strftime('%m-%d-%Y')
        elif object.activation_dt:
            value += object.activation_dt.strftime('%m-%d-%Y')

        # primary keywords OR category/subcategory
        if primary_keywords:
            value = '%s : %s' % (value, primary_keywords)
        else:
            if category:
                value = '%s %s' % (value, category)
            if category and subcategory:
                value = '%s : %s' % (value, subcategory)

        value = '%s directory' % value

        if creator_name:
            value = '%s contact: %s' % (value, creator_name)

        value = '%s directories for %s' % (value, site_name)

        if geo_location:
            value = '%s in %s' % (value, geo_location)

        return value
Ejemplo n.º 19
0
def encode_site(xml):
    xml.write("<title>%s</title>"%get_setting('site', 'global', 'sitedisplayname'), depth=1)
    xml.write("<description></description>", depth=1)
    xml.write("<pubDate>%s</pubDate>"%datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), depth=1)
    xml.write("<language>%s</language>"%get_setting('site', 'global', 'localizationlanguage'), depth=1)
    xml.write("<wp:wxr_version>%s</wp:wxr_version>"%1.0, depth=1)
    # not sure if this is required
    #xml.write("<wp:base_site_url>http://wordpress.com/</wp:base_site_url>", depth=1)
    #xml.write("<wp:base_blog_url>http://sambixly.wordpress.com</wp:base_blog_url>", depth=1)
    encode_categories(xml)
    encode_tags(xml)
Ejemplo n.º 20
0
    def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)
        # check if we need to hide the remember me checkbox
        # and set the default value for remember me
        hide_remember_me = get_setting('module', 'users', 'usershiderememberme')
        remember_me_default_checked = get_setting('module', 'users', 'usersremembermedefaultchecked')

        if remember_me_default_checked:
            self.fields['remember'].initial = True
        if hide_remember_me:
            self.fields['remember'].widget = forms.HiddenInput()
Ejemplo n.º 21
0
    def clean_new_password1(self):
        password1 = self.cleaned_data.get('new_password1')
        password_regex = get_setting('module', 'users', 'password_requirements_regex')
        password_requirements = get_setting('module', 'users', 'password_text')
        if password_regex:
            # At least MIN_LENGTH long
            # "^(?=.{8,})(?=.*[0-9=]).*$"
            if not re.match(password_regex, password1):
                raise forms.ValidationError(mark_safe("The new password does not meet the requirements </li><li>%s" % password_requirements))

        return password1
Ejemplo n.º 22
0
    def get_admin_emails(self):
        payment_admins = get_setting('module', 'payments', 'paymentrecipients')
        if payment_admins:
            payment_admins = payment_admins.split(',')
            admin_emails = payment_admins
        else:
            admin_emails = (get_setting('site', 'global', 'admincontactemail')).split(',')

        if admin_emails:
            admin_emails = ','.join(admin_emails)

        return admin_emails
Ejemplo n.º 23
0
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(LoginForm, self).__init__(*args, **kwargs)
        # check if we need to hide the remember me checkbox
        # and set the default value for remember me
        self.hide_remember_me = get_setting('module', 'users', 'usershiderememberme')
        self.remember_default = get_setting('module', 'users', 'usersremembermedefaultchecked')

        if self.remember_default:
            self.fields['remember'].initial = True
        if self.hide_remember_me:
            self.fields['remember'].widget = forms.HiddenInput()
Ejemplo n.º 24
0
def add(request, form_class=ResumeForm, template_name="resumes/add.html"):
    can_add_active = has_perm(request.user, 'resumes.add_resume')
    
    if not any([request.user.profile.is_superuser,
               can_add_active,
               get_setting('module', 'resumes', 'usercanadd'),
               (request.user.profile.is_member and get_setting('module', 'resumes', 'userresumesrequiresmembership'))
               ]):
        raise Http403

    if request.method == "POST":
        form = form_class(request.POST or None, user=request.user)
        if form.is_valid():
            resume = form.save(commit=False)

            # set it to pending if the user does not have add permission
            if not can_add_active:
                resume.status_detail = 'pending'

            # set up the expiration time based on requested duration
            now = datetime.now()
            resume.expiration_dt = now + timedelta(days=resume.requested_duration)

            resume = update_perms_and_save(request, form, resume)
            # we need to save instance first since we need the id for the file path
            if request.FILES:
                resume.resume_file = request.FILES['resume_file']
                resume.resume_file.file.seek(0)
                resume.save()

            EventLog.objects.log(instance=resume)

            if request.user.is_authenticated():
                messages.add_message(request, messages.SUCCESS, _('Successfully added %(r)s' % {'r':resume}))

            # send notification to administrators
            recipients = get_notice_recipients('module', 'resumes', 'resumerecipients')
            if recipients:
                if notification:
                    extra_context = {
                        'object': resume,
                        'request': request,
                    }
                    notification.send_emails(recipients,'resume_added', extra_context)

            if not request.user.is_authenticated():
                return HttpResponseRedirect(reverse('resume.thank_you'))
            else:
                return HttpResponseRedirect(reverse('resume', args=[resume.slug]))
    else:
        form = form_class(user=request.user)
    return render_to_response(template_name, {'form':form},
        context_instance=RequestContext(request))
Ejemplo n.º 25
0
    def get_admin_emails(self):
        payment_admins = get_setting("module", "payments", "paymentrecipients")
        if payment_admins:
            payment_admins = payment_admins.split(",")
            admin_emails = payment_admins
        else:
            admin_emails = (get_setting("site", "global", "admincontactemail")).split(",")

        if admin_emails:
            admin_emails = ",".join(admin_emails)

        return admin_emails
Ejemplo n.º 26
0
    def get_description(self):
        object = self.object

        ### Assign variables -----------------------
        primary_keywords = get_setting('site','global','siteprimarykeywords')
        category_set = object.category_set
        category = category_set.get('category', '')
        subcategory = category_set.get('sub_category', '')
        site_name = get_setting('site','global','sitedisplayname')
        geo_location = get_setting('site','global','sitegeographiclocation')
        creator_name = ''
        if object.creator:
            creator_name = '%s %s' % (
                object.creator.first_name,
                object.creator.last_name
            )
        creator_name = creator_name.strip()

        if object.summary:
            content = object.summary
        else:
            content = object.body

        content = strip_tags(content) #strips HTML tags
        content = unescape_entities(content)
        content = content.replace("\n","").replace("\r","")
        content = truncate_words(content, 50) # ~ about 250 chars

        ### Build string -----------------------
        value = object.headline

        if creator_name:
            value = '%s %s' % (value, creator_name)

        value = '%s : %s' % (value, content)

        if primary_keywords:
            value = '%s %s' % (value, primary_keywords)
        else:
            if category:
                value = '%s %s' % (value, category)
            if category and subcategory:
                value = '%s : %s' % (value, subcategory)

            value = '%s directory' % value

        value = '%s Directories for %s %s' % (
            value, site_name, geo_location)

        value = value.strip()

        return value
Ejemplo n.º 27
0
    def get_reminder_conf_body(self, event):
        from tendenci.apps.site_settings.utils import get_setting
        template_name = 'events/reminder_conf_email.html'

        return render_to_string(template_name=template_name,
                       context={'event': event,
                        'site_url': get_setting('site', 'global',
                                                'siteurl'),
                        'site_display_name': get_setting(
                                                 'site',
                                                 'global',
                                                 'sitedisplayname')
                        })
Ejemplo n.º 28
0
    def get_keywords(self):
        object = self.object

        ### Assign variables -----------------------
        dynamic_keywords = generate_meta_keywords(object.body)
        primary_keywords = get_setting('site','global','siteprimarykeywords')
        secondary_keywords = get_setting('site','global','sitesecondarykeywords')
        geo_location = get_setting('site','global','sitegeographiclocation')
        site_name = get_setting('site','global','sitedisplayname')

        creator_name = ''
        if object.creator:
            creator_name = '%s %s' % (
                object.creator.first_name,
                object.creator.last_name
            )

        ### Build string -----------------------
        value = ''

        if primary_keywords:
            value = '%s %s' % (value, primary_keywords)
            value = value.strip()

        if object.headline:
            list = [
                'Directories',
                geo_location,
                site_name,
                'white paper',
                creator_name,
            ]

            # remove blank items
            for item in list:
                if not item.strip():
                    list.remove(item)

            value = '%s %s, %s' % (value, ', '.join(list), dynamic_keywords)

        else:
            list = [
                'Directories',
                geo_location,
                site_name,
                'white paper',
                secondary_keywords,
            ]
            value = '%s %s' % (value, ''.join(list))

        return value
Ejemplo n.º 29
0
def geocode_api(**kwargs):
    import simplejson

    GEOCODE_BASE_URL = 'https://maps.googleapis.com/maps/api/geocode/json'
    kwargs['sensor'] = kwargs.get('sensor', 'false')
    api_key = get_setting('module', 'locations', 'google_geocoding_api_key')
    if not api_key:
        api_key = get_setting('module', 'locations', 'google_maps_api_key')
    if api_key:
        kwargs.update({
            'key': api_key
    })
    url = '%s?%s' % (GEOCODE_BASE_URL, urlencode(kwargs))

    return simplejson.load(urlopen(url))
Ejemplo n.º 30
0
def ajax_user(request, event_id):
    """Ajax query for user validation
    The parameters are email and memberid and pricing.
    The user that matches the given email/memberid will be checked
    if he/she can still register in the event with the given pricing.
    """
    event = get_object_or_404(Event, pk=event_id)

    if not get_setting('module', 'events', 'anonymousmemberpricing'):
        raise Http404

    memberid = request.GET.get('memberid', None)
    email = request.GET.get('email', None)
    pricingid = request.GET.get('pricingid', None)

    pricing = get_object_or_404(RegConfPricing, pk=pricingid)

    user = AnonymousUser()

    allow_memberid = get_setting('module', 'events', 'memberidpricing')
    if memberid and allow_memberid:# memberid takes priority over email
        membership = Membership.objects.first(member_number=memberid)
        if hasattr(membership, 'user'):
            user = membership.user
    elif email:
        users = User.objects.filter(email=email)
        if users:
            user = users[0]

    data = json.dumps(None)
    #check if already registered
    if not (user.is_anonymous() or pricing.allow_anonymous):
        used = Registrant.objects.filter(user=user)
        if used:
            if not (pricing.allow_anonymous or user.profile.is_superuser):
                data = json.dumps({"error":"REG"})
            else:
                data = json.dumps({"message":"REG"})

    #check if can use
    can_use = can_use_pricing(event, user, pricing)
    if not can_use:
        if not get_setting('module', 'events', 'sharedpricing'):
            data = json.dumps({"error":"INVALID"})
        else:
            data = json.dumps({"error":"SHARED"})

    return HttpResponse(data, content_type="text/plain")
Ejemplo n.º 31
0
from django.conf.urls import url
from tendenci.apps.resumes.signals import init_signals
from tendenci.apps.site_settings.utils import get_setting
from . import views
from .feeds import LatestEntriesFeed

init_signals()

urlpath = get_setting('module', 'resumes', 'url')
if not urlpath:
    urlpath = "resumes"

urlpatterns = [
    url(r'^%s/$' % urlpath, views.search, name="resumes"),
    url(r'^%s/search/$' % urlpath, views.search_redirect,
        name="resume.search"),
    url(r'^%s/print-view/(?P<slug>[\w\-\/]+)/$' % urlpath,
        views.print_view,
        name="resume.print_view"),
    url(r'^%s/add/$' % urlpath, views.add, name="resume.add"),
    url(r'^%s/edit/(?P<id>\d+)/$' % urlpath, views.edit, name="resume.edit"),
    url(r'^%s/edit/meta/(?P<id>\d+)/$' % urlpath,
        views.edit_meta,
        name="resume.edit.meta"),
    url(r'^%s/delete/(?P<id>\d+)/$' % urlpath,
        views.delete,
        name="resume.delete"),
    url(r'^%s/feed/$' % urlpath, LatestEntriesFeed(), name='resume.feed'),
    url(r'^%s/pending/$' % urlpath, views.pending, name="resume.pending"),
    url(r'^%s/approve/(?P<id>\d+)/$' % urlpath,
        views.approve,
Ejemplo n.º 32
0
    def __init__(self, apps, build_from_cache=False):
        self.all_apps = []
        self.core = []
        self.addons = []
        self.people = []

        # append core and plugin apps to
        # individual lists
        if not build_from_cache:
            for model, registry in apps.items():

                setting_tuple = (
                    'module',
                    registry.fields['model']._meta.app_label,
                    'enabled',
                )

                # enabled / has settings
                if check_setting(*setting_tuple):
                    registry.fields['enabled'] = get_setting(*setting_tuple)
                    registry.fields['has_settings'] = True
                else:
                    registry.fields['enabled'] = True
                    registry.fields['has_settings'] = False

                if not 'settings' in registry.fields['url'].keys():
                    registry.fields['url'].update({
                        'settings':
                        lazy_reverse(
                            'settings.index',
                            args=[
                                'module',
                                registry.fields['model']._meta.app_label
                            ])
                    })

                if registry.fields['app_type'] == 'addon':
                    self.addons.append(registry.fields)

                if registry.fields['app_type'] == 'people':
                    self.people.append(registry.fields)

                if registry.fields['app_type'] == 'core':
                    self.core.append(registry.fields)

                # append all apps for main iterable
                self.all_apps.append(registry.fields)
        else:
            #since we can only cache the list of apps and not the RegisteredApps instance
            #we have to rebuild this object based on the list of apps from the cache.

            # fix for TypeErrors encountered
            # This is just a patch fix.
            # TODO: Find the root cause of TypeError here

            try:
                for app in apps:

                    setting_tuple = (
                        'module',
                        app['model']._meta.app_label,
                        'enabled',
                    )

                    # enabled / has settings
                    if check_setting(*setting_tuple):
                        app['enabled'] = get_setting(*setting_tuple)
                        app['has_settings'] = True
                    else:
                        app['enabled'] = True
                        app['has_settings'] = False

                    if not 'settings' in app['url'].keys():
                        app['url'].update({
                            'settings':
                            lazy_reverse(
                                'settings.index',
                                args=['module', app['model']._meta.app_label])
                        })

                    if app['app_type'] == 'addon':
                        self.addons.append(app)

                    if app['app_type'] == 'people':
                        self.people.append(app)

                    if app['app_type'] == 'core':
                        self.core.append(app)

                    # append all apps for main iterable
                    self.all_apps.append(app)

            except TypeError:
                pass

        # sort the applications alphabetically by
        # object representation
        key = lambda x: unicode(x)
        self.all_apps = sorted(self.all_apps, key=key)
        self.core = sorted(self.core, key=key)
        self.addons = sorted(self.addons, key=key)
        self.people = sorted(self.people, key=key)
Ejemplo n.º 33
0
    def make_payment_transaction(self, payment_profile_id, membership=None):
        """
        Make a payment transaction. This includes:
        1) Make an API call createCustomerProfileTransactionRequest
        2) Create a payment transaction entry
        3) Create a payment entry
        4) If the transaction is successful, populate payment entry with the direct response and mark payment as paid
        """
        amount = self.invoice.balance
        # tender the invoice
        self.invoice.tender(self.recurring_payment.user)

        # create a payment record
        payment = Payment()

        payment.payments_pop_by_invoice_user(self.recurring_payment.user,
                                             self.invoice, self.invoice.guid)

        if self.billing_cycle_start_dt and self.billing_cycle_end_dt:
            description = self.recurring_payment.description
            description += '(billing cycle from {0} to {1})'.format(
                self.billing_cycle_start_dt.strftime('%m/%d/%Y'),
                self.billing_cycle_end_dt.strftime('%m/%d/%Y'))
        else:
            description = payment.description

        # charge user
        if self.recurring_payment.platform == "stripe":
            stripe.api_key = getattr(settings, 'STRIPE_SECRET_KEY', '')
            params = {
                'amount': math.trunc(amount * 100),  # amount in cents, again
                'currency': get_setting('site', 'global', 'currency'),
                'description': description,
                'customer': self.recurring_payment.customer_profile_id
            }

            success = False
            response_d = {
                'status_detail': 'not approved',
                'response_code': '0',
                'response_reason_code': '0',
                'result_code': 'Error',  # Error, Ok
                'message_code': '',  # I00001, E00027
            }
            try:
                charge_response = stripe.Charge.create(**params)
                success = True
                response_d['status_detail'] = 'approved'
                response_d['response_code'] = '1'
                response_d['response_subcode'] = '1'
                response_d['response_reason_code'] = '1'
                response_d[
                    'response_reason_text'] = 'This transaction has been approved. (Created# %s)' % charge_response.created
                response_d['trans_id'] = charge_response.id
                response_d['result_code'] = 'Ok'
                response_d['message_text'] = 'Successful.'
            except stripe.error.CardError as e:
                # it's a decline
                json_body = e.json_body
                err = json_body and json_body['error']
                code = err and err['code']
                message = err and err['message']
                charge_response = '{message} status={status}, code={code}'.format(
                    message=message, status=e.http_status, code=code)

                response_d['response_reason_text'] = charge_response
                response_d['message_code'] = code
                response_d['message_text'] = charge_response
            except Exception as e:
                charge_response = e.message
                response_d['response_reason_text'] = charge_response
                response_d['message_text'] = charge_response[:200]

            # update payment
            for key in response_d:
                if hasattr(payment, key):
                    setattr(payment, key, response_d[key])

        else:
            # make a transaction using CIM
            d = {
                'amount': amount,
                'order': {
                    'invoice_number': str(payment.invoice_num),
                    'description': description,
                    'recurring_billing': 'true'
                }
            }

            cpt = CIMCustomerProfileTransaction(
                self.recurring_payment.customer_profile_id, payment_profile_id)

            success, response_d = cpt.create(**d)

            # update the payment entry with the direct response returned from payment gateway
            payment = payment_update_from_response(
                payment, response_d['direct_response'])

        if success:
            payment.mark_as_paid()
            payment.save()
            payment.invoice.make_payment(self.recurring_payment.user,
                                         Decimal(payment.amount))
            # approve membership
            if membership:
                membership.approve()
                # send notification to user

            self.payment_received_dt = datetime.now()
        else:
            if payment.status_detail == '':
                payment.status_detail = 'not approved'
            payment.save()
            self.last_payment_failed_dt = datetime.now()

        self.save()

        # create a payment transaction record
        payment_transaction = PaymentTransaction(
            recurring_payment=self.recurring_payment,
            recurring_payment_invoice=self,
            payment_profile_id=payment_profile_id,
            trans_type='auth_capture',
            amount=amount,
            status=success)

        payment_transaction.payment = payment
        payment_transaction.result_code = response_d['result_code']
        payment_transaction.message_code = response_d['message_code']
        payment_transaction.message_text = response_d['message_text']

        payment_transaction.save()

        return payment_transaction
Ejemplo n.º 34
0
    def __init__(self, form, user, *args, **kwargs):
        """
        Dynamically add each of the form fields for the given form model
        instance and its related field model instances.
        """
        self.user = user
        self.form = form
        self.form_fields = form.fields.visible().order_by('position')
        self.auto_fields = form.fields.auto_fields().order_by('position')
        super(FormForForm, self).__init__(*args, **kwargs)

        def add_fields(form, form_fields):
            for field in form_fields:
                field_key = "field_%s" % field.id
                if "/" in field.field_type:
                    field_class, field_widget = field.field_type.split("/")
                else:
                    field_class, field_widget = field.field_type, None

                if field.field_type == 'EmailVerificationField':
                    one_email = get_setting('module', 'forms', 'one_email')
                    if one_email:
                        field_class = forms.EmailField
                    else:
                        field_class = EmailVerificationField

                elif field.field_type == 'BooleanField' and len(
                        field.choices) > 0:
                    field_class = forms.MultipleChoiceField
                    field_widget = 'django.forms.CheckboxSelectMultiple'

                elif field.field_type == 'CountryField' or field.field_type == 'StateProvinceField':
                    field_class = getattr(forms, 'ChoiceField')
                else:
                    field_class = getattr(forms, field_class)
                field_args = {
                    "label": mark_safe(field.label),
                    "required": field.required
                }
                arg_names = field_class.__init__.im_func.func_code.co_varnames
                if "max_length" in arg_names:
                    field_args["max_length"] = FIELD_MAX_LENGTH
                if "choices" in arg_names:
                    field_args["choices"] = field.get_choices()
                    #field_args["choices"] = zip(choices, choices)
                if "initial" in arg_names:
                    default = field.default.lower()
                    if field_class == "BooleanField":
                        if default == "checked" or default == "true" or \
                            default == "on" or default == "1":
                            default = True
                        else:
                            default = False
                    field_args["initial"] = field.default

                if field_widget is not None:
                    module, widget = field_widget.rsplit(".", 1)
                    field_args["widget"] = getattr(import_module(module),
                                                   widget)

                if field.field_function == 'EmailFirstName':
                    field_args["max_length"] = FIELD_FNAME_LENGTH
                elif field.field_function == 'EmailLastName':
                    field_args["max_length"] = FIELD_LNAME_LENGTH
                elif field.field_function == 'EmailFullName':
                    field_args["max_length"] = FIELD_NAME_LENGTH
                elif field.field_function == 'EmailPhoneNumber':
                    field_args["max_length"] = FIELD_PHONE_LENGTH

                form.fields[field_key] = field_class(**field_args)

                if not field_class == EmailVerificationField:
                    form.fields[field_key].widget.attrs['title'] = field.label
                    form.fields[field_key].widget.attrs[
                        'class'] = 'formforform-field'
                else:
                    form.fields[field_key].widget.widgets[0].attrs[
                        'class'] += ' formforform-field'
                    form.fields[field_key].widget.widgets[1].attrs[
                        'class'] += ' formforform-field'

                if form.fields[field_key].widget.__class__.__name__.lower(
                ) == 'selectdatewidget':
                    form.fields[field_key].widget.years = range(
                        1920, THIS_YEAR + 10)

        def add_pricing_fields(form, formforform):
            # include pricing options if any
            if (formforform.custom_payment or formforform.recurring_payment
                ) and formforform.pricing_set.all():

                currency_symbol = get_setting('site', 'global',
                                              'currencysymbol')

                pricing_options = []
                for pricing in formforform.pricing_set.all():

                    if pricing.price == None:
                        pricing_options.append((
                            pricing.pk,
                            mark_safe(
                                '<input type="text" class="custom-price" name="custom_price_%s" value="%s"/> <strong>%s</strong><br>%s'
                                %
                                (pricing.pk,
                                 form.data.get('custom_price_%s' % pricing.pk,
                                               unicode()), pricing.label,
                                 pricing.description))))
                    else:
                        if formforform.recurring_payment:
                            pricing_options.append(
                                (pricing.pk,
                                 mark_safe(
                                     '<strong>%s per %s %s - %s</strong><br>%s'
                                     % (tcurrency(pricing.price),
                                        pricing.billing_frequency,
                                        pricing.billing_period, pricing.label,
                                        pricing.description))))
                        else:
                            pricing_options.append(
                                (pricing.pk,
                                 mark_safe(
                                     '<strong>%s %s</strong><br>%s' %
                                     (tcurrency(pricing.price), pricing.label,
                                      pricing.description))))

                form.fields['pricing_option'] = forms.ChoiceField(
                    label=_('Pricing'),
                    choices=pricing_options,
                    widget=forms.RadioSelect(attrs={'class': 'pricing-field'}))

                form.fields['payment_option'] = forms.ModelChoiceField(
                    label=_('Payment Method'),
                    empty_label=None,
                    queryset=formforform.payment_methods.all(),
                    widget=forms.RadioSelect(attrs={'class': 'payment-field'}),
                    initial=1,
                )

        if self.form.pricing_position < self.form.fields_position:
            add_pricing_fields(self, self.form)
            add_fields(self, self.form_fields)
        else:
            add_fields(self, self.form_fields)
            add_pricing_fields(self, self.form)

        if not self.user.is_authenticated() and get_setting(
                'site', 'global', 'captcha'):  # add captcha if not logged in
            self.fields['captcha'] = CaptchaField(
                label=_('Type the code below'))

        self.add_form_control_class()
Ejemplo n.º 35
0
    def handle(self, *args, **options):
        from tendenci.apps.entities.models import Entity
        from tendenci.apps.user_groups.models import Group
        from tendenci.apps.site_settings.utils import get_setting
        from tendenci.apps.perms.models import TendenciBaseModel

        verbosity = int(options['verbosity'])

        [entity] = Entity.objects.filter(pk=1)[:1] or [None]
        [user] = User.objects.filter(pk=1)[:1] or [None]

        site_display_name = get_setting('site',
                                        'global',
                                        'sitedisplayname')
        if not site_display_name:
            site_display_name = 'Default'

        site_contact_name = get_setting('site',
                                        'global',
                                        'sitecontactname')
        site_contact_email = get_setting('site',
                                         'global',
                                         'sitecontactemail')
        site_phone_number = get_setting('site',
                                        'global',
                                        'sitephonenumber')
        site_url = get_setting('site',
                               'global',
                               'siteurl')
        # if there is no entity, create one.
        if not entity:
            params = {'id': 1,
                      'entity_name': site_display_name,
                      'entity_type': '',
                      'contact_name': site_contact_name,
                      'phone': site_phone_number,
                      'email': site_contact_email,
                      'fax': '',
                      'website': site_url,
                      'summary': '',
                      'notes': '',
                      'admin_notes': 'system auto created',
                      'allow_anonymous_view': True,
                      'status': True,
                      'status_detail': 'active'
                      }
            if user:
                params.update({'creator': user,
                               'creator_username': user.username,
                               'owner': user,
                               'owner_username': user.username
                               })
            else:
                params.update({'creator_username': '',
                               'owner_username': ''
                               })
            entity = Entity(**params)

            entity.save()
            print('entity created: ', entity.entity_name)

        # loop through all the tables and populate
        # the entity field only if it's null.
        models = apps.get_models()
        # exclude legacy tables
        tables_excluded = ['corporate_memberships_corporatemembership',
                           'corporate_memberships_corporatemembershiparchive']
        table_updated = []
        for model in models:
            if TendenciBaseModel in model.__bases__:
                if hasattr(model, 'entity'):
                    table_name = model._meta.db_table
                    if table_name in tables_excluded:
                        continue
                    for row in model.objects.all():
                        if not row.entity:
                            row.entity = entity
                            row.save(update_fields=['entity'])
                    table_updated.append(table_name)

        if verbosity >= 2:
            print()
            print('List of tables updated: ')
            print('\n'.join(table_updated))
            print()

        # GROUP - check if we have a group associated with
        group_exists = Group.objects.filter(entity=entity).exists()
        if not group_exists:
            params = {'name': site_display_name,
                      'entity': entity,
                      'type': 'distribution',
                      'email_recipient': site_contact_email,
                      'allow_anonymous_view': True,
                      'status': True,
                      'status_detail': 'active'
                      }
            if user:
                params.update({'creator': user,
                               'creator_username': user.username,
                               'owner': user,
                               'owner_username': user.username
                               })
            else:
                params.update({'creator_username': '',
                               'owner_username': ''
                               })
            group = Group(**params)

            try:
                group.save()
                print('Group created: ', group.name)
            except Exception as e:
                print(e)

        print('All done.')
Ejemplo n.º 36
0
from django.conf.urls import patterns, url, include
from tendenci.apps.site_settings.utils import get_setting
from tendenci.apps.corporate_memberships.signals import init_signals

init_signals()

urlpath = get_setting('module', 'corporate_memberships', 'url')
if not urlpath:
    urlpath = "corporatememberships"

urlpatterns = patterns(
    'tendenci.apps.corporate_memberships.views',
    url(r'^%s/$' % urlpath, 'search', name="corp_memb"),
    url(r'^%s/$' % urlpath, 'search', name="corp_memb.search"),
    url(r"^%s/get_app_fields/$" % urlpath,
        "get_app_fields_json",
        name="corpmemberships.get_app_fields"),
    url(r"^%s/applications/(?P<slug>[\w\-]+)/preview/$" % urlpath,
        "app_preview",
        name="corpmembership_app.preview"),
    url(r"^%s/applications/add_pre/$" % urlpath,
        "corpmembership_add_pre",
        name="corpmembership.add_pre"),
    url(r"^%s/applications/add/$" % urlpath,
        "corpmembership_add",
        name="corpmembership.add"),
    url(r"^%s/(?P<slug>[\w\-]+)/add/$" % urlpath,
        "corpmembership_add",
        name="corpmembership.add"),
    url(r"^%s/applications/add_conf/(?P<id>\d+)/$" % urlpath,
        "corpmembership_add_conf",
Ejemplo n.º 37
0
from django.conf.urls import patterns, url
from tendenci.apps.pages.feeds import LatestEntriesFeed
from tendenci.apps.site_settings.utils import get_setting

urlpath = get_setting('module', 'pages', 'url')
if not urlpath:
    urlpath = "pages"

urlpatterns = patterns(
    'tendenci.apps.pages.views',
    url(r'^%s/$' % urlpath, 'index', name="pages"),
    url(r'^%s/search/$' % urlpath, 'search', name="page.search"),
    url(r'^%s/print-view/(?P<slug>[\w\-\/]+)/$' % urlpath,
        'print_view',
        name="page.print_view"),
    url(r'^%s/export/$' % urlpath, 'export', name="page.export"),
    url(r'^%s/preview/$' % urlpath, 'preview', name="page.preview"),
    url(r'^%s/preview/(?P<id>\d+)/$' % urlpath, 'preview',
        name="page.preview"),
    url(r'^%s/add/$' % urlpath, 'add', name="page.add"),
    url(r'^%s/edit/(?P<id>\d+)/$' % urlpath, 'edit', name="page.edit"),
    url(r'^%s/versions/(?P<hash>[\w\-]+)/$' % urlpath,
        'index',
        name="page.version"),
    url(r'^%s/inactive/(?P<id>\d+)/$' % urlpath, 'index',
        name="page.inactive"),
    url(r'^%s/edit/meta/(?P<id>\d+)/$' % urlpath,
        'edit_meta',
        name="page.edit.meta"),
    url(r'^%s/delete/(?P<id>\d+)/$' % urlpath, 'delete', name="page.delete"),
    url(r'^%s/feed/$' % urlpath, LatestEntriesFeed(), name='page.feed'),
Ejemplo n.º 38
0
def get_active_theme():
    return get_setting('module', 'theme_editor', 'theme')
Ejemplo n.º 39
0
 def notice_log(self):
     return '<a href="%s%s?notice_id=%d">View logs</a>' % (get_setting(
         'site', 'global',
         'siteurl'), reverse('membership.notice.log.search'), self.id)
Ejemplo n.º 40
0
class MembershipDefaultAdmin(admin.ModelAdmin):
    """
    MembershipDefault model
    """

    form = MembershipDefaultForm

    profile = (
        _('Profile'),
        {'fields': (
            ('first_name', 'last_name'),
            ('email', 'email2'),
            ('company', 'department'), ('position_title', 'education'),
            ('address', 'address2'), ('address_type', 'industry'),
            ('city', 'state'), ('zipcode', 'country'),
            ('phone', 'phone2'),
            ('work_phone', 'home_phone'), ('mobile_phone',),
            ('fax'),
            ('url', 'url2'),
            ('dob', 'sex'), ('spouse',),
            ('hide_in_search', 'hide_address'), ('hide_email', 'hide_phone'),
            ('address_2', 'address2_2'),
            ('city_2', 'state_2'), ('zipcode_2', 'country_2'),
        )}
    )

    membership = (
        _('Membership'),
        {'fields': (
            'member_number',
            'renewal',
            'certifications',
            'work_experience',
            'referral_source',
            'referral_source_other',
            'referral_source_member_name',
            'referral_source_member_number',
            'affiliation_member_number',
            'primary_practice',
            'how_long_in_practice',
            'notes',
            'admin_notes',
            'newsletter_type',
            'directory_type',
            'chapter',
            'areas_of_expertise',
            'corporate_membership_id',
            'home_state',
            'year_left_native_country',
            'network_sectors',
            'networking',
            'government_worker',
            'government_agency',
            'license_number',
            'license_state',
            'region',
            'company_size',
            'promotion_code',
            'app',
        )}
    )

    education = (
        _('Education History'),
        {'fields': (
            ('school1', 'major1'), ('degree1', 'graduation_dt1'),
            ('school2', 'major2'), ('degree2', 'graduation_dt2'),
            ('school3', 'major3'), ('degree3', 'graduation_dt3'),
            ('school4', 'major4'), ('degree4', 'graduation_dt4'),
        )}
    )

    money = (
        _('Money'),
        {'fields': (
            'payment_method',
            'membership_type',
        )}
    )

    extra = (
        _('Extra'),
        {'fields': (
            'industry',
            'region',
        )}
    )

    status = (
        _('Status'),
        {'fields': (
            'join_dt',
            'renew_dt',
            'expire_dt',
        )}
    )

    fieldsets = (
        profile,
        membership,
        education,
        money,
        status
    )

    search_fields = [
        'user__first_name',
        'user__last_name',
        'user__email',
        'member_number',
        'user__username'
    ]

    list_display = [
        'id',
        'edit_link',
        'view_on_site',
        'user_profile',
        'email',
        'member_number',
        'membership_type_link',
        'get_approve_dt',
        'get_expire_dt',
        'get_status',
        'get_invoice',
    ]
    if get_setting('module', 'recurring_payments', 'enabled') and get_setting('module', 'memberships', 'autorenew'):
        list_display.append('auto_renew')
    list_display.append('admin_notes')
    list_display.append('reminder')
    list_editable = ['reminder',]
    list_display_links = ('id',)

    list_filter = [
        MembershipStatusDetailFilter,
        'membership_type',
    ]
    if get_setting('module', 'recurring_payments', 'enabled') and get_setting('module', 'memberships', 'autorenew'):
        list_filter.append(MembershipAutoRenewFilter)

    actions = [
        approve_selected,
        renew_selected,
        disapprove_selected,
        expire_selected,
        export_selected_main,
        export_selected_all
    ]

    def get_fieldsets(self, request, instance=None):
        demographics_fields = get_selected_demographic_field_names(
            instance and instance.app)

        if demographics_fields:
            demographics = (
                    _('Demographics'),
                    {'fields': tuple(demographics_fields)
                     }
                           )
        fieldsets = (
                self.profile,
                self.membership,
                self.education,)
        if demographics_fields:
            fieldsets += (
                demographics,
            )
        fieldsets += (
                self.money,
                self.status)

        return fieldsets

    @mark_safe
    def edit_link(self, instance):
        return '<a href="%s" title="Edit at Front End">%s</a>' % (
                reverse('membership_default.edit',args=[instance.id]),
                _('Edit'),)
    edit_link.short_description = _('edit')

    @mark_safe
    def view_on_site(self, obj):
        if not hasattr(obj, 'get_absolute_url'):
            return None

        link_icon = static('images/icons/external_16x16.png')
        link = '<a href="%s" title="%s"><img src="%s" alt="external_16x16" title="external icon"/></a>' % (
            obj.get_absolute_url(),
            strip_tags(obj),
            link_icon,
        )
        return link
    view_on_site.short_description = _('view')

    @mark_safe
    def user_profile(self, instance):
        return '<a href="%s">%s</a>' % (
              reverse('profile', args=[instance.user.username]),
              instance.user.get_full_name() or instance.user.username,)
    user_profile.short_description = _('User Profile')
    user_profile.admin_order_field = 'user__last_name'

    def email(self, instance):
        return instance.user.email
    email.admin_order_field = 'user__email'

    def get_status(self, instance):
        return instance.get_status().capitalize()
    get_status.short_description = u'Status'
    get_status.admin_order_field = 'status_detail'

    @mark_safe
    def get_invoice(self, instance):
        inv = instance.get_invoice()
        if inv:
            if inv.balance > 0:
                return '<a href="%s" title="Invoice">#%s (%s)</a>' % (
                    inv.get_absolute_url(),
                    inv.pk,
                    tcurrency(inv.balance)
                )
            else:
                return '<a href="%s" title="Invoice">#%s</a>' % (
                    inv.get_absolute_url(),
                    inv.pk
                )
        return ""
    get_invoice.short_description = u'Invoice'

    def get_create_dt(self, instance):
        return instance.create_dt.strftime('%b %d, %Y, %I:%M %p')
    get_create_dt.short_description = u'Created On'

    def get_approve_dt(self, instance):
        dt = instance.application_approved_dt

        if dt:
            return dt.strftime('%b %d, %Y, %I:%M %p')
        return u''
    get_approve_dt.short_description = u'Approved On'
    get_approve_dt.admin_order_field = 'application_approved_dt'

    def get_expire_dt(self, instance):
        dt = instance.expire_dt

        if dt:
            return dt.strftime('%m/%d/%Y')
        return u''
    get_expire_dt.short_description = u'Expire Date'

    def get_actions(self, request):
        actions = super(MembershipDefaultAdmin, self).get_actions(request)
        if not has_perm(request.user, 'memberships.approve_membershipdefault'):
            del actions['approve_selected']
        return actions

    def save_form(self, request, form, change):
        """
        Given a ModelForm return an unsaved instance. ``change`` is True if
        the object is being changed, and False if it's being added.
        """
        if form.Meta.fields == ['reminder']:
            return form.save(commit=False)

        return form.save(request=request, commit=False)

    def add_view(self, request, form_url='', extra_context=None):
        """
        Intercept add page and redirect to form.
        """
        apps = MembershipApp.objects.filter(
            status=True,
            status_detail__in=['published', 'active'])

        count = apps.count()
        if count == 1:
            app = apps[0]
            if app.use_for_corp:
                return HttpResponseRedirect(
                    reverse('membership_default.corp_pre_add')
                )
            else:
                return HttpResponseRedirect(
                    reverse('membership_default.add', args=[app.slug])
                )
        else:
            return HttpResponseRedirect(
                reverse('admin:memberships_membershipapp_changelist')
            )

    def response_change(self, request, obj):
        """
        When the change page is submitted we can redirect
        to a URL specified in the next parameter.
        """
        POST_KEYS = request.POST
        GET_KEYS = request.GET
        NEXT_URL = iri_to_uri('%s') % request.GET.get('next')

        do_next_url = (
            '_addanother' not in POST_KEYS,
            '_continue' not in POST_KEYS,
            'next' in GET_KEYS)

        if all(do_next_url):
            return HttpResponseRedirect(NEXT_URL)

        return super(MembershipDefaultAdmin, self).response_change(request, obj)

    def has_change_permission(self, request, obj=None):
        return (has_perm(request.user, 'memberships.approve_membershipdefault') or
                has_perm(request.user, 'memberships.change_membershipdefault'))

    def get_urls(self):
        """
        Add the export view to urls.
        """
        urls = super(MembershipDefaultAdmin, self).get_urls()

        extra_urls = [
            re_path(r'^approve/(?P<pk>\d+)/$',
                self.admin_site.admin_view(self.approve),
                name='membership.admin_approve'),
            re_path(r'^renew/(?P<pk>\d+)/$',
                self.admin_site.admin_view(self.renew),
                name='membership.admin_renew'),
            re_path(r'^disapprove/(?P<pk>\d+)/$',
                self.admin_site.admin_view(self.disapprove),
                name='membership.admin_disapprove'),
            re_path(r'^expire/(?P<pk>\d+)/$',
                self.admin_site.admin_view(self.expire),
                name='membership.admin_expire'),
        ]
        return extra_urls + urls

    # django-admin custom views ----------------------------------------

    def approve(self, request, pk):
        """
        Approve membership and redirect to
        membershipdefault change page.
        """
        if not has_perm(request.user, 'memberships.approve_membershipdefault'):
            raise Http403

        m = get_object_or_404(MembershipDefault, pk=pk)
        is_renewal = m.is_renewal()
        m.approve(request_user=request.user)
        m.send_email(request, ('approve_renewal' if is_renewal else 'approve'))
        if m.corporate_membership_id:
            # notify corp reps
            m.email_corp_reps(request)

        messages.add_message(
            request,
            messages.SUCCESS,
            _('Successfully Approved')
        )

        return redirect(reverse(
            'admin:memberships_membershipdefault_change',
            args=[pk],
        ))

    def renew(self, request, pk):
        """
        Renew membership and redirect to
        membershipdefault change page.
        """
        m = get_object_or_404(MembershipDefault, pk=pk)
        m.renew(request_user=request.user)
        m.send_email(request, 'renewal')

        messages.add_message(
            request,
            messages.SUCCESS,
            _('Successfully Renewed')
        )

        return redirect(reverse(
            'admin:memberships_membershipdefault_change',
            args=[pk],
        ))

    def disapprove(self, request, pk):
        """
        Disapprove membership and redirect to
        membershipdefault change page.
        """
        m = get_object_or_404(MembershipDefault, pk=pk)
        is_renewal = m.is_renewal()
        m.disapprove(request_user=request.user)
        m.send_email(request, ('disapprove_renewal' if is_renewal else 'disapprove'))

        messages.add_message(
            request,
            messages.SUCCESS,
            _('Successfully Disapproved')
        )

        return redirect(reverse(
            'admin:memberships_membershipdefault_change',
            args=[pk],
        ))

    def expire(self, request, pk):
        """
        Expire membership and redirect to
        membershipdefault change page.
        """
        m = get_object_or_404(MembershipDefault, pk=pk)
        m.expire(request_user=request.user)

        messages.add_message(
            request,
            messages.SUCCESS,
            _('Successfully Expired')
        )

        return redirect(reverse(
            'admin:memberships_membershipdefault_change',
            args=[pk],
        ))
Ejemplo n.º 41
0
def add(request, form_class=ResumeForm, template_name="resumes/add.html"):
    can_add_active = has_perm(request.user, 'resumes.add_resume')

    if not any([
            request.user.profile.is_superuser, can_add_active,
            get_setting('module', 'resumes', 'usercanadd'),
        (request.user.profile.is_member
         and get_setting('module', 'resumes', 'userresumesrequiresmembership'))
    ]):
        raise Http403

    if request.method == "POST":
        form = form_class(request.POST or None, user=request.user)
        if form.is_valid():
            resume = form.save(commit=False)

            # set it to pending if the user does not have add permission
            if not can_add_active:
                resume.status_detail = 'pending'

            # set up the expiration time based on requested duration
            now = datetime.now()
            resume.expiration_dt = now + timedelta(
                days=resume.requested_duration)

            resume = update_perms_and_save(request, form, resume)
            # we need to save instance first since we need the id for the file path
            if request.FILES:
                resume.resume_file = request.FILES['resume_file']
                resume.resume_file.file.seek(0)
                resume.save()

            EventLog.objects.log(instance=resume)

            if request.user.is_authenticated:
                messages.add_message(
                    request, messages.SUCCESS,
                    _('Successfully added %(r)s' % {'r': resume}))

            # send notification to administrators
            recipients = get_notice_recipients('module', 'resumes',
                                               'resumerecipients')
            if recipients:
                if notification:
                    extra_context = {
                        'object': resume,
                        'request': request,
                    }
                    notification.send_emails(recipients, 'resume_added',
                                             extra_context)

            if not request.user.is_authenticated:
                return HttpResponseRedirect(reverse('resume.thank_you'))
            else:
                return HttpResponseRedirect(
                    reverse('resume', args=[resume.slug]))
    else:
        form = form_class(user=request.user)
    return render_to_resp(request=request,
                          template_name=template_name,
                          context={'form': form})
Ejemplo n.º 42
0
from django.conf.urls import patterns, url
from tendenci.apps.site_settings.utils import get_setting

urlpath = get_setting('module', 'associations', 'url')
if not urlpath:
    urlpath = "associations"

urlpatterns = patterns(
    'tendenci.apps.associations.views',
    url(r'^%s/add/$' % urlpath, 'add', name="associations.add"),
    url(r'^%s/edit/(?P<id>\d+)/$' % urlpath, 'edit', name='associations.edit'),
    url(r'^%s/join/$' % urlpath, 'join', name="associations.join"),
    url(r'^%s/change/$' % urlpath, 'change', name="associations.change"),
    # url(r'^%s/delete/$' % urlpath, 'delete', name="associations.delete"),
)
Ejemplo n.º 43
0
from django.utils.translation import ugettext_lazy as _
from django.utils.html import mark_safe
from django.core.urlresolvers import reverse

from tendenci.libs.model_report.report import reports, ReportAdmin
from tendenci.libs.model_report.utils import (sum_column, us_date_format,
                                              date_label, obj_type_format,
                                              date_from_datetime,
                                              entity_format)

from tendenci.apps.invoices.models import Invoice
from tendenci.apps.site_settings.utils import get_setting

CURRENCY_SYMBOL = get_setting("site", "global", "currencysymbol")


def id_format(value, instance):
    link = reverse('invoice.view', args=[value])
    html = "<a href=\"%s\">%s</a>" % (link, value)
    return mark_safe(html)


def currency_format(value, instance):
    return "%s%s" % (CURRENCY_SYMBOL, value)


class InvoiceReport(ReportAdmin):
    # choose a title for your report for h1, title tag and report list
    title = _('Invoice Report')

    # specify your model
Ejemplo n.º 44
0
    def send(self, fail_silently=False, **kwargs):
        recipient_list = []
        recipient_bcc_list = []
        headers = kwargs.get('headers', {})
        attachments = kwargs.get('attachments', [])

        if isinstance(self.recipient, str):
            recipient_list = self.recipient.split(',')
            recipient_list = [recipient.strip() for recipient in recipient_list
                              if recipient.strip() != '']
        else:
            recipient_list = list(self.recipient)
        if isinstance(self.recipient_cc, str):
            recipient_cc_list = self.recipient_cc.split(',')
            recipient_cc_list = [recipient_cc.strip() for recipient_cc in recipient_cc_list if
                                  recipient_cc.strip() != '']
            recipient_list += recipient_cc_list
        else:
            recipient_list += list(self.recipient_cc)
        if isinstance(self.recipient_bcc, str):
            recipient_bcc_list = self.recipient_bcc.split(',')
            recipient_bcc_list = [recipient_bcc.strip() for recipient_bcc in recipient_bcc_list if
                                   recipient_bcc.strip() != '']
        else:
            recipient_bcc_list = list(self.recipient_bcc)

        if self.reply_to:
            headers['Reply-To'] = self.reply_to
        if not self.sender:
            self.sender = get_setting('site', 'global', 'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL
        if self.sender_display:
            # Add quotes around display name to prevent errors on sending
            # When display name contains comma or other control characters,
            headers['From'] = '"%s" <%s>' % (self.sender_display, self.sender)
        if self.priority and self.priority == 1:
            headers['X-Priority'] = '1'
            headers['X-MSMail-Priority'] = 'High'

        # remove blocked from recipient_list and recipient_bcc_list
        temp_recipient_list = copy.copy(recipient_list)
        for e in temp_recipient_list:
            if self.is_blocked(e) or not is_valid_domain(e):
                recipient_list.remove(e)
        temp_recipient_bcc_list = copy.copy(recipient_bcc_list)
        for e in temp_recipient_bcc_list:
            if self.is_blocked(e) or not is_valid_domain(e):
                recipient_bcc_list.remove(e)

        if recipient_list or recipient_bcc_list:
            msg = EmailMessage(self.subject,
                               add_tendenci_footer(self.body),
                               self.sender,
                               recipient_list,
                               recipient_bcc_list,
                               headers=headers,
                               connection=kwargs.get('connection', None))
            if self.content_type == 'html' or self.content_type == self.CONTENT_TYPE_HTML:
                msg.content_subtype = 'html'
            if attachments:
                msg.attachments = attachments
            msg.send(fail_silently=fail_silently)
Ejemplo n.º 45
0
class FormAdmin(TendenciBaseModelAdmin):

    inlines = (
        PricingAdmin,
        FieldAdmin,
    )
    list_display = (
        "title",
        "intro",
        "email_from",
        "email_copies",
        "admin_link_export",
        'export_all_link',
        "admin_link_view",
        'group',
    )
    list_display_links = ("title", )
    #    list_filter = ("status",)
    search_fields = ("title", "intro", "response", "email_from",
                     "email_copies")
    #    radio_fields = {"status": admin.HORIZONTAL}
    prepopulated_fields = {'slug': ['title']}
    list_filter = ('group', )

    if not get_setting('module', 'recurring_payments', 'enabled'):
        payment_fields = ("custom_payment", "payment_methods")
    else:
        payment_fields = ("custom_payment", 'recurring_payment',
                          "payment_methods")

    position_fields = ("intro_position", "fields_position", "pricing_position")
    section_name_fields = ("intro_name", "fields_name", "pricing_name")

    fieldsets = (
        (None, {
            "fields": ("title", "slug", "intro", "response", "completion_url",
                       'group', "template")
        }),
        (_("Email"), {
            "fields": ('subject_template', "email_from", "email_copies",
                       "send_email", "email_text")
        }),
        (_('Permissions'), {
            'fields': ('allow_anonymous_view', )
        }),
        (_('Advanced Permissions'), {
            'classes': ('collapse', ),
            'fields': (
                'user_perms',
                'member_perms',
                'group_perms',
            )
        }),
        (_('Publishing Status'), {
            'fields': ('status_detail', )
        }),
        (_("Payment"), {
            "fields": payment_fields
        }),
        (_("Section Positions"), {
            "fields":
            position_fields,
            "description":
            _("Please select the order in which you would like the Intro paragraph, the fields (name, date, address, etc) and the pricing options to appear on your finished form. Example: If you want the paragraph at the top, position the 'Intro' to the first position."
              )
        }),
        (_("Section Names"), {
            "fields":
            section_name_fields,
            "description":
            _("Label the section names to meet the needs of your form. Examples for the pricing section would be: Pricing, Costs, Ticket Prices, Additional Costs, Service Fees and text of that nature."
              )
        }),
    )

    form = FormAdminForm

    class Media:
        js = (
            '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js',
            '//ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js',
            static('js/global/tinymce.event_handlers.js'),
            static('js/admin/form-fields-inline-ordering.js'),
            static('js/admin/form-field-dynamic-hiding.js'),
            static('js/admin/form-position.js'),
            static('js/admin/tax_fields.js'),
        )
        css = {
            'all': [static('css/admin/dynamic-inlines-with-sort.css')],
        }

    @mark_safe
    def export_all_link(self, obj):
        link = '-----'
        if obj.has_files():
            link = '<a href="%s" title="Export all">Export entries (including uploaded files)</a>' % reverse(
                'form_entries_export_full', args=[obj.pk])
        return link

    export_all_link.short_description = ''

    def change_view(self, request, object_id, form_url='', extra_context=None):
        obj = self.get_object(request, unquote(object_id))
        if obj:
            #check if the form has file fields
            extra_context = extra_context or {}
            extra_context['has_files'] = obj.has_files()

            for inline_class in self.inlines:
                if inline_class.model == Field:
                    if obj.fields_name:
                        inline_class.verbose_name = obj.fields_name
                        inline_class.verbose_name_plural = obj.fields_name
                elif inline_class.model == Pricing:
                    inline_class.verbose_name = obj.pricing_name
                    inline_class.verbose_name_plural = obj.pricing_name

        return super(FormAdmin, self).change_view(request, object_id, form_url,
                                                  extra_context)

    def get_urls(self):
        """
        Add the export view to urls.
        """
        urls = super(FormAdmin, self).get_urls()
        extra_urls = [
            url(r'^export/(?P<form_id>\d+)/$',
                self.admin_site.admin_view(self.export_view),
                name="forms_form_export"),
            url(r'^file/(?P<field_entry_id>\d+)/$',
                self.admin_site.admin_view(self.file_view),
                name="forms_form_file"),
        ]
        return extra_urls + urls

    def export_view(self, request, form_id):
        """
        Output a CSV file to the browser containing the entries for the form.
        """
        form = get_object_or_404(Form, id=form_id)
        response = HttpResponse(content_type='text/csv')
        csvname = '%s-%s.csv' % (form.slug, slugify(datetime.now().ctime()))
        response['Content-Disposition'] = 'attachment; filename="%s"' % csvname
        csv = writer(response)
        # Write out the column names and store the index of each field
        # against its ID for building each entry row. Also store the IDs of
        # fields with a type of FileField for converting their field values
        # into download URLs.
        columns = []
        field_indexes = {}
        file_field_ids = []
        for field in form.fields.all().order_by('position', 'id'):
            columns.append(field.label)
            field_indexes[field.id] = len(field_indexes)
            if field.field_type == "FileField":
                file_field_ids.append(field.id)
        entry_time_name = FormEntry._meta.get_field("entry_time").verbose_name
        columns.append(str(entry_time_name))
        if form.custom_payment:
            columns.append(str("Pricing"))
            columns.append(str("Price"))
            columns.append(str("Payment Method"))
        csv.writerow(columns)
        # Loop through each field value order by entry, building up each
        # entry as a row.
        entries = FormEntry.objects.filter(form=form).order_by('pk')
        for entry in entries:
            values = FieldEntry.objects.filter(entry=entry)
            row = [""] * len(columns)
            entry_time = entry.entry_time.strftime("%Y-%m-%d %H:%M:%S")

            if form.custom_payment:
                if entry.pricing:
                    row[-4] = entry_time
                    row[-3] = entry.pricing.label
                    if not entry.pricing.price:
                        row[-2] = entry.custom_price
                    else:
                        row[-2] = entry.pricing.price
                row[-1] = entry.payment_method
            else:
                row[-1] = entry_time

            for field_entry in values:
                value = field_entry.value
                # Create download URL for file fields.
                if field_entry.field_id in file_field_ids:
                    url = reverse("admin:forms_form_file",
                                  args=(field_entry.id, ))
                    value = request.build_absolute_uri(url)
                # Only use values for fields that currently exist for the form.
                try:
                    row[field_indexes[field_entry.field_id]] = value
                except KeyError:
                    pass
            # Write out the row.
            csv.writerow(row)
        return response

    def file_view(self, request, field_entry_id):
        """
        Output the file for the requested field entry.
        """
        field = get_object_or_404(FieldEntry, id=field_entry_id)

        base_name = os.path.basename(field.value)
        mime_type = mimetypes.guess_type(base_name)[0]

        if not mime_type:
            raise Http404

        if not default_storage.exists(field.value):
            raise Http404

        data = default_storage.open(field.value).read()
        f = ContentFile(data)

        response = HttpResponse(f.read(), content_type=mime_type)
        response['Content-Disposition'] = 'filename="%s"' % base_name
        return response
Ejemplo n.º 46
0
def renew(request,
          id,
          form_class=DirectoryRenewForm,
          template_name="directories/renew.html"):
    can_add_active = has_perm(request.user, 'directories.add_directory')
    require_approval = get_setting('module', 'directories',
                                   'renewalrequiresapproval')
    directory = get_object_or_404(Directory, pk=id)

    if not has_perm(request.user, 'directories.change_directory',
                    directory) or not request.user == directory.creator:
        raise Http403

    # pop payment fields if not required
    require_payment = get_setting('module', 'directories',
                                  'directoriesrequirespayment')
    form = form_class(request.POST or None,
                      request.FILES or None,
                      instance=directory,
                      user=request.user)
    if not require_payment:
        del form.fields['payment_method']
        del form.fields['list_type']

    if request.method == "POST":
        if form.is_valid():
            directory = form.save(commit=False)
            pricing = form.cleaned_data['pricing']

            if directory.payment_method:
                directory.payment_method = directory.payment_method.lower()
            if not directory.requested_duration:
                directory.requested_duration = 30
            if not directory.list_type:
                directory.list_type = 'regular'

            if not directory.slug:
                directory.slug = '%s-%s' % (slugify(
                    directory.headline), Directory.objects.count())

            if not can_add_active and require_approval:
                directory.status = True
                directory.status_detail = 'pending'
            else:
                directory.activation_dt = datetime.now()
                # set the expiration date
                directory.expiration_dt = directory.activation_dt + timedelta(
                    days=directory.requested_duration)
                # mark renewal as not sent for new exp date
                directory.renewal_notice_sent = False
            # update all permissions and save the model
            directory = update_perms_and_save(request, form, directory)

            # create invoice
            directory_set_inv_payment(request.user, directory, pricing)
            msg_string = 'Successfully renewed %s' % directory
            messages.add_message(request, messages.SUCCESS, _(msg_string))

            # send notification to administrators
            # get admin notice recipients
            recipients = get_notice_recipients('module', 'directories',
                                               'directoryrecipients')
            if recipients:
                if notification:
                    extra_context = {
                        'object': directory,
                        'request': request,
                    }
                    notification.send_emails(recipients, 'directory_renewed',
                                             extra_context)

            if directory.payment_method.lower() in ['credit card', 'cc']:
                if directory.invoice and directory.invoice.balance > 0:
                    return HttpResponseRedirect(
                        reverse('payments.views.pay_online',
                                args=[
                                    directory.invoice.id,
                                    directory.invoice.guid
                                ]))
            if can_add_active:
                return HttpResponseRedirect(
                    reverse('directory', args=[directory.slug]))
            else:
                return HttpResponseRedirect(reverse('directory.thank_you'))

    return render_to_response(template_name, {
        'directory': directory,
        'form': form
    },
                              context_instance=RequestContext(request))
Ejemplo n.º 47
0
 def save(self, *args, **kwargs):
     # If this is the current contact form, update checklist
     if str(self.pk) == get_setting('site', 'global', 'contact_form'):
         checklist_update('update-contact')
     super(Form, self).save(*args, **kwargs)
Ejemplo n.º 48
0
def add(request,
        form_class=DirectoryForm,
        template_name="directories/add.html"):
    can_add_active = has_perm(request.user, 'directories.add_directory')

    if not any([
            request.user.profile.is_superuser, can_add_active,
            get_setting('module', 'directories', 'usercanadd'),
        (request.user.profile.is_member and get_setting(
            'module', 'directories', 'directoriesrequiresmembership'))
    ]):
        raise Http403

    pricings = DirectoryPricing.objects.filter(status=True)
    if not pricings and has_perm(request.user,
                                 'directories.add_directorypricing'):
        msg_string = 'You need to add a %s Pricing before you can add %s.' % (
            get_setting('module', 'directories', 'label_plural'),
            get_setting('module', 'directories', 'label'))
        messages.add_message(request, messages.WARNING, _(msg_string))
        return HttpResponseRedirect(reverse('directory_pricing.add'))

    require_payment = get_setting('module', 'directories',
                                  'directoriesrequirespayment')

    form = form_class(request.POST or None,
                      request.FILES or None,
                      user=request.user)

    if not require_payment:
        del form.fields['payment_method']
        del form.fields['list_type']

    if request.method == "POST":
        if require_payment:
            is_free = is_free_listing(request.user,
                                      request.POST.get('pricing', 0),
                                      request.POST.get('list_type'))
            if is_free:
                del form.fields['payment_method']

        if form.is_valid():
            directory = form.save(commit=False)
            pricing = form.cleaned_data['pricing']

            if require_payment and is_free:
                directory.payment_method = 'paid - cc'
            if directory.payment_method:
                directory.payment_method = directory.payment_method.lower()
            if not directory.requested_duration:
                directory.requested_duration = 30
            if not directory.list_type:
                directory.list_type = 'regular'

            if not directory.slug:
                directory.slug = '%s-%s' % (slugify(
                    directory.headline), Directory.objects.count())

            if not can_add_active:
                directory.status = True
                directory.status_detail = 'pending'
            else:
                directory.activation_dt = datetime.now()
                # set the expiration date
                directory.expiration_dt = directory.activation_dt + timedelta(
                    days=directory.requested_duration)

            directory = update_perms_and_save(request, form, directory)

            # create invoice
            directory_set_inv_payment(request.user, directory, pricing)
            msg_string = 'Successfully added %s' % directory
            messages.add_message(request, messages.SUCCESS, _(msg_string))

            # send notification to administrators
            # get admin notice recipients
            recipients = get_notice_recipients('module', 'directories',
                                               'directoryrecipients')
            if recipients:
                if notification:
                    extra_context = {
                        'object': directory,
                        'request': request,
                    }
                    notification.send_emails(recipients, 'directory_added',
                                             extra_context)

            if directory.payment_method.lower() in ['credit card', 'cc']:
                if directory.invoice and directory.invoice.balance > 0:
                    return HttpResponseRedirect(
                        reverse('payment.pay_online',
                                args=[
                                    directory.invoice.id,
                                    directory.invoice.guid
                                ]))
            if can_add_active:
                return HttpResponseRedirect(
                    reverse('directory', args=[directory.slug]))
            else:
                return HttpResponseRedirect(reverse('directory.thank_you'))

    return render_to_response(template_name, {
        'form': form,
        'require_payment': require_payment
    },
                              context_instance=RequestContext(request))
Ejemplo n.º 49
0
 def __str__(self):
     currency_symbol = get_setting('site', 'global', 'currencysymbol')
     price = "%s%s(R)/%s(P)" % (currency_symbol, self.regular_price,
                                self.premium_price)
     return "%d days for %s" % (self.duration, price)
Ejemplo n.º 50
0
def add(request, form_class=JobForm, template_name="jobs/add.html",
        object_type=Job, success_redirect='job', thankyou_redirect='job.thank_you'):

    require_payment = get_setting('module', 'jobs',
                                    'jobsrequirespayment')

    can_add_active = has_perm(request.user, 'jobs.add_job')

    get_object_or_404(
        ContentType,
        app_label=object_type._meta.app_label,
        model=object_type._meta.model_name
    )

    form = form_class(request.POST or None, request.FILES or None, user=request.user)
    # adjust the fields depending on user type
    if not require_payment:
        del form.fields['payment_method']
        del form.fields['list_type']

    if request.method == "POST":
        if require_payment:
            is_free = is_free_listing(request.user,
                               request.POST.get('pricing', 0),
                               request.POST.get('list_type'))
            if is_free:
                del form.fields['payment_method']

        if form.is_valid():
            job = form.save(commit=False)
            pricing = form.cleaned_data['pricing']

            if require_payment and is_free:
                job.payment_method = 'paid - cc'

            # set it to pending if the user is anonymous or not an admin
            if not can_add_active:
                #job.status = 1
                job.status_detail = 'pending'

            # list types and duration
            if not job.requested_duration:
                job.requested_duration = 30
            if not job.list_type:
                job.list_type = 'regular'

            # set up all the times
            now = datetime.now()
            job.activation_dt = now
            if not job.post_dt:
                job.post_dt = now

            # set the expiration date
            job.expiration_dt = job.activation_dt + timedelta(
                                        days=job.requested_duration)

            # semi-anon job posts don't get a slug field on the form
            # see __init__ method in JobForm
            if not job.slug:
                job.slug = '%s-%d' % (slugify(job.title), int(time.time()))

            job = update_perms_and_save(request, form, job)

            # create invoice
            job_set_inv_payment(request.user, job, pricing)

            #save relationships
            job.save()
            msg_string = u'Successfully added %s' % str(job)
            messages.add_message(request, messages.SUCCESS,_(msg_string))

            # send notification to administrators
            recipients = get_notice_recipients(
                            'module', 'jobs', 'jobrecipients')
            if recipients:
                if notification:
                    extra_context = {
                        'object': job,
                        'request': request,
                    }
                    notification.send_emails(recipients, 'job_added',
                                                extra_context)

            # send user to the payment page if payment is required
            if require_payment:
                if job.payment_method.lower() in ['credit card', 'cc', 'online payment']:
                    if job.invoice and job.invoice.balance > 0:
                        return HttpResponseRedirect(reverse(
                            'payment.pay_online',
                            args=[job.invoice.id, job.invoice.guid])
                        )

            # send user to thank you or view page
            if request.user.profile.is_superuser:
                return HttpResponseRedirect(
                        reverse(success_redirect, args=[job.slug]))
            else:
                return HttpResponseRedirect(reverse(thankyou_redirect))
    else:
        # Redirect user w/perms to create pricing if none exist
        pricings = JobPricing.objects.all()
        if not pricings and has_perm(request.user, 'jobs.add_jobpricing'):
            msg_string = 'You need to add a %s Pricing before you can add a %s.' % (get_setting('module', 'jobs', 'label_plural'),get_setting('module', 'jobs', 'label'))
            messages.add_message(request, messages.WARNING, _(msg_string))
            return HttpResponseRedirect(reverse('job_pricing.add'))

    return render_to_resp(request=request, template_name=template_name,
            context={'form': form,
             'require_payment': require_payment})
Ejemplo n.º 51
0
        def add_fields(form, form_fields):
            for field in form_fields:
                field_key = "field_%s" % field.id
                if "/" in field.field_type:
                    field_class, field_widget = field.field_type.split("/")
                else:
                    field_class, field_widget = field.field_type, None

                if field.field_type == 'EmailVerificationField':
                    one_email = get_setting('module', 'forms', 'one_email')
                    if one_email:
                        field_class = forms.EmailField
                    else:
                        field_class = EmailVerificationField

                elif field.field_type == 'BooleanField' and len(
                        field.choices) > 0:
                    field_class = forms.MultipleChoiceField
                    field_widget = 'django.forms.CheckboxSelectMultiple'

                elif field.field_type == 'CountryField' or field.field_type == 'StateProvinceField':
                    field_class = getattr(forms, 'ChoiceField')
                else:
                    field_class = getattr(forms, field_class)
                field_args = {
                    "label": mark_safe(field.label),
                    "required": field.required
                }
                arg_names = field_class.__init__.im_func.func_code.co_varnames
                if "max_length" in arg_names:
                    field_args["max_length"] = FIELD_MAX_LENGTH
                if "choices" in arg_names:
                    field_args["choices"] = field.get_choices()
                    #field_args["choices"] = zip(choices, choices)
                if "initial" in arg_names:
                    default = field.default.lower()
                    if field_class == "BooleanField":
                        if default == "checked" or default == "true" or \
                            default == "on" or default == "1":
                            default = True
                        else:
                            default = False
                    field_args["initial"] = field.default

                if field_widget is not None:
                    module, widget = field_widget.rsplit(".", 1)
                    field_args["widget"] = getattr(import_module(module),
                                                   widget)

                if field.field_function == 'EmailFirstName':
                    field_args["max_length"] = FIELD_FNAME_LENGTH
                elif field.field_function == 'EmailLastName':
                    field_args["max_length"] = FIELD_LNAME_LENGTH
                elif field.field_function == 'EmailFullName':
                    field_args["max_length"] = FIELD_NAME_LENGTH
                elif field.field_function == 'EmailPhoneNumber':
                    field_args["max_length"] = FIELD_PHONE_LENGTH

                form.fields[field_key] = field_class(**field_args)

                if not field_class == EmailVerificationField:
                    form.fields[field_key].widget.attrs['title'] = field.label
                    form.fields[field_key].widget.attrs[
                        'class'] = 'formforform-field'
                else:
                    form.fields[field_key].widget.widgets[0].attrs[
                        'class'] += ' formforform-field'
                    form.fields[field_key].widget.widgets[1].attrs[
                        'class'] += ' formforform-field'

                if form.fields[field_key].widget.__class__.__name__.lower(
                ) == 'selectdatewidget':
                    form.fields[field_key].widget.years = range(
                        1920, THIS_YEAR + 10)
Ejemplo n.º 52
0
 def get_browser_view_url(self):
     site_url = get_setting('site', 'global', 'siteurl')
     return "%s%s?key=%s" % (site_url,
                             reverse('newsletter.view_from_browser',
                                     args=[self.pk]), self.security_key)
Ejemplo n.º 53
0
 def notice_log(self):
     if self.notice_time == 'attimeof':
         return '--'
     return '<a href="%s%s?notice_id=%d">View logs</a>' % (get_setting('site', 'global', 'siteurl'),
                      reverse('corporate_membership.notice.log.search'), self.id)
Ejemplo n.º 54
0
def detail(request, slug=None, hash=None, template_name="articles/view.html"):
    if not slug and not hash:
        return HttpResponseRedirect(reverse('articles'))

    if hash:
        version = get_object_or_404(Version, hash=hash)
        current_article = get_object_or_404(Article, pk=version.object_id)
        article = version.get_version_object()
        msg_string = 'You are viewing a previous version of this article. View the <a href="%s%s">Current Version</a>.' % (get_setting('site', 'global', 'siteurl'), current_article.get_absolute_url())
        messages.add_message(request, messages.WARNING, _(msg_string))
    else:
        article = get_object_or_404(Article, slug=slug)

    # non-admin can not view the non-active content
    # status=0 has been taken care of in the has_perm function
    if (article.status_detail).lower() != 'active' and (not request.user.profile.is_superuser):
        raise Http403

    if not article.release_dt_local and article.release_dt:
        article.assign_release_dt_local()

    if not article.release_dt_local or article.release_dt_local >= datetime.now():
        if not any([
            has_perm(request.user, 'articles.view_article'),
            request.user == article.owner,
            request.user == article.creator
            ]):
            raise Http403

    if has_view_perm(request.user, 'articles.view_article', article):
        EventLog.objects.log(instance=article)
        return render_to_response(template_name, {'article': article},
            context_instance=RequestContext(request))
    else:
        raise Http403
Ejemplo n.º 55
0
    def __init__(self, *args, **kwargs):
        if 'user_this' in kwargs:
            self.user_this = kwargs.pop('user_this', None)
        else:
            self.user_this = None

        if 'user_current' in kwargs:
            self.user_current = kwargs.pop('user_current', None)
        else:
            self.user_current = None

        if 'required_fields_list' in kwargs:
            self.required_fields_list = kwargs.pop('required_fields_list', None)
        else:
            self.required_fields_list = None

        super(ProfileForm, self).__init__(*args, **kwargs)

        if self.user_this:
            self.fields['first_name'].initial = self.user_this.first_name
            self.fields['last_name'].initial = self.user_this.last_name
            self.fields['username'].initial = self.user_this.username
            self.fields['email'].initial = self.user_this.email

            if self.user_this.is_superuser:
                self.fields['security_level'].initial = "superuser"
            elif self.user_this.is_staff:
                self.fields['security_level'].initial = "staff"
            else:
                self.fields['security_level'].initial = "user"
            if self.user_this.is_active == 1:
                self.fields['interactive'].initial = 1
            else:
                self.fields['interactive'].initial = 0

            del self.fields['password1']
            del self.fields['password2']

            if not self.user_current.profile.is_superuser:
                del self.fields['admin_notes']
                del self.fields['security_level']
                del self.fields['status_detail']

            if self.user_current.profile.is_superuser and self.user_current == self.user_this:
                self.fields['security_level'].choices = (('superuser',_('Superuser')),)

        if not self.user_current.profile.is_superuser:
            if 'status_detail' in self.fields: self.fields.pop('status_detail')

        # we make first_name, last_name, email, username and password as required field regardless
        # the rest of fields will be decided by the setting - UsersRequiredFields
        if self.required_fields_list:
            for field in self.required_fields_list:
                for myfield in self.fields:
                    if field == self.fields[myfield].label:
                        self.fields[myfield].required = True
                        continue

        if 'password1' in self.fields:
            self.password_regex = (get_setting('module', 'users', 'password_requirements_regex')).strip()
            self.password_help_text = (get_setting('module', 'users', 'password_text')).strip()
            if not self.password_regex:
                self.password_regex = PASSWORD_REGEX_DEFAULT
                self.password_help_text = PASSWORD_HELP_TEXT_DEFAULT
            if not self.password_help_text:
                if self.fields['password1'].help_text:
                    self.password_help_text = self.fields['password1'].help_text
                else:
                    self.password_help_text = PASSWORD_HELP_TEXT_DEFAULT
            self.fields['password1'].help_text = self.password_help_text
Ejemplo n.º 56
0
    def authenticate(self, *args, **kwargs):
        """Authenticate user using social credentials

        Authentication is made if this is the correct backend, backend
        verification is made by kwargs inspection for current backend
        name presence.
        """
        # Validate backend and arguments. Require that the Social Auth
        # response be passed in as a keyword argument, to make sure we
        # don't match the username/password calling conventions of
        # authenticate.
        if not (self.name and kwargs.get(self.name) and 'response' in kwargs):
            return None

        response = kwargs.get('response')
        request = kwargs.get('request')
        details = self.get_user_details(response)
        uid = self.get_user_id(details, response)
        is_new = False
        try:
            social_user = UserSocialAuth.objects.select_related('user')\
                                                .get(provider=self.name,
                                                     uid=uid)
        except UserSocialAuth.DoesNotExist:
            user = kwargs.get('user')
            if user is None:  # new user
                if not CREATE_USERS:
                    return None

                email = details.get('email')
                if email and ASSOCIATE_BY_MAIL:
                    # try to associate accounts registered with the same email
                    # address, only if it's a single object. ValueError is
                    # raised if multiple objects are returned
                    try:
                        user = User.objects.get(email=email)
                    except MultipleObjectsReturned:
                        raise ValueError('Not unique email address supplied')
                    except User.DoesNotExist:
                        user = None
                if not user:
                    username = self.username(details)
                    user = User.objects.create_user(username=username,
                                                    email=email)
                    is_new = True
                    default_user_groups = [
                        g.strip() for g in (get_setting(
                            'module', 'users', 'defaultusergroup')).split(',')
                    ]
                    if default_user_groups:
                        from tendenci.apps.user_groups.models import Group, GroupMembership
                        from django.db.models import Q
                        for group_name in default_user_groups:
                            groups = Group.objects.filter(
                                Q(name=group_name)
                                | Q(label=group_name)).filter(
                                    allow_self_add=1,
                                    status=1,
                                    status_detail='active')
                            if groups:
                                group = groups[0]
                            else:
                                # group doesnot exist, so create the group
                                group = Group()
                                group.name = group_name
                                group.label = group_name
                                group.type = 'distribution'
                                group.show_as_option = 1
                                group.allow_self_add = 1
                                group.allow_self_remove = 1
                                group.creator = user
                                group.creator_username = user.username
                                group.owner = user
                                group.owner_username = user.username
                                try:
                                    group.save()
                                except:
                                    group = None

                            if group:
                                gm = GroupMembership()
                                gm.group = group
                                gm.member = user
                                gm.creator_id = user.id
                                gm.creator_username = user.username
                                gm.owner_id = user.id
                                gm.owner_username = user.username
                                gm.save()
                    log_defaults = {
                        'event_id':
                        121000,
                        'event_data':
                        '%s (%d) self added by form' %
                        (user._meta.object_name, user.pk),
                        'description':
                        '%s self added' % user._meta.object_name,
                        'user':
                        user,
                        'request':
                        request,
                        'instance':
                        user,
                    }
                    EventLog.objects.log(**log_defaults)
            social_user = self.associate_auth(user, uid, response, details)
        else:
            # This account was registered to another user, so we raise an
            # error in such case and the view should decide what to do on
            # at this moment, merging account is not an option because that
            # would imply update user references on other apps, that's too
            # much intrusive
            if 'user' in kwargs and kwargs['user'] != social_user.user:
                raise ValueError('Account already in use.', social_user)
            user = social_user.user

        # Update user account data.
        self.update_user_details(user, response, details, is_new)

        # Update extra_data storage, unless disabled by setting
        if LOAD_EXTRA_DATA:
            extra_data = self.extra_data(user, uid, response, details)
            if extra_data and social_user.extra_data != extra_data:
                social_user.extra_data = extra_data
                social_user.save()

        return user
Ejemplo n.º 57
0
    def send_newsletter(self, newsletter_id, **kwargs):
        from tendenci.apps.emails.models import Email
        from tendenci.apps.newsletters.models import Newsletter
        from tendenci.apps.site_settings.utils import get_setting
        from tendenci.apps.base.utils import validate_email

        from tendenci.apps.newsletters.utils import get_newsletter_connection

        connection = get_newsletter_connection()
        if not connection:
            print(
                'Exiting..Please set up your newsletter email provider before proceeding.'
            )
            return

        print "Started sending newsletter..."

        if newsletter_id == 0:
            raise CommandError(
                'Newsletter ID is required. Usage: ./manage.py send_newsletter <newsletter_id>'
            )

        newsletter = Newsletter.objects.filter(pk=int(newsletter_id))
        if newsletter.exists():
            newsletter = newsletter[0]
        else:
            newsletter = None

        if not newsletter:
            raise CommandError(
                'You are trying to send a newsletter that does not exist.')

        if newsletter.send_status == 'queued':
            newsletter.send_status = 'sending'

        elif newsletter.send_status == 'sent':
            newsletter.send_status = 'resending'

        elif newsletter.send_status == 'resent':
            newsletter.send_status == 'resending'

        newsletter.save()

        recipients = newsletter.get_recipients()
        email = newsletter.email
        # replace relative to absolute urls
        self.site_url = get_setting('site', 'global', 'siteurl')
        email.body = email.body.replace("src=\"/", "src=\"%s/" % self.site_url)
        email.body = email.body.replace("href=\"/",
                                        "href=\"%s/" % self.site_url)

        counter = 0
        for recipient in recipients:
            # skip if not a valid email address
            if not validate_email(recipient.member.email):
                continue

            subject = email.subject
            body = email.body

            if '[firstname]' in subject:
                subject = subject.replace('[firstname]',
                                          recipient.member.first_name)

            if '[lastname]' in subject:
                subject = subject.replace('[lastname]',
                                          recipient.member.last_name)

            if '[username]' in body:
                body = body.replace('[username]', recipient.member.username)

            if '[firstname]' in body:
                body = body.replace('[firstname]', recipient.member.first_name)

            if '[unsubscribe_url]' in body:
                #body = body.replace('[unsubscribe_url]', recipient.noninteractive_unsubscribe_url)
                # The unsubscribe_url link should be something like <a href="[unsubscribe_url]">Unsubscribe</a>.
                # But it can be messed up sometimes. Let's prevent that from happening.
                p = r'(href=\")([^\"]*)(\[unsubscribe_url\])(\")'
                body = re.sub(
                    p,
                    r'\1' + recipient.noninteractive_unsubscribe_url + r'\4',
                    body)

            if '[browser_view_url]' in body:
                body = body.replace('[browser_view_url]',
                                    newsletter.get_browser_view_url())

            email_to_send = Email(subject=subject,
                                  body=body,
                                  sender=email.sender,
                                  sender_display=email.sender_display,
                                  reply_to=email.reply_to,
                                  recipient=recipient.member.email)
            print "Sending to %s" % recipient.member.email
            email_to_send.send(connection=connection)
            counter += 1
            print "Newsletter sent to %s" % recipient.member.email

            if newsletter.send_to_email2 and hasattr(recipient.member, 'profile') \
                and validate_email(recipient.member.profile.email2):
                email_to_send.recipient = recipient.member.profile.email2
                email_to_send.send(connection=connection)
                counter += 1
                print "Newsletter sent to %s" % recipient.member.profile.email2

        if newsletter.send_status == 'sending':
            newsletter.send_status = 'sent'
            newsletter.date_email_sent = datetime.datetime.now()

        elif newsletter.send_status == 'resending':
            newsletter.send_status = 'resent'
            newsletter.date_last_resent = datetime.datetime.now()
            if not newsletter.resend_count:
                newsletter.resend_count = 0
            newsletter.resend_count += 1

        newsletter.email_sent_count = counter

        newsletter.save()

        print "Successfully sent %s newsletter emails." % counter

        print "Sending confirmation message to creator..."
        # send confirmation email
        subject = "Newsletter Submission Recap for %s" % newsletter.email.subject
        detail_url = get_setting('site', 'global',
                                 'siteurl') + newsletter.get_absolute_url()
        params = {
            'first_name': newsletter.email.creator.first_name,
            'subject': newsletter.email.subject,
            'count': counter,
            'detail_url': detail_url
        }

        body = render_to_string('newsletters/newsletter_sent_email_body.html',
                                params)

        email = Email(recipient=newsletter.email.sender,
                      subject=subject,
                      body=body)

        email.send(connection=connection)

        print "Confirmation email sent."

        # add cache clear to resolve issue
        # TODO: cache clear only to specifies
        cache.clear()
        print 'Cache cleared!'
Ejemplo n.º 58
0
    def render(self, context):
        query = u''
        user = AnonymousUser()
        limit = None
        order = '-join_dt'
        randomize = False
        renewed_only = False
        exclude_expired = False

        allow_anonymous_search = get_setting(
            'module', 'corporate_memberships',
            'anonymoussearchcorporatemembers')
        allow_member_search = get_setting('module', 'corporate_memberships',
                                          'membersearchcorporatemembers')
        allow_member_search = allow_member_search or allow_anonymous_search

        if 'random' in self.kwargs:
            randomize = bool(self.kwargs['random'])

        if 'user' in self.kwargs:
            try:
                user = Variable(self.kwargs['user'])
                user = user.resolve(context)
            except:
                user = self.kwargs['user']
                if user == "anon" or user == "anonymous":
                    user = AnonymousUser()
        else:
            # check the context for an already existing user
            # and see if it is really a user object
            if 'user' in context:
                if isinstance(context['user'], User):
                    user = context['user']

        if 'limit' in self.kwargs:
            try:
                limit = Variable(self.kwargs['limit'])
                limit = int(limit.resolve(context))
            except:
                limit = None

        if 'query' in self.kwargs:
            try:
                query = Variable(self.kwargs['query'])
                query = query.resolve(context)
            except:
                query = self.kwargs['query']  # context string

        if 'order' in self.kwargs:
            try:
                order = Variable(self.kwargs['order'])
                order = order.resolve(context)
            except:
                order = self.kwargs['order']

        if 'renewed_only' in self.kwargs:
            renewed_only = bool(self.kwargs['renewed_only'])

        if 'exclude_expired' in self.kwargs:
            exclude_expired = bool(self.kwargs['exclude_expired'])

        items = CorpMembership.objects.exclude(status_detail='archive')
        if not allow_anonymous_search:
            if user.is_authenticated:
                if not user.profile.is_superuser:
                    if user.profile.is_member and allow_member_search:
                        items = items.distinct()
                    else:
                        items = items.none()
            else:
                items = items.none()

        items = self.custom_model_filter(items, user)

        objects = []

        if renewed_only:
            items = items.filter(renewal=True)

        if exclude_expired:
            items = items.exclude(status_detail='expired')

        # if order is not specified it sorts by relevance
        if order:
            if order == 'corp_profile__name':
                items = items.order_by(Lower(order))
            else:
                items = items.order_by(order)

        if items.count() > 0:
            if randomize:
                if limit:
                    num_to_show = min(items.count(), limit)
                else:
                    num_to_show = items.count()
                objects = random.sample(list(items), num_to_show)
            else:
                objects = items[:limit]

        context[self.context_var] = objects
        return ""
Ejemplo n.º 59
0
def template_edit(request,
                  template_id,
                  form_class=TemplateForm,
                  template_name='campaign_monitor/templates/edit.html'):

    template = get_object_or_404(Template, template_id=template_id)

    if not has_perm(request.user, 'campaign_monitor.change_template',
                    template):
        raise Http403

    if request.method == "POST":
        form = form_class(request.POST, request.FILES, instance=template)
        if form.is_valid():

            #save template to generate urls
            template = form.save()

            #set up urls
            site_url = get_setting('site', 'global', 'siteurl')

            if hasattr(settings, 'USE_S3_STORAGE') and settings.USE_S3_STORAGE:
                html_url = template.html_file.url
            else:
                html_url = str("%s%s" % (site_url, template.get_html_url()))

            if template.zip_file:
                if hasattr(settings,
                           'USE_S3_STORAGE') and settings.USE_S3_STORAGE:
                    zip_url = template.get_zip_url()
                else:
                    zip_url = "%s%s" % (site_url, template.get_zip_url())
            else:
                zip_url = ""

            #sync with campaign monitor
            try:
                t = CST(auth=auth, template_id=form.instance.template_id)
                t.update(str(template.name), html_url, zip_url)
            except BadRequest as e:
                msg_string = 'Bad Request %s: %s' % (e.data.Code,
                                                     e.data.Message)
                messages.add_message(request, messages.ERROR, _(msg_string))
                return render_to_resp(request=request,
                                      template_name=template_name,
                                      context={'form': form})
            except Exception as e:
                msg_string = 'Error: %s' % e
                messages.add_message(request, messages.ERROR, _(msg_string))
                return render_to_resp(request=request,
                                      template_name=template_name,
                                      context={'form': form})

            #get campaign monitor details
            t = t.details()
            template.name = t.Name
            template.cm_preview_url = t.PreviewURL
            template.cm_screenshot_url = t.ScreenshotURL
            template.save()

            #extract and serve files in zip
            extract_files(template)
            msg_string = 'Successfully updated Template : %s' % template.template_id
            messages.add_message(request, messages.SUCCESS, _(msg_string))

            return redirect(template)

    else:
        form = form_class(instance=template)

    return render_to_resp(request=request,
                          template_name=template_name,
                          context={'form': form})
Ejemplo n.º 60
0
def campaign_generate(request,
                      form_class=CampaignForm,
                      template_name='campaign_monitor/campaigns/add.html'):
    if not has_perm(request.user, 'campaign_monitor.add_campaign'):
        raise Http403

    if request.method == 'POST':
        form = form_class(request.POST)
        if form.is_valid():
            template = form.cleaned_data['template']

            #set up urls
            site_url = get_setting('site', 'global', 'siteurl')
            html_url = str("%s%s" % (site_url, template.get_html_url()))
            html_url += "?jump_links=%s" % form.cleaned_data.get('jump_links')
            try:
                html_url += "&events=%s" % form.cleaned_data.get('events')
                html_url += "&events_type=%s" % form.cleaned_data.get(
                    'events_type')
                html_url += "&event_start_dt=%s" % form.cleaned_data.get(
                    'event_start_dt', '')
                html_url += "&event_end_dt=%s" % form.cleaned_data.get(
                    'event_end_dt', '')
            except ImportError:
                pass
            html_url += "&articles=%s" % form.cleaned_data.get('articles')
            html_url += "&articles_days=%s" % form.cleaned_data.get(
                'articles_days')
            html_url += "&news=%s" % form.cleaned_data.get('news')
            html_url += "&news_days=%s" % form.cleaned_data.get('news_days')
            html_url += "&jobs=%s" % form.cleaned_data.get('jobs')
            html_url += "&jobs_days=%s" % form.cleaned_data.get('jobs_days')
            html_url += "&pages=%s" % form.cleaned_data.get('pages')
            html_url += "&pages_days=%s" % form.cleaned_data.get('pages_days')

            if template.zip_file:
                if hasattr(settings,
                           'USE_S3_STORAGE') and settings.USE_S3_STORAGE:
                    zip_url = str(template.get_zip_url())
                else:
                    zip_url = str("%s%s" % (site_url, template.get_zip_url()))
            else:
                zip_url = str()

            #sync with campaign monitor
            try:
                t = CST(auth=auth, template_id=template.template_id)
                t.update(str(template.name), html_url, zip_url)
            except BadRequest as e:
                messages.add_message(
                    request, messages.ERROR,
                    'Bad Request %s: %s' % (e.data.Code, e.data.Message))
                return redirect('campaign_monitor.campaign_generate')
            except Exception as e:
                messages.add_message(request, messages.ERROR, 'Error: %s' % e)
                return redirect('campaign_monitor.campaign_generate')
            return redirect("%s/campaign/create/new" %
                            settings.CAMPAIGNMONITOR_URL)

    else:
        form = form_class()

    return render_to_resp(request=request,
                          template_name=template_name,
                          context={'form': form})