def delete(request, id, template_name="resumes/delete.html"): resume = get_object_or_404(Resume, pk=id) if has_perm(request.user,'resumes.delete_resume'): if request.method == "POST": log_defaults = { 'event_id' : 433000, 'event_data': '%s (%d) deleted by %s' % (resume._meta.object_name, resume.pk, request.user), 'description': '%s deleted' % resume._meta.object_name, 'user': request.user, 'request': request, 'instance': resume, } EventLog.objects.log(**log_defaults) messages.add_message(request, messages.SUCCESS, 'Successfully deleted %s' % 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_deleted', extra_context) resume.delete() return HttpResponseRedirect(reverse('resume.search')) return render_to_response(template_name, {'resume': resume}, context_instance=RequestContext(request)) else: raise Http403
def group_delete(request, id, template_name="user_groups/delete.html"): group = get_object_or_404(Group, pk=id) if not has_perm(request.user,'user_groups.delete_group',group): raise Http403 if request.method == "POST": # send notification to administrators recipients = get_notice_recipients('module', 'groups', 'grouprecipients') if recipients: if notification: extra_context = { 'object': group, 'request': request, } notification.send_emails(recipients,'group_deleted', extra_context) log_defaults = { 'event_id' : 163000, 'event_data': '%s (%d) deleted by %s' % (group._meta.object_name, group.pk, request.user), 'description': '%s deleted' % group._meta.object_name, 'user': request.user, 'request': request, 'instance': group, } EventLog.objects.log(**log_defaults) group.delete() return HttpResponseRedirect(reverse('group.search')) return render_to_response(template_name, {'group':group}, context_instance=RequestContext(request))
def delete(request, id, template_name="news/delete.html"): news = get_object_or_404(News, pk=id) # check permission if not has_perm(request.user, "news.delete_news"): raise Http403 if request.method == "POST": log_defaults = { "event_id": 305300, "event_data": "%s (%d) deleted by %s" % (news._meta.object_name, news.pk, request.user), "description": "%s deleted" % news._meta.object_name, "user": request.user, "request": request, "instance": news, } EventLog.objects.log(**log_defaults) messages.add_message(request, messages.SUCCESS, "Successfully deleted %s" % news) # send notification to administrators recipients = get_notice_recipients("module", "news", "newsrecipients") if recipients: if notification: extra_context = {"object": news, "request": request} notification.send_emails(recipients, "news_deleted", extra_context) news.delete() return HttpResponseRedirect(reverse("news.search")) return render_to_response(template_name, {"news": news}, context_instance=RequestContext(request))
def send_notifications(scope, scope_category, name, label, extra_context=None): """ a small wrapper for sending notification emails to recipients specified in site_settings. """ recipients = get_notice_recipients(scope, scope_category, name) if recipients: send_emails(recipients, label, extra_context)
def send_email_notification(notice_name, recipients, extra_context): """ Send email notice specified by the notice_name to the recipients. recipients - a list of emails """ try: from notification import models as notification except: notification = None if notification and recipients: notification.send_emails(recipients, notice_name, extra_context)
def add(request, form_class=ResumeForm, template_name="resumes/add.html"): can_add_active = has_perm(request.user, 'resumes.add_resume') if request.method == "POST": form = form_class(request.POST, 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 = 0 resume.status_detail = 'pending' # set up the expiration time based on requested duration now = now_localized() resume.expiration_dt = now + timedelta(days=resume.requested_duration) resume = update_perms_and_save(request, form, resume) log_defaults = { 'event_id' : 351000, 'event_data': '%s (%d) added by %s' % (resume._meta.object_name, resume.pk, request.user), 'description': '%s added' % resume._meta.object_name, 'user': request.user, 'request': request, 'instance': resume, } EventLog.objects.log(**log_defaults) if request.user.is_authenticated(): messages.add_message(request, messages.SUCCESS, 'Successfully added %s' % 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))
def auto_update_paid_object(self, request, payment): """ Update the object after online payment is received. """ from datetime import datetime try: from notification import models as notification except: notification = None from perms.utils import get_notice_recipients from events.utils import email_admins site_label = get_setting('site', 'global', 'sitedisplayname') site_url = get_setting('site', 'global', 'siteurl') self_reg8n = get_setting('module', 'users', 'selfregistration') payment_attempts = self.invoice.payment_set.count() registrants = self.registrant_set.all().order_by('id') for registrant in registrants: #registrant.assign_mapped_fields() if registrant.custom_reg_form_entry: registrant.name = registrant.custom_reg_form_entry.__unicode__() else: registrant.name = ' '.join([registrant.first_name, registrant.last_name]) # only send email on success! or first fail if payment.is_paid or payment_attempts <= 1: notification.send_emails( [self.registrant.email], # recipient(s) 'event_registration_confirmation', # template { 'site_label': site_label, 'site_url': site_url, 'self_reg8n': self_reg8n, 'reg8n': self, 'registrants': registrants, 'event': self.event, 'price': self.invoice.total, 'is_paid': payment.is_paid, }, True, # notice saved in db ) #notify the admins too email_admins(self.event, self.invoice.total, self_reg8n, self, registrants)
def request_new(request, template_name="help_files/request_new.html"): "Request new file form" if request.method == "POST": form = RequestForm(request.POST) if form.is_valid(): instance = form.save() # send notification to administrators recipients = get_notice_recipients("module", "help_files", "helpfilerecipients") if recipients: if notification: extra_context = {"object": instance, "request": request} notification.send_emails(recipients, "help_file_requested", extra_context) messages.add_message(request, messages.INFO, "Thanks for requesting a new help file!") return HttpResponseRedirect(reverse("help_files")) else: form = RequestForm() return render_to_response(template_name, {"form": form}, context_instance=RequestContext(request))
def save_model(self, request, object, form, change): instance = form.save(commit=False) instance = update_perms_and_save(request, form, instance) # notifications if not is_admin(request.user): # send notification to administrators recipients = get_notice_recipients('module', 'pages', 'pagerecipients') notice_type = 'page_added' if change: notice_type = 'page_edited' if recipients: if notification: extra_context = { 'object': instance, 'request': request, } notification.send_emails(recipients, notice_type, extra_context) return instance # admin.site.register(Page, PageAdmin)
def add(request, form_class=NewsForm, template_name="news/add.html"): # check permission if not has_perm(request.user, "news.add_news"): raise Http403 if request.method == "POST": form = form_class(request.POST, user=request.user) if form.is_valid(): news = form.save(commit=False) # update all permissions and save the model news = update_perms_and_save(request, form, news) log_defaults = { "event_id": 305100, "event_data": "%s (%d) added by %s" % (news._meta.object_name, news.pk, request.user), "description": "%s added" % news._meta.object_name, "user": request.user, "request": request, "instance": news, } EventLog.objects.log(**log_defaults) messages.add_message(request, messages.SUCCESS, "Successfully added %s" % news) # send notification to administrators recipients = get_notice_recipients("module", "news", "newsrecipients") if recipients: if notification: extra_context = {"object": news, "request": request} notification.send_emails(recipients, "news_added", extra_context) return HttpResponseRedirect(reverse("news.view", args=[news.slug])) else: form = form_class(user=request.user) return render_to_response(template_name, {"form": form}, context_instance=RequestContext(request))
def add(request, form_class=ArticleForm, template_name="articles/add.html"): if has_perm(request.user,'articles.add_article'): if request.method == "POST": form = form_class(request.POST, user=request.user) if form.is_valid(): article = form.save(commit=False) # add all permissions and save the model articles = update_perms_and_save(request, form, article) log_defaults = { 'event_id' : 431000, 'event_data': '%s (%d) added by %s' % (article._meta.object_name, article.pk, request.user), 'description': '%s added' % article._meta.object_name, 'user': request.user, 'request': request, 'instance': article, } EventLog.objects.log(**log_defaults) messages.add_message(request, messages.SUCCESS, 'Successfully added %s' % article) # send notification to administrator(s) and module recipient(s) recipients = get_notice_recipients('module', 'articles', 'articlerecipients') if recipients and notification: notification.send_emails(recipients,'article_added', { 'object': article, 'request': request, }) return HttpResponseRedirect(reverse('article', args=[article.slug])) else: form = form_class(user=request.user) return render_to_response(template_name, {'form':form}, context_instance=RequestContext(request)) else: raise Http403
def email_admins(event, event_price, self_reg8n, reg8n, registrants): site_label = get_setting('site', 'global', 'sitedisplayname') site_url = get_setting('site', 'global', 'siteurl') admins = get_setting('module', 'events', 'admin_emails').split(',') email_list = [admin.strip() for admin in admins] notification.send_emails( email_list, 'event_registration_confirmation', { 'SITE_GLOBAL_SITEDISPLAYNAME': site_label, 'SITE_GLOBAL_SITEURL': site_url, 'self_reg8n': self_reg8n, 'reg8n': reg8n, 'registrants': registrants, 'event': event, 'price': event_price, 'is_paid': reg8n.invoice.balance == 0, 'reg8n_number': reg8n.registrant_set.all().count(), 'for_admin': True, }, True, # save notice in db )
def send_registrant_email(reg8n, self_reg8n): """ Email registrant about his/her registration """ site_label = get_setting('site', 'global', 'sitedisplayname') site_url = get_setting('site', 'global', 'siteurl') primary_registrant = reg8n.registrant if primary_registrant and primary_registrant.email: notification.send_emails( [primary_registrant.email], 'event_registration_confirmation', { 'SITE_GLOBAL_SITEDISPLAYNAME': site_label, 'SITE_GLOBAL_SITEURL': site_url, 'self_reg8n': self_reg8n, 'reg8n': reg8n, 'event': reg8n.event, 'price': reg8n.amount_paid, 'is_paid': reg8n.invoice.balance == 0 }, True, # save notice in db )
def group_add_edit(request, group_slug=None, form_class=GroupForm, template_name="user_groups/add_edit.html"): add, edit = False, False if group_slug: group = get_object_or_404(Group, slug=group_slug) if not has_perm(request.user,'user_groups.change_group',group): raise Http403 title = "Edit Group" edit = True else: group = None if not has_perm(request.user,'user_groups.add_group'):raise Http403 title = "Add Group" add = True if request.method == 'POST': if edit: form = form_class(request.POST, instance=group, user=request.user) else: form = form_class(request.POST, user=request.user) if form.is_valid(): group = form.save(commit=False) if not group.id: group.creator = request.user group.creator_username = request.user.username # set up user permission group.allow_user_view, group.allow_user_edit = form.cleaned_data['user_perms'] group.owner = request.user group.owner_username = request.user.username group = form.save() if add: # send notification to administrators recipients = get_notice_recipients('module', 'groups', 'grouprecipients') if recipients: if notification: extra_context = { 'object': group, 'request': request, } notification.send_emails(recipients,'group_added', extra_context) log_defaults = { 'event_id' : 161000, 'event_data': '%s (%d) added by %s' % (group._meta.object_name, group.pk, request.user), 'description': '%s added' % group._meta.object_name, 'user': request.user, 'request': request, 'instance': group, } EventLog.objects.log(**log_defaults) if edit: log_defaults = { 'event_id' : 162000, 'event_data': '%s (%d) edited by %s' % (group._meta.object_name, group.pk, request.user), 'description': '%s edited' % group._meta.object_name, 'user': request.user, 'request': request, 'instance': group, } EventLog.objects.log(**log_defaults) return HttpResponseRedirect(group.get_absolute_url()) else: if edit: form = form_class(instance=group, user=request.user) else: form = form_class(user=request.user) return render_to_response(template_name, {'form':form, 'titie':title, 'group':group}, context_instance=RequestContext(request))
def application_entries(request, id=None, template_name="memberships/entries/details.html"): """ Displays the details of a membership application entry. """ if not id: return redirect(reverse('membership.application_entries_search')) entry = get_object_or_404(AppEntry, id=id) if not entry.allow_view_by(request.user): raise Http403 # log entry view EventLog.objects.log(**{ 'event_id' : 1085000, 'event_data': '%s (%d) viewed by %s' % (entry._meta.object_name, entry.pk, request.user), 'description': '%s viewed' % entry._meta.object_name, 'user': request.user, 'request': request, 'instance': entry, }) if request.method == "POST": form = MemberApproveForm(entry, request.POST) if form.is_valid(): membership_total = Membership.objects.filter(status=True, status_detail='active').count() status = request.POST.get('status', '') approve = (status.lower() == 'approve') or (status.lower() == 'approve renewal') entry.judge = request.user if approve: user_pk = int(form.cleaned_data['users']) if user_pk: entry.user = User.objects.get(pk=user_pk) else: entry.user = User.objects.create_user(**{ 'username': entry.spawn_username(entry.first_name, entry.last_name), 'email': entry.email, 'password': hashlib.sha1(entry.email).hexdigest()[:6] }) from django.core.mail import send_mail from django.utils.http import int_to_base36 from django.contrib.auth.tokens import default_token_generator from site_settings.utils import get_setting token_generator = default_token_generator site_url = get_setting('site', 'global', 'siteurl') site_name = get_setting('site', 'global', 'sitedisplayname') # send new user account welcome email (notification) notification.send_emails([entry.user.email],'user_welcome', { 'site_url': site_url, 'site_name': site_name, 'uid': int_to_base36(entry.user.id), 'user': entry.user, 'username': entry.user.username, 'token': token_generator.make_token(entry.user), }) # update application, user, # group, membership, and archive entry.approve() # silence old memberships within renewal period Membership.objects.silence_old_memberships(entry.user) # execute field functions (group subscriptions) entry.execute_field_functions() # send "approved" notification Notice.send_notice( request=request, entry=entry, emails=entry.email, notice_type='approve', membership=entry.membership, membership_type=entry.membership_type, ) # log entry approved EventLog.objects.log(**{ 'event_id' : 1085000, 'event_data': '%s (%d) approved by %s' % (entry._meta.object_name, entry.pk, request.user), 'description': '%s approved' % entry._meta.object_name, 'user': request.user, 'request': request, 'instance': entry, }) else: # if not approved entry.disapprove() # send "disapproved" notification Notice.send_notice( entry = entry, request = request, emails=entry.email, notice_type='disapprove', membership_type=entry.membership_type, ) # log entry disapproved EventLog.objects.log(**{ 'event_id' : 1082102, 'event_data': '%s (%d) disapproved by %s' % (entry._meta.object_name, entry.pk, request.user), 'description': '%s disapproved' % entry._meta.object_name, 'user': request.user, 'request': request, 'instance': entry, }) return redirect(reverse('membership.application_entries', args=[entry.pk])) else: # if request != POST form = MemberApproveForm(entry) return render_to_response(template_name, { 'entry': entry, 'form': form, }, context_instance=RequestContext(request))
def application_details(request, slug=None, cmb_id=None, imv_id=0, imv_guid=None, secret_hash="", membership_id=0, template_name="memberships/applications/details.html"): """ Display a built membership application and handle submission. """ if not slug: raise Http404 user = request.user app = get_object_or_404(App, slug=slug) if not app.allow_view_by(user): raise Http403 # if this app is for corporation individuals, redirect them to corp-pre page if # they have not passed the security check. is_corp_ind = False corporate_membership = None if hasattr(app, 'corp_app') and app.corp_app: if not cmb_id: # redirect them to the corp_pre page return redirect(reverse('membership.application_details_corp_pre', args=[app.slug])) is_corp_ind = True corporate_membership = get_object_or_404(CorporateMembership, id=cmb_id) # check if they have verified their email or entered the secret code is_verified = False if is_admin(request.user) or app.corp_app.authentication_method == 'admin': is_verified = True elif app.corp_app.authentication_method == 'email': try: indiv_veri = IndivMembEmailVeri8n.objects.get(pk=imv_id, guid=imv_guid) if indiv_veri.verified: is_verified = True except IndivMembEmailVeri8n.DoesNotExist: pass elif app.corp_app.authentication_method == 'secret_code': tmp_secret_hash = md5('%s%s' % (corporate_membership.secret_code, request.session.get('corp_hash_random_string', ''))).hexdigest() if secret_hash == tmp_secret_hash: is_verified = True if not is_verified: return redirect(reverse('membership.application_details_corp_pre', args=[slug])) # log application details view EventLog.objects.log(**{ 'event_id' : 655000, 'event_data': '%s (%d) viewed by %s' % (app._meta.object_name, app.pk, user), 'description': '%s viewed' % app._meta.object_name, 'user': user, 'request': request, 'instance': app, }) initial_dict = {} if hasattr(user, 'memberships'): membership = user.memberships.get_membership() is_only_a_member = [ is_developer(user) == False, is_admin(user) == False, is_member(user) == True, ] if corporate_membership: # exclude corp. reps, creator and owner - they should be able to add new is_only_a_member.append(corporate_membership.allow_edit_by(user)==False) # deny access to renew memberships if all(is_only_a_member): initial_dict = membership.get_app_initial(app) if not membership.can_renew(): return render_to_response("memberships/applications/no-renew.html", { "app": app, "user":user, "membership": membership}, context_instance=RequestContext(request)) pending_entries = [] if hasattr(user, 'appentry_set'): pending_entries = user.appentry_set.filter( is_approved__isnull = True, # pending ) # if an application entry was submitted # after your current membership was created if user.memberships.get_membership(): pending_entries.filter( entry_time__gte = user.memberships.get_membership().subscribe_dt ) app_entry_form = AppEntryForm( app, request.POST or None, request.FILES or None, user=user, corporate_membership=corporate_membership, initial=initial_dict, ) if request.method == "POST": if app_entry_form.is_valid(): entry = app_entry_form.save(commit=False) entry_invoice = entry.save_invoice() if user.is_authenticated(): entry.user = user entry.is_renewal = all(is_only_a_member) # add all permissions and save the model entry = update_perms_and_save(request, app_entry_form, entry) # administrators go to approve/disapprove page if is_admin(user): return redirect(reverse('membership.application_entries', args=[entry.pk])) # send "joined" notification Notice.send_notice( entry=entry, request = request, emails=entry.email, notice_type='join', membership_type=entry.membership_type, ) if entry_invoice.total == 0: if not entry_invoice.is_tendered: entry_invoice.tender(request.user) # online payment if entry_invoice.total>0 and entry.payment_method and entry.payment_method.is_online: return HttpResponseRedirect(reverse( 'payments.views.pay_online', args=[entry_invoice.pk, entry_invoice.guid] )) if not entry.approval_required(): entry.approve() # silence old memberships within renewal period Membership.objects.silence_old_memberships(entry.user) # get user from the membership since it's null in the entry entry.user = entry.membership.user membership_total = Membership.objects.filter(status=True, status_detail='active').count() # send "approved" notification Notice.send_notice( request = request, emails=entry.email, notice_type='approve', membership=entry.membership, membership_type=entry.membership_type, ) if not user.is_authenticated(): from django.core.mail import send_mail from django.utils.http import int_to_base36 from django.contrib.auth.tokens import default_token_generator from site_settings.utils import get_setting token_generator = default_token_generator site_url = get_setting('site', 'global', 'siteurl') site_name = get_setting('site', 'global', 'sitedisplayname') # send new user account welcome email (notification) notification.send_emails([entry.user.email],'user_welcome', { 'site_url': site_url, 'site_name': site_name, 'uid': int_to_base36(entry.user.id), 'user': entry.user, 'username': entry.user.username, 'token': token_generator.make_token(entry.user), }) # log - entry approval EventLog.objects.log(**{ 'event_id' : 1082101, 'event_data': '%s (%d) approved by %s' % (entry._meta.object_name, entry.pk, entry.judge), 'description': '%s viewed' % entry._meta.object_name, 'user': user, 'request': request, 'instance': entry, }) # log - entry submission EventLog.objects.log(**{ 'event_id' : 1081000, 'event_data': '%s (%d) submitted by %s' % (entry._meta.object_name, entry.pk, request.user), 'description': '%s viewed' % entry._meta.object_name, 'user': user, 'request': request, 'instance': entry, }) return redirect(entry.confirmation_url) return render_to_response(template_name, { 'app': app, 'app_entry_form': app_entry_form, 'pending_entries': pending_entries, }, context_instance=RequestContext(request))
def distribute_newsletter_v2(action, request=None, **kwargs): from django.template.loader import render_to_string from django.template import RequestContext from django.core import mail if not request: from site_settings.context_processors import settings extra_contexts = settings(None) context_instance = None else: extra_contexts = {} context_instance = RequestContext(request) extra_contexts.update({'action': action}) connection = mail.get_connection() if action.status_detail == 'open': if action.group: # update the status_detail first action.submit_dt = datetime.datetime.now() action.status_detail = 'inprogress' action.start_dt = datetime.datetime.now() action.save() # save the recap ar = ActionRecap() ar.action = action ar.start_dt = action.start_dt ar.save() i = 0 result_d = {'total': 0, 'total_success':0, 'total_failed':0, 'total_nomail':0} recap_d = [] # the result will be stored in the action_recap table email_subject = action.email.subject email_body = action.email.body no_reply_email = get_setting('site', 'global', 'siteemailnoreplyaddress') # if there is [password], replace here password_txt = render_to_string('newsletters/password.txt', extra_contexts, context_instance=context_instance) # turn relative links to absolute links site_url = get_setting('site', 'global', 'siteurl') email_body = email_relativeReftoFQDN(email_body, site_url) if action.email.content_type == 'text': email_body = htmltotext(email_body) else: # verify if we have the <html> and <body> tags email_body = verify_basic_html(email_subject, email_body) # remove </body> and </html> - need to append footer to body email_body = email_body.replace('</body>', '') email_body = email_body.replace('</html>', '') connection.open() for user_this in action.group.members.all().order_by('email'): result_d['total'] += 1 direct_mail = (user_this.get_profile()).direct_mail # if this user opted to not receiving email, skip it # but do store his info in the recap_d if not direct_mail: recap_d.append({'direct_mail':direct_mail, 'first_name':user_this.first_name, 'last_name':user_this.last_name, 'email':user_this.email, 'id':user_this.id, 'notes':'not delivered - user does not receive email'}) result_d['total_nomail'] += 1 continue if i > 0 and i % EMAILS_PER_CONNECTION == 0: # make a new connection connection.close() connection.open() # save the recap during process ar.recap = cPickle.dumps(recap_d) ar.sent = result_d['total_success'] ar.attempted = result_d['total'] ar.failed = result_d['total_failed']+ result_d['total_nomail'] ar.save() i += 1 profile_this = user_this.get_profile() user_this.password = password_txt subject = customize_subject(email_subject, user_this, profile_this) body = customize_body(email_body, user_this, profile_this) if action.email.content_type <> 'text': action.email.content_type = 'html' footer_template = 'newsletters/footer.html' else: footer_template = 'newsletters/footer.txt' extra_contexts.update({'user_this': user_this}) footer = render_to_string(footer_template, extra_contexts, context_instance=context_instance) # append footer to the body body += footer if action.email.content_type == 'html': body += "</body></html>" recipient = [user_this.email] if action.send_to_email2: recipient.append(user_this.get_profile().email2) email = mail.EmailMessage(subject, body, no_reply_email, recipient, headers={'Reply-To':action.email.sender}, connection=connection) email.content_subtype= action.email.content_type boo = email.send() # send the e-mail myrecap = {'direct_mail' :direct_mail, 'first_name':user_this.first_name, 'last_name':user_this.last_name, 'email':user_this.email, 'email2':profile_this.email2, 'username':user_this.username, 'id':user_this.id} if boo: result_d['total_success'] += 1 myrecap['notes'] = 'sent' else: result_d['total_failed'] += 1 myrecap['notes'] = 'bad address or e-mail blocked' recap_d.append(myrecap) #connection.close() # update the status action.status_detail = 'closed' action.sent = result_d['total_success'] action.attempted = result_d['total'] action.failed = result_d['total_failed']+ result_d['total_nomail'] action.finish_dt = datetime.datetime.now() action.save() # save the recap ar.recap = cPickle.dumps(recap_d) ar.finish_dt = action.finish_dt ar.sent = action.sent ar.attempted = action.attempted ar.failed = action.failed ar.save() # clear the recap_d recap_d = None # log an event log_defaults = { 'event_id' : 301100, 'event_data': """<b>Actionid: </b><a href="%s">%d</a>,<br /> <b>Action name: </b> %s,<br /> <b>Action type: </b> %s,<br /> <b>Category: </b> marketing,<br /> <b>Description: </b> %s,<br /> <b>Distributed to %d users part of user group: </b>%s.<br /> """ % (reverse('action.view', args=[action.id]), action.id, action.name, action.type, action.description, action.sent, action.group.name), 'description': '%s newsletter sent' % action._meta.object_name, 'user': action.owner, 'instance': action, } if request: log_defaults['request'] = request EventLog.objects.log(**log_defaults) # send the email notification to creator that the newsletter has been processed subject = action.email.subject subject = subject.replace("[firstname] [lastname], ", '') subject = subject.replace("[firstname], ", '') subject = subject.replace("[lastname], ", '') subject = subject.replace("[firstname]", '') subject = subject.replace("[lastname]", '') extra_contexts.update({'subject': subject, 'recipient_bcc': ['*****@*****.**']}) recipients = [action.owner.email] if recipients: if notification: notification.send_emails(recipients,'newsletter_recap', extra_contexts)
def add(request, form_class=JobForm, template_name="jobs/add.html"): require_payment = get_setting('module', 'jobs', 'jobsrequirespayment') can_add_active = has_perm(request.user, 'jobs.add_job') content_type = get_object_or_404(ContentType, app_label='jobs',model='job') if is_admin(request.user): category_form_class = CategoryForm else: category_form_class = CategoryForm2 if request.method == "POST": form = form_class(request.POST, user=request.user) categoryform = category_form_class( content_type, request.POST, prefix='category') # adjust the fields depending on user type if not require_payment: del form.fields['payment_method'] del form.fields['list_type'] if form.is_valid() and categoryform.is_valid(): job = form.save(commit=False) pricing = form.cleaned_data['pricing'] # 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 = now_localized() 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 = get_job_unique_slug(slugify(job.title)) job.slug = '%s-%s' % (slugify(job.title), Job.objects.count()) job = update_perms_and_save(request, form, job) # create invoice job_set_inv_payment(request.user, job, pricing) #setup categories category = Category.objects.get_for_object(job,'category') sub_category = Category.objects.get_for_object(job,'sub_category') ## update the category of the article category_removed = False category = categoryform.cleaned_data['category'] if category != '0': Category.objects.update(job,category,'category') else: # remove category_removed = True Category.objects.remove(job,'category') Category.objects.remove(job,'sub_category') if not category_removed: # update the sub category of the article sub_category = categoryform.cleaned_data['sub_category'] if sub_category != '0': Category.objects.update(job, sub_category,'sub_category') else: # remove Category.objects.remove(job,'sub_category') #save relationships job.save() log_defaults = { 'event_id': 251000, 'event_data': '%s (%d) added by %s' % (job._meta.object_name, job.pk, request.user), 'description': '%s added' % job._meta.object_name, 'user': request.user, 'request': request, 'instance': job, } EventLog.objects.log(**log_defaults) messages.add_message(request, messages.SUCCESS, 'Successfully added %s' % job) # 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']: if job.invoice and job.invoice.balance > 0: return HttpResponseRedirect(reverse( 'payments.views.pay_online', args=[job.invoice.id, job.invoice.guid]) ) # send user to thank you or view page if is_admin(request.user): return HttpResponseRedirect(reverse('job', args=[job.slug])) else: return HttpResponseRedirect(reverse('job.thank_you')) 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'): messages.add_message(request, messages.WARNING, 'You need to add a %s Pricing before you can add a %s.' % (get_setting('module', 'jobs', 'label_plural'),get_setting('module', 'jobs', 'label'))) return HttpResponseRedirect(reverse('job_pricing.add')) form = form_class(user=request.user) initial_category_form_data = { 'app_label': 'jobs', 'model': 'job', 'pk': 0, #not used for this view but is required for the form } categoryform = category_form_class( content_type, initial=initial_category_form_data, prefix='category') # adjust the fields depending on user type if not require_payment: del form.fields['payment_method'] del form.fields['list_type'] return render_to_response(template_name, {'form': form, 'categoryform':categoryform}, context_instance=RequestContext(request))
def index(request, form_class=ContactForm, template_name="form.html"): if request.method == "POST": form = form_class(request.POST) if form.is_valid(): email = form.cleaned_data.get('email', None) first_name = form.cleaned_data.get('first_name', None) last_name = form.cleaned_data.get('last_name', None) if listed_in_email_block(email): # listed in the email blocks - it's a spam email we want to block # log the spam log_defaults = { 'event_id' : 130999, 'event_data': 'SPAM detected in email from %s %s, %s.' \ % (first_name, last_name, email), 'description': 'email spam detected', 'user': request.user, 'request': request, } EventLog.objects.log(**log_defaults) # redirect normally so they don't suspect return HttpResponseRedirect(reverse('form.confirmation')) address = form.cleaned_data.get('address', None) city = form.cleaned_data.get('city', None) state = form.cleaned_data.get('state', None) zipcode = form.cleaned_data.get('zipcode', None) country = form.cleaned_data.get('country', None) phone = form.cleaned_data.get('phone', None) url = form.cleaned_data.get('url', None) message = form.cleaned_data.get('message', None) contact_kwargs = { 'first_name': first_name, 'last_name': last_name, 'message': message, } contact = Contact(**contact_kwargs) contact.creator_id = 1 # TODO: decide if we should use tendenci base model contact.owner_id = 1 # TODO: decide if we should use tendenci base model contact.save() if address or city or state or zipcode or country: address_kwargs = { 'address': address, 'city': city, 'state': state, 'zipcode': zipcode, 'country': country, } obj_address = Address(**address_kwargs) obj_address.save() # saves object contact.addresses.add(obj_address) # saves relationship if phone: obj_phone = Phone(number=phone) obj_phone.save() # saves object contact.phones.add(obj_phone) # saves relationship if email: obj_email = Email(email=email) obj_email.save() # saves object contact.emails.add(obj_email) # saves relationship if url: obj_url = URL(url=url) obj_url.save() # saves object contact.urls.add(obj_url) # saves relationship site_name = get_setting('site', 'global', 'sitedisplayname') message_link = get_setting('site', 'global', 'siteurl') # send notification to administrators # get admin notice recipients recipients = get_notice_recipients('module', 'contacts', 'contactrecipients') if recipients: if notification: extra_context = { 'reply_to': email, 'contact':contact, 'first_name':first_name, 'last_name':last_name, 'address':address, 'city':city, 'state':state, 'zipcode':zipcode, 'country':country, 'phone':phone, 'email':email, 'url':url, 'message':message, 'message_link':message_link, 'site_name':site_name, } notification.send_emails(recipients,'contact_submitted', extra_context) try: user = User.objects.filter(email=email)[0] except: user = None if user: event_user = user event_id = 125115 else: event_user = AnonymousUser() event_id = 125114 log_defaults = { 'event_id' : event_id, 'event_data': 'Contact Form (id:%d) submitted by %s' % (contact.pk, email), 'description': '%s added' % contact._meta.object_name, 'user': event_user, 'request': request, 'instance': contact, } EventLog.objects.log(**log_defaults) return HttpResponseRedirect(reverse('form.confirmation')) else: return render_to_response(template_name, {'form': form}, context_instance=RequestContext(request)) form = form_class() return render_to_response(template_name, {'form': form}, context_instance=RequestContext(request))
def add(request, form_class=MakePaymentForm, template_name="make_payments/add.html"): if request.method == "POST": form = form_class(request.user, request.POST) if form.is_valid(): mp = form.save(commit=False) # we might need to create a user record if not exist if request.user.is_authenticated(): user = request.user else: try: user = User.objects.get(email=mp.email) except: user = request.user if not user.is_anonymous(): mp.user = user mp.creator = user mp.creator_username = user.username mp.save(user) # create invoice invoice = make_payment_inv_add(user, mp) # log an event for invoice add log_defaults = { 'event_id' : 311000, 'event_data': '%s (%d) added by %s' % (invoice._meta.object_name, invoice.pk, request.user), 'description': '%s added' % invoice._meta.object_name, 'user': request.user, 'request': request, 'instance': invoice, } EventLog.objects.log(**log_defaults) # updated the invoice_id for mp, so save again mp.save(user) # log an event for make_payment log_defaults = { 'event_id' : 671000, 'event_data': '%s (%d) added by %s' % (mp._meta.object_name, mp.pk, request.user), 'description': '%s added' % mp._meta.object_name, 'user': request.user, 'request': request, 'instance': mp, } EventLog.objects.log(**log_defaults) # send notification to administrators # get admin notice recipients recipients = get_notice_recipients('module', 'payments', 'paymentrecipients') if recipients: if notification: extra_context = { 'mp': mp, 'invoice': invoice, 'request': request, } notification.send_emails(recipients,'make_payment_added', extra_context) # email to user email_receipt = form.cleaned_data['email_receipt'] if email_receipt: make_payment_email_user(request, mp, invoice) # redirect to online payment or confirmation page if mp.payment_method == 'cc' or mp.payment_method == 'credit card': return HttpResponseRedirect(reverse('payments.views.pay_online', args=[invoice.id, invoice.guid])) else: return HttpResponseRedirect(reverse('make_payment.add_confirm', args=[mp.id])) else: form = form_class(request.user) # check for initial payment_amount and clean up payment_amount = request.GET.get('payment_amount', 0) try: payment_amount = float(payment_amount) except: payment_amount = 0 if payment_amount > 0: form.fields['payment_amount'].initial = payment_amount # check for initial comment and clean up comments = request.GET.get('comments','') if comments: comments = strip_tags(comments) comments = strip_entities(comments) form.fields['comments'].initial = comments currency_symbol = get_setting("site", "global", "currencysymbol") if not currency_symbol: currency_symbol = "$" return render_to_response(template_name, {'form':form, 'currency_symbol': currency_symbol}, context_instance=RequestContext(request))
def add(request, form_class=PageForm, meta_form_class=MetaForm, category_form_class=CategoryForm, template_name="pages/add.html"): if not has_perm(request.user,'pages.add_page'): raise Http403 content_type = get_object_or_404(ContentType, app_label='pages',model='page') if request.method == "POST": form = form_class(request.POST, user=request.user) metaform = meta_form_class(request.POST, prefix='meta') categoryform = category_form_class(content_type, request.POST, prefix='category') if form.is_valid() and metaform.is_valid() and categoryform.is_valid(): page = form.save(commit=False) # add all permissions and save the model page = update_perms_and_save(request, form, page) #save meta meta = metaform.save() page.meta = meta #setup categories category = Category.objects.get_for_object(page,'category') sub_category = Category.objects.get_for_object(page,'sub_category') ## update the category of the article category_removed = False category = categoryform.cleaned_data['category'] if category != '0': Category.objects.update(page ,category,'category') else: # remove category_removed = True Category.objects.remove(page ,'category') Category.objects.remove(page ,'sub_category') if not category_removed: # update the sub category of the article sub_category = categoryform.cleaned_data['sub_category'] if sub_category != '0': Category.objects.update(page, sub_category,'sub_category') else: # remove Category.objects.remove(page,'sub_category') #save relationships page.save() log_defaults = { 'event_id' : 581000, 'event_data': '%s (%d) added by %s' % (page._meta.object_name, page.pk, request.user), 'description': '%s added' % page._meta.object_name, 'user': request.user, 'request': request, 'instance': page, } EventLog.objects.log(**log_defaults) messages.add_message(request, messages.SUCCESS, 'Successfully added %s' % page) if not is_admin(request.user): # send notification to administrators recipients = get_notice_recipients('module', 'pages', 'pagerecipients') if recipients: if notification: extra_context = { 'object': page, 'request': request, } notification.send_emails(recipients,'page_added', extra_context) return HttpResponseRedirect(reverse('page', args=[page.slug])) else: initial_category_form_data = { 'app_label': 'pages', 'model': 'page', 'pk': 0, #not used for this view but is required for the form } form = form_class(user=request.user) metaform = meta_form_class(prefix='meta') categoryform = category_form_class(content_type, initial=initial_category_form_data, prefix='category') return render_to_response(template_name, { 'form':form, 'metaform':metaform, 'categoryform':categoryform, }, context_instance=RequestContext(request))