def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): body = loader.render_to_string(email_template_name, context) message = EmailMessage() message.subject = 'Password reset' message.body = body message.from_address = '*****@*****.**' message.reply_address = '*****@*****.**' message.from_name = context['user'].chapter.name message.sender = User.objects.get(username='******') message.html = False message.status = -1 message.save() recipient = EmailRecipient() recipient.message = message recipient.user = context['user'] recipient.to_name = context['user'].get_full_name() recipient.to_address = to_email recipient.save() message.status = 0 message.save()
def email_message(email_subject, email_body, chapter): message = EmailMessage() message.subject = email_subject message.body = email_body message.from_name = "myRobogals" message.from_address = "*****@*****.**" message.reply_address = "*****@*****.**" message.sender = User.objects.get(username='******') message.html = True message.email_type = 0 # Message is set to WAIT mode message.status = -1 message.save() # Creates a list of all users to notify if chapter.notify_list != None: users_to_notify = chapter.notify_list.users.all() # Email to all users that need to be notified for user in users_to_notify: recipient = EmailRecipient() recipient.message = message recipient.user = user recipient.to_name = user.get_full_name() recipient.to_address = user.email recipient.save() message.status = 0 message.save()
def genandsendpw(user, welcomeemail, chapter): plaintext_password = User.objects.make_random_password(6) user.set_password(plaintext_password) user.save() message = EmailMessage() message.subject = welcomeemail['subject'] try: message.body = welcomeemail['body'].format( chapter=chapter, user=user, plaintext_password=plaintext_password) except Exception: raise RgGenAndSendPwException('Email body contains invalid fields') message.from_address = '*****@*****.**' message.reply_address = '*****@*****.**' message.from_name = chapter.name message.sender = User.objects.get(username='******') message.html = welcomeemail['html'] message.status = -1 message.save() recipient = EmailRecipient() recipient.message = message recipient.user = user recipient.to_name = user.get_full_name() recipient.to_address = user.email recipient.save() message.status = 0 message.save()
def cancelvisit(request, visit_id): if not request.user.is_staff: raise Http404 chapter = request.user.chapter v = get_object_or_404(SchoolVisit, pk=visit_id) if (v.chapter != chapter) and not request.user.is_superuser: raise Http404 if request.method == 'POST': cancelform = CancelForm(request.POST, user=request.user, visit=v) if cancelform.is_valid(): data = cancelform.cleaned_data message = EmailMessage() message.subject = data['subject'] message.body = data['body'] message.from_address = request.user.email message.reply_address = request.user.email message.sender = request.user message.html = True message.from_name = chapter.name message.scheduled = False # Don't send it yet until the recipient list is done message.status = -1 # Save to database so we get a value for the primary key, # which we need for entering the recipient entries message.save() # Send to everyone who has been invited id_list = EventAttendee.objects.filter( event=v.id, rsvp_status=2).values_list('user_id') users = User.objects.filter(id__in=id_list, is_active=True, email_reminder_optin=True) for one_user in users: recipient = EmailRecipient() recipient.message = message recipient.user = one_user recipient.to_name = one_user.get_full_name() recipient.to_address = one_user.email recipient.save() message.status = 0 message.save() Event.objects.filter(id=v.id).delete() messages.success(request, message=unicode( _("Visit cancelled successfully"))) return HttpResponseRedirect('/teaching/list/') else: cancelform = CancelForm(None, user=request.user, visit=v) return render_to_response('visit_cancel.html', { 'cancelform': cancelform, 'visit_id': visit_id }, context_instance=RequestContext(request))
def save(self, domain_override=None, email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator): """ Generates a one-use only link for resetting password and sends to the user """ for user in self.users_cache: t = loader.get_template(email_template_name) c = { 'email': user.email, 'uid': int_to_base36(user.id), 'user': user, 'token': token_generator.make_token(user), } message = EmailMessage() message.subject = 'Password reset' message.body = t.render(Context(c)) message.from_address = '*****@*****.**' message.reply_address = '*****@*****.**' message.from_name = user.chapter.name message.sender = User.objects.get(username='******') message.html = False message.status = -1 message.save() recipient = EmailRecipient() recipient.message = message recipient.user = user recipient.to_name = user.get_full_name() recipient.to_address = user.email recipient.save() message.status = 0 message.save()
def send_email(email_subject, email_body, to_address): #Set up message fields message = EmailMessage() message.subject = email_subject message.body = email_body message.from_name = "myRobogals" message.from_address = "*****@*****.**" message.reply_address = "*****@*****.**" message.sender = User.objects.get(username='******') message.html = True message.email_type = 0 #set message to WAIT message.status = -1 message.save() #Set up recipient fields recipient = EmailRecipient() recipient.message = message recipient.to_address = to_address #Set message to PENDING, save and send message.status = 0 message.save()
def cancelvisit(request, visit_id): if not request.user.is_staff: raise Http404 chapter = request.user.chapter v = get_object_or_404(SchoolVisit, pk=visit_id) if (v.chapter != chapter) and not request.user.is_superuser: raise Http404 if request.method == 'POST': cancelform = CancelForm(request.POST, user=request.user, visit=v) if cancelform.is_valid(): data = cancelform.cleaned_data message = EmailMessage() message.subject = data['subject'] message.body = data['body'] message.from_address = request.user.email message.reply_address = request.user.email message.sender = request.user message.html = True message.from_name = chapter.name message.scheduled = False # Don't send it yet until the recipient list is done message.status = -1 # Save to database so we get a value for the primary key, # which we need for entering the recipient entries message.save() # Send to everyone who has been invited id_list = EventAttendee.objects.filter(event=v.id, rsvp_status=2).values_list('user_id') users = User.objects.filter(id__in=id_list, is_active=True, email_reminder_optin=True) for one_user in users: recipient = EmailRecipient() recipient.message = message recipient.user = one_user recipient.to_name = one_user.get_full_name() recipient.to_address = one_user.email recipient.save() message.status = 0 message.save() Event.objects.filter(id=v.id).delete() messages.success(request, message=unicode(_("Visit cancelled successfully"))) return HttpResponseRedirect('/teaching/list/') else: cancelform = CancelForm(None, user=request.user, visit=v) return render_to_response('visit_cancel.html', {'cancelform': cancelform, 'visit_id': visit_id}, context_instance=RequestContext(request))
def welcome_email(request, chapter, u): message = EmailMessage() try: message.subject = chapter.welcome_email_subject.format( chapter=chapter, user=u, plaintext_password=request.POST['password1']) except Exception: message.subject = chapter.welcome_email_subject try: message.body = chapter.welcome_email_msg.format( chapter=chapter, user=u, plaintext_password=request.POST['password1']) except Exception: message.body = chapter.welcome_email_msg # Setting defaults message.from_address = '*****@*****.**' message.reply_address = '*****@*****.**' message.from_name = chapter.name message.sender = User.objects.get(username='******') message.html = chapter.welcome_email_html # Setting message to -1 in the DB shows that the message is in WAIT mode message.status = -1 message.save() # Prepares message for sending recipient = EmailRecipient() recipient.message = message recipient.user = u recipient.to_name = u.get_full_name() recipient.to_address = u.email recipient.save() # Change message to PENIDNG mode, which waits for server to send message.status = 0 message.save()
def check_default_pass(): users = User.objects.all() for u in users: if check_password("newrg123", u.password): message = EmailMessage() message.body = "Dear " + u.first_name + ",\n\nYou are recieving this automated email because your myRobogals account is still set to use the default password. This is a security risk and exposes your myRobogals account to potentially being used by others.\n\nPlease login at http://my.robogals.org using the following credentials:\nUsername: "******"\nPassword: newrg123\n\nOnce you have logged in, please change your password.\n\nThankyou,\n\nmyRobogals password nagging bot :)" message.subject = "Warning: Account is using default password" message.from_address = "*****@*****.**" message.from_name = "myRobogals" message.reply_address = "*****@*****.**" message.html = False message.status = -1 message.sender_id = 168 message.save() recipient = EmailRecipient() recipient.message = message recipient.user = u recipient.to_name = u.get_full_name() recipient.to_address = u.email recipient.save() message.status = 0 message.save()
def newpost(request, topic_id): request.user.forum_last_act = datetime.datetime.now() request.user.save() user = request.user t = get_object_or_404(Topic, pk=topic_id) f = t.forum g = f.category c = g.chapter if (user.is_superuser) or (user.is_staff and ((c == user.chapter) or (c == None))) or ((c == user.chapter) and (g.exec_only == False)) or ((c == None) and (g.exec_only == False)): if request.method == 'POST': postform = WritePostForm(request.POST) if postform.is_valid(): data = postform.cleaned_data postMessage = Post() postMessage.topic = t postMessage.posted_by = user postMessage.message = data['message'] postMessage.save() t.num_views = t.num_views - 1 t.last_post_time = datetime.datetime.now() t.last_post_user = user t.save() f.last_post_time = datetime.datetime.now() f.last_post_user = user f.save() if 'watch' in request.POST: if request.POST['watch'] == '1': if not f.watchers.filter(pk=user.pk): t.watchers.add(user) else: if f.watchers.filter(pk=user.pk): f.watchers.remove(user) for topic in f.topic_set.all(): if topic != t: topic.watchers.add(user) else: topic.watchers.remove(user) else: t.watchers.remove(user) watchers = (f.watchers.all() | t.watchers.all()).distinct().exclude(pk=request.user.pk) if watchers: message = EmailMessage() message.subject = 'New Post for topic "' + t.subject + '"' message.body = 'New post for topic "' + t.subject + '" for forum "' + f.name + '" in category "' + g.name + '"\n\nPost message: (posted by ' + postMessage.posted_by.get_full_name() + ')\n' + postMessage.message message.from_name = "myRobogals" message.from_address = "*****@*****.**" message.reply_address = "*****@*****.**" message.sender = User.objects.get(pk=1692) #need to change message.html = False message.email_type = 1 message.status = -1 message.save() for watcher in watchers: recipient = EmailRecipient() recipient.message = message recipient.user = watcher recipient.to_name = watcher.get_full_name() recipient.to_address = watcher.email recipient.save() message.status = 0 message.save() else: request.user.message_set.create(message=unicode(_('- The field "Message" can not be empty'))) else: raise Http404 if 'return' in request.GET: return HttpResponseRedirect(request.GET['return']) elif 'return' in request.POST: return HttpResponseRedirect(request.POST['return']) elif c: return HttpResponseRedirect('/forums/' + c.myrobogals_url + '/topic/' + str(t.pk) + '/') else: return HttpResponseRedirect('/forums/' + request.user.chapter.myrobogals_url + '/topic/' + str(t.pk) + '/') else: raise Http404
def importcsv(filerows, welcomeemail, defaults, newsletter, user): columns = None subscribers_imported = 0 most_recent_issue = newsletter.get_most_recent() if defaults['type']: defaults['subscriber_type_id'] = defaults['type'].pk countries = Country.objects.all() country_ids = [] for country in countries: country_ids.append(country.pk) for row in filerows: try: # Get column names from first row if (columns == None): columns = row if 'email' not in columns: raise RgImportCsvException('You must specify an email field') continue # Create new user newsubscriber = NewsletterSubscriber() # Process row i = 0 send_most_recent = defaults['send_most_recent'] send_email = False for cell in row: colname = columns[i] if colname == 'email': stringval(colname, cell, newsubscriber, defaults) if not email_re.match(newsubscriber.email): raise SkipRowException if NewsletterSubscriber.objects.filter(email=newsubscriber.email, newsletter=newsletter).count() > 0: raise SkipRowException # This email address is already subscribed if newsletter.pk == 1: users_count = User.objects.filter(is_active=True, email=newsubscriber.email, email_newsletter_optin=True).count() if users_count > 0: raise SkipRowException # This email address is already subscribed by having User.email_newsletter_optin True if newsletter.pk == 5: users_count = User.objects.filter(is_active=True, email=newsubscriber.email, email_careers_newsletter_AU_optin=True).count() if users_count > 0: raise SkipRowException # This email address is already subscribed by having User.email_newsletter_optin True elif colname == 'first_name': stringval(colname, cell, newsubscriber, defaults) elif colname == 'last_name': stringval(colname, cell, newsubscriber, defaults) elif colname == 'company': stringval(colname, cell, newsubscriber, defaults) elif colname == 'type': types = SubscriberType.objects.all() type_ids = [] for type in types: type_ids.append(type.pk) numval('subscriber_type_id', cell, newsubscriber, defaults, type_ids) elif colname == 'country': if cell in country_ids: stringval('country_id', cell, newsubscriber, defaults) else: newsubscriber.country = defaults['country'] elif colname == 'details_verified': boolval(colname, cell, newsubscriber, defaults) elif colname == 'send_most_recent': data = cell.strip() if data == 'true': send_most_recent = True elif data == '1': send_most_recent = True elif data == 'yes': send_most_recent = True if data == 'false': send_most_recent = False elif data == '0': send_most_recent = False elif data == 'no': send_most_recent = False elif colname == 'send_email': data = cell.strip() if data == 'true': send_email = True elif data == '1': send_email = True elif data == 'yes': send_email = True else: pass # Unknown column, ignore # Increment column and do the loop again i += 1 # Apply any unapplied defaults if 'type' not in columns: if 'subscriber_type_id' in defaults: newsubscriber.subscriber_type_id = defaults['subscriber_type_id'] if 'details_verified' not in columns: if 'details_verified' in defaults: newsubscriber.details_verified = defaults['details_verified'] if 'country' not in columns: if 'country' in defaults: newsubscriber.country = defaults['country'] # Set some other important attributes newsubscriber.newsletter = newsletter newsubscriber.subscribed_date = datetime.now() newsubscriber.active = True # And finally... newsubscriber.save() # Send welcome email, if applicable if (welcomeemail['importaction'] == '1' or (welcomeemail['importaction'] == '3' and send_email)): message = EmailMessage() message.subject = welcomeemail['subject'] try: message.body = welcomeemail['body'].format( newsletter=newsletter, subscriber=newsubscriber) except Exception: newsubscriber.delete() raise RgImportCsvException('Welcome email format is invalid') message.from_address = welcomeemail['from_address'] message.reply_address = welcomeemail['reply_address'] message.from_name = welcomeemail['from_name'] message.sender = user message.html = welcomeemail['html'] message.status = -1 message.save() recipient = EmailRecipient() recipient.message = message recipient.to_name = newsubscriber.first_name + " " + newsubscriber.last_name recipient.to_address = newsubscriber.email recipient.save() message.status = 0 message.save() # Send most recent newsletter, if applicable if send_most_recent: recipient = EmailRecipient() recipient.message = most_recent_issue recipient.to_name = newsubscriber.first_name + " " + newsubscriber.last_name recipient.to_address = newsubscriber.email recipient.save() # Increment counter subscribers_imported += 1 except SkipRowException: continue # Skip this row # Tell the most recent issue to send with new subscribers, # if applicable most_recent_issue.status = 0 most_recent_issue.save() return subscribers_imported
def writeemail(request): memberstatustypes = MemberStatusType.objects.all() if not request.user.is_staff: raise Http404 if request.method == 'POST': typesel = request.POST['type'] schedsel = request.POST['scheduling'] statussel = request.POST['status'] if 'step' in request.POST: if request.POST['step'] == '1': emailform = WriteEmailForm(request.POST, user=request.user) request.session['emailid'] = datetime.utcnow().strftime('%y%m%d%H%M%S') request.session['emailform'] = emailform elif request.POST['step'] == '2': if ('emailform' not in request.session) or ('emailid' not in request.session): if 'emailform' in request.session: del request.session['emailform'] if 'emailid' in request.session: del request.session['emailid'] raise Http404 if request.session['emailid'] != request.POST['emailid']: raise Http404 warning = False msg = '' maxfilesize = 10 maxfilesetting = MessagesSettings.objects.filter(key='maxuploadfilesize') if maxfilesetting: maxfilesize = int(maxfilesetting[0].value) for f in request.FILES.getlist('upload_files'): if (f.name.__len__() > 70): msg += '<br>File name: "' + f.name + '" is longer than 70 characters' warning = True if (f.size > maxfilesize * 1024*1024): msg += '<br>File: "' + f.name + '" is larger than ' + str(maxfilesize) + ' MB' warning = True if warning: del request.session['emailform'] del request.session['emailid'] request.user.message_set.create(message=unicode(_('- Can not upload files. Reason(s): %s' % msg))) return HttpResponseRedirect('/messages/email/write/') emailform = request.session['emailform'] del request.session['emailform'] del request.session['emailid'] else: raise Http404 else: raise Http404 if emailform.is_valid(): data = emailform.cleaned_data if request.POST['step'] == '2': message = EmailMessage() message.subject = data['subject'] if data['header_list']: hl = data['header_list'] message.body = hl.upper_body + data['body'] + hl.lower_body else: message.body = data['body'] message.from_address = request.user.email message.reply_address = request.user.email message.sender = request.user message.html = True if request.POST['scheduling'] == '1': message.scheduled = True message.scheduled_date = datetime.combine(data['schedule_date'], data['schedule_time']) try: message.scheduled_date_type = int(data['schedule_zone']) except Exception: message.scheduled_date_type = 1 else: message.scheduled = False if request.POST['type'] == '4': n = data['newsletters'] message.from_name = n.from_name message.from_address = n.from_email message.reply_address = n.from_email message.sender = n.from_user else: message.content_subtype = "html" if int(data['from_type']) == 0: message.from_name = "Robogals" elif int(data['from_type']) == 1: message.from_name = request.user.chapter.name else: message.from_name = request.user.get_full_name() # Don't send it yet until the recipient list is done message.status = -1 # Save to database so we get a value for the primary key, # which we need for entering the recipient entries message.save() if request.POST['type'] == '1': if request.user.is_superuser: # "Email all members worldwide" feature disabled Nov 2010 - too much potential for abuse. # Can be re-enabled by uncommenting the following line, commenting the exception, # and removing the disabled tag from the relevant radio button in email_write.html #users = User.objects.filter(chapter__in=data['chapters'], is_active=True, email_chapter_optin=True) raise Exception else: users = User.objects.filter(chapter=request.user.chapter, is_active=True, email_chapter_optin=True).exclude(email='') elif request.POST['type'] == '2': if request.user.is_superuser: users = User.objects.filter(chapter__in=data['chapters_exec'], is_active=True, is_staff=True).exclude(email='') else: users = User.objects.filter(chapter=request.user.chapter, is_active=True, is_staff=True).exclude(email='') elif request.POST['type'] == '5': ul = data['list'] users = ul.users.all().exclude(email='') elif request.POST['type'] == '4': if request.user.is_superuser: # Special rule for The Amplifier if data['newsletters'].pk == 1: users = User.objects.filter(is_active=True, email_newsletter_optin=True).exclude(email='') elif data['newsletters'].pk == 5: users = User.objects.filter(is_active=True, email_careers_newsletter_AU_optin=True).exclude(email='') else: users = User.objects.none() else: users = data['recipients'] usersfiltered = [] if statussel != '0' and request.POST['type'] != '4': for one_user in users: if one_user.membertype().pk == int(statussel): if request.POST['step'] == '1': usersfiltered.append(one_user) else: if str(one_user.pk) in request.POST.keys(): recipient = EmailRecipient() recipient.message = message recipient.user = one_user recipient.to_name = one_user.get_full_name() recipient.to_address = one_user.email recipient.save() else: for one_user in users: if request.POST['step'] == '1': usersfiltered.append(one_user) else: if str(one_user.pk) in request.POST.keys(): recipient = EmailRecipient() recipient.message = message recipient.user = one_user recipient.to_name = one_user.get_full_name() recipient.to_address = one_user.email recipient.save() subscribers = [] if request.POST['type'] == '4' and request.user.is_superuser: for one_subscriber in NewsletterSubscriber.objects.filter(newsletter=data['newsletters'], active=True): if request.POST['step'] == '1': subscribers.append(one_subscriber) else: if ('sub' + str(one_subscriber.pk)) in request.POST.keys(): recipient = EmailRecipient() recipient.message = message recipient.user = None recipient.to_name = one_subscriber.first_name + " " + one_subscriber.last_name recipient.to_address = one_subscriber.email recipient.save() if request.POST['step'] == '2': for f in request.FILES.getlist('upload_files'): ef = EmailFile(emailfile=f) ef.save() message.upload_files.add(ef) # Now mark it as OK to send. The email and all recipients are now in MySQL. # A background script on the server will process the queue. message.status = 0 message.save() if request.POST['step'] == '1': return render_to_response('email_users_confirm.html', {'usersfiltered': usersfiltered, 'subscribers': subscribers, 'type': request.POST['type'], 'scheduling': request.POST['scheduling'], 'status': request.POST['status'], 'emailid': request.session['emailid']}, context_instance=RequestContext(request)) else: return HttpResponseRedirect('/messages/email/done/') else: if request.user.is_superuser: typesel = '2' else: typesel = '1' schedsel = '0' statussel = '1' emailform = WriteEmailForm(None, user=request.user) return render_to_response('email_write.html', {'memberstatustypes': memberstatustypes, 'emailform': emailform, 'chapter': request.user.chapter, 'typesel': typesel, 'schedsel': schedsel, 'statussel': statussel}, context_instance=RequestContext(request))
def importcsv(filerows, welcomeemail, defaults, chapter, updateuser, ignore_email): columns = None users_imported = 0 username_pos = 0 users_updated = 0 existing_users = 0 existing_emails = 0 count = -1 username_field_exists_flag = False user_already_exists = False msg = "" if 'date_joined' not in defaults: defaults['date_joined'] = timezone.now() elif defaults['date_joined'] == None: defaults['date_joined'] = timezone.now() for row in filerows: if any(row): # Create new user newuser = User() count += 1 user_already_exists_flag = False # Get column names from first row, also get the positions of the fields so that we can extract their values # using their positions later. if (columns == None): columns = row if 'first_name' not in columns: raise RgImportCsvException( _('You must specify a first_name field')) else: first_name_pos = columns.index('first_name') if 'last_name' not in columns: raise RgImportCsvException( _('You must specify a last_name field')) else: last_name_pos = columns.index('last_name') if 'email' not in columns: raise RgImportCsvException( _('You must specify an email field')) else: email_pos = columns.index('email') if 'username' in columns: username_pos = columns.index('username') username_field_exists_flag = True if 'mobile' in columns: mobile_pos = columns.index('mobile') continue # Process row i = 0 # extracting the values of the username, email, first_name and last_name fields for each row. if username_field_exists_flag: uname = row[username_pos] else: uname = '' email = row[email_pos] first_name = row[first_name_pos] last_name = row[last_name_pos] # now remove all the whitespaces from the extracted values. uname_data = uname.strip() email_data = email.strip() first_name_data = first_name.strip() last_name_data = last_name.strip() # check if any of the values is None or empty for a row. If yes, form an error message and ignore that row. if first_name_data == None or first_name_data == '': msg += ("<br>First name not provided for row %d - row ignored." ) % count continue if last_name_data == None or last_name_data == '': msg += ("<br>Last name not provided for row %d - row ignored." ) % count continue if email_data == None or email_data == '': msg += ( "<br>Email not provided for row %d - row ignored.") % count continue # check if the username exists, if yes, check if the 'updateuser' checkbox is ticked. If it is ticked, # then get the row with the matching username (and, as we will see, replace its contents). Otherwise, ignore. # Also, they must be from the same chapter if not check_username(uname_data): user_already_exists_flag = True if updateuser: newuser = User.objects.get(username=uname_data) if newuser.chapter == chapter: existing_users += 1 else: msg += ( "<br>Row %d has a username clash (%s) with another chapter - row ignored" ) % (count, uname_data) continue else: msg += ( "<br>Row %d has a username clash (%s) - row ignored" ) % (count, uname_data) continue # check if the email exists for any user, if yes, check if the 'ignore_email' checkbox is ticked. If it is not ticked, # then get the row with the matching username (and, as we will see, replace its contents). Otherwise, ignore. # Also, they must be from the same chapter elif not check_email_and_chapter(email_data, chapter): existing_emails += 1 if ignore_email: msg += ( "<br>Row %d's email address (%s) matches an existing user - row ignored" ) % (count, email_data) continue for cell in row: colname = columns[i] if colname == 'first_name': stringval(colname, cell, newuser, defaults) elif colname == 'last_name': stringval(colname, cell, newuser, defaults) elif colname == 'email': stringval(colname, cell, newuser, defaults) elif colname == 'username': data = cell.strip() if data != "": new_username = data else: new_username = generate_unique_username(row, columns) newuser.username = new_username elif colname == 'password': data = cell.strip() if data != "": plaintext_password = data else: plaintext_password = User.objects.make_random_password( 6) newuser.set_password(plaintext_password) elif colname == 'alt_email': stringval(colname, cell, newuser, defaults) elif colname == 'mobile': num = cell.strip().replace(' ', '').replace('+', '') if num != '': regexes = MobileRegex.objects.filter( collection=chapter.mobile_regexes) try: number_valid = False for regex in regexes: matches = re.compile(regex.regex).findall(num) if matches == []: matches = re.compile( regex.regex).findall("0" + num) if matches == []: continue else: num = "0" + num num = regex.prepend_digits + num[regex. strip_digits:] number_valid = True except ValueError: number_valid = False if number_valid: newuser.mobile = num elif colname == 'date_joined': dateval(colname, cell, newuser, defaults) elif colname == 'dob': dateval(colname, cell, newuser, defaults) elif colname == 'gender': numval(colname, cell, newuser, defaults, [0, 1, 2]) elif colname == 'course': stringval(colname, cell, newuser, defaults) elif colname == 'uni_start': dateval(colname, cell, newuser, defaults) elif colname == 'uni_end': dateval(colname, cell, newuser, defaults) elif colname == 'university_id': unis = University.objects.all() uni_ids = [-1] for uni in unis: uni_ids.append(uni.pk) numval(colname, cell, newuser, defaults, uni_ids) if getattr(newuser, 'university_id', 0) == -1: newuser.university_id = chapter.university_id elif colname == 'course_type': numval(colname, cell, newuser, defaults, [1, 2]) elif colname == 'student_type': numval(colname, cell, newuser, defaults, [1, 2]) elif colname == 'student_number': stringval(colname, cell, newuser, defaults) elif colname == 'privacy': numval(colname, cell, newuser, defaults, [0, 5, 10, 20]) elif colname == 'dob_public': boolval(colname, cell, newuser, defaults) elif colname == 'email_public': boolval(colname, cell, newuser, defaults) elif colname == 'email_chapter_optin': boolval(colname, cell, newuser, defaults) elif colname == 'mobile_marketing_optin': boolval(colname, cell, newuser, defaults) elif colname == 'email_reminder_optin': boolval(colname, cell, newuser, defaults) elif colname == 'mobile_reminder_optin': boolval(colname, cell, newuser, defaults) elif colname == 'email_newsletter_optin': boolval(colname, cell, newuser, defaults) elif colname == 'email_careers_newsletter_AU_optin': boolval(colname, cell, newuser, defaults) else: pass # Unknown column, ignore # Increment column and do the loop again i += 1 # If we still don't have a username and/or password # by this stage, let's generate one if getattr(newuser, 'username', '') == '': new_username = generate_unique_username(row, columns) newuser.username = new_username if getattr(newuser, 'password', '') == '': plaintext_password = User.objects.make_random_password(6) newuser.set_password(plaintext_password) # And finally... newuser.chapter = chapter newuser.save() # If updating an existing user, we don't need to do the rest if user_already_exists_flag: continue # Should be the default at the model-level, # but just to be sure... newuser.is_active = True newuser.is_staff = False newuser.is_superuser = False # Apply any unapplied defaults for key, value in defaults.iteritems(): if key not in columns: setattr(newuser, key, value) newuser.save() # Must be called after newuser.save() because the primary key # is required for these mt = MemberStatus(user_id=newuser.pk, statusType_id=1, status_date_start=newuser.date_joined) mt.save() # Send welcome email if welcomeemail: message = EmailMessage() try: message.subject = welcomeemail['subject'].format( chapter=chapter, user=newuser, plaintext_password=plaintext_password) except Exception: newuser.delete() raise RgImportCsvException( _('Welcome email subject format is invalid')) try: message.body = welcomeemail['body'].format( chapter=chapter, user=newuser, plaintext_password=plaintext_password) except Exception: newuser.delete() raise RgImportCsvException( _('Welcome email format is invalid')) message.from_address = '*****@*****.**' message.reply_address = '*****@*****.**' message.from_name = chapter.name message.sender = User.objects.get(username='******') message.html = welcomeemail['html'] message.status = -1 message.save() recipient = EmailRecipient() recipient.message = message recipient.user = newuser recipient.to_name = newuser.get_full_name() recipient.to_address = newuser.email recipient.save() message.status = 0 message.save() users_imported += 1 return users_imported, existing_users, existing_emails, msg
def importcsv(filerows, welcomeemail, defaults, chapter): columns = None users_imported = 0 if 'date_joined' not in defaults: defaults['date_joined'] = datetime.now() elif defaults['date_joined'] == None: defaults['date_joined'] = datetime.now() for row in filerows: # Get column names from first row if (columns == None): columns = row if 'first_name' not in columns: raise RgImportCsvException(_('You must specify a first_name field')) if 'last_name' not in columns: raise RgImportCsvException(_('You must specify a last_name field')) if 'email' not in columns: raise RgImportCsvException(_('You must specify an email field')) continue # Create new user newuser = User() # Process row i = 0; for cell in row: colname = columns[i] if colname == 'first_name': stringval(colname, cell, newuser, defaults) elif colname == 'last_name': stringval(colname, cell, newuser, defaults) elif colname == 'email': stringval(colname, cell, newuser, defaults) elif colname == 'username': data = cell.strip() if data != "": new_username = data else: new_username = generate_unique_username(row, columns) newuser.username = new_username elif colname == 'password': data = cell.strip() if data != "": plaintext_password = data else: plaintext_password = User.objects.make_random_password(6) newuser.set_password(plaintext_password) elif colname == 'alt_email': stringval(colname, cell, newuser, defaults) elif colname == 'mobile': num = cell.strip().replace(' ','').replace('+','') if num != '': regexes = MobileRegex.objects.filter(collection=chapter.mobile_regexes) try: number_valid = False for regex in regexes: matches = re.compile(regex.regex).findall(num) if matches == []: matches = re.compile(regex.regex).findall("0" + num) if matches == []: continue else: num = "0" + num num = regex.prepend_digits + num[regex.strip_digits:] number_valid = True except ValueError: number_valid = False if number_valid: newuser.mobile = num elif colname == 'date_joined': dateval(colname, cell, newuser, defaults) elif colname == 'dob': dateval(colname, cell, newuser, defaults) elif colname == 'gender': numval(colname, cell, newuser, defaults, [0, 1, 2]) elif colname == 'course': stringval(colname, cell, newuser, defaults) elif colname == 'uni_start': dateval(colname, cell, newuser, defaults) elif colname == 'uni_end': dateval(colname, cell, newuser, defaults) elif colname == 'university_id': unis = University.objects.all() uni_ids = [-1] for uni in unis: uni_ids.append(uni.pk) numval(colname, cell, newuser, defaults, uni_ids) if getattr(newuser, 'university_id', 0) == -1: newuser.university_id = chapter.university_id elif colname == 'course_type': numval(colname, cell, newuser, defaults, [1, 2]) elif colname == 'student_type': numval(colname, cell, newuser, defaults, [1, 2]) elif colname == 'student_number': stringval(colname, cell, newuser, defaults) elif colname == 'privacy': numval(colname, cell, newuser, defaults, [0, 5, 10, 20]) elif colname == 'dob_public': boolval(colname, cell, newuser, defaults) elif colname == 'email_public': boolval(colname, cell, newuser, defaults) elif colname == 'email_chapter_optin': boolval(colname, cell, newuser, defaults) elif colname == 'mobile_marketing_optin': boolval(colname, cell, newuser, defaults) elif colname == 'email_reminder_optin': boolval(colname, cell, newuser, defaults) elif colname == 'mobile_reminder_optin': boolval(colname, cell, newuser, defaults) elif colname == 'email_newsletter_optin': boolval(colname, cell, newuser, defaults) else: pass # Unknown column, ignore # Increment column and do the loop again i += 1 # Should be the default at the model-level, # but just to be sure... newuser.is_active = True newuser.is_staff = False newuser.is_superuser = False # If we still don't have a username and/or password # by this stage, let's generate one if getattr(newuser, 'username', '') == '': new_username = generate_unique_username(row, columns) newuser.username = new_username if getattr(newuser, 'password', '') == '': plaintext_password = User.objects.make_random_password(6) newuser.set_password(plaintext_password) # Apply any unapplied defaults for key, value in defaults.iteritems(): if key not in columns: setattr(newuser, key, value) # And finally... newuser.chapter = chapter newuser.save() # Must be called after save() because the primary key # is required for these mt = MemberStatus(user_id=newuser.pk, statusType_id=1) mt.save() # Send welcome email if welcomeemail: message = EmailMessage() try: message.subject = welcomeemail['subject'].format( chapter=chapter, user=newuser, plaintext_password=plaintext_password) except Exception: newuser.delete() raise RgImportCsvException(_('Welcome email subject format is invalid')) try: message.body = welcomeemail['body'].format( chapter=chapter, user=newuser, plaintext_password=plaintext_password) except Exception: newuser.delete() raise RgImportCsvException(_('Welcome email format is invalid')) message.from_address = '*****@*****.**' message.reply_address = '*****@*****.**' message.from_name = chapter.name message.sender = User.objects.get(username='******') message.html = welcomeemail['html'] message.status = -1 message.save() recipient = EmailRecipient() recipient.message = message recipient.user = newuser recipient.to_name = newuser.get_full_name() recipient.to_address = newuser.email recipient.save() message.status = 0 message.save() users_imported += 1 return users_imported
def importcsv(filerows, welcomeemail, defaults, newsletter, user): columns = None subscribers_imported = 0 most_recent_issue = newsletter.get_most_recent() if defaults['type']: defaults['subscriber_type_id'] = defaults['type'].pk countries = Country.objects.all() country_ids = [] for country in countries: country_ids.append(country.pk) for row in filerows: try: # Get column names from first row if (columns == None): columns = row if 'email' not in columns: raise RgImportCsvException('You must specify an email field') continue # Create new user newsubscriber = NewsletterSubscriber() # Process row i = 0; send_most_recent = defaults['send_most_recent'] send_email = False for cell in row: colname = columns[i] if colname == 'email': stringval(colname, cell, newsubscriber, defaults) if not email_re.match(newsubscriber.email): raise SkipRowException if NewsletterSubscriber.objects.filter(email=newsubscriber.email, newsletter=newsletter).count() > 0: raise SkipRowException # This email address is already subscribed if newsletter.pk == 1: users_count = User.objects.filter(is_active=True, email=newsubscriber.email, email_newsletter_optin=True).count() if users_count > 0: raise SkipRowException # This email address is already subscribed by having User.email_newsletter_optin True elif colname == 'first_name': stringval(colname, cell, newsubscriber, defaults) elif colname == 'last_name': stringval(colname, cell, newsubscriber, defaults) elif colname == 'company': stringval(colname, cell, newsubscriber, defaults) elif colname == 'type': types = SubscriberType.objects.all() type_ids = [] for type in types: type_ids.append(type.pk) numval('subscriber_type_id', cell, newsubscriber, defaults, type_ids) elif colname == 'country': if cell in country_ids: stringval('country_id', cell, newsubscriber, defaults) else: newsubscriber.country = defaults['country'] elif colname == 'details_verified': boolval(colname, cell, newsubscriber, defaults) elif colname == 'send_most_recent': data = cell.strip() if data == 'true': send_most_recent = True elif data == '1': send_most_recent = True elif data == 'yes': send_most_recent = True if data == 'false': send_most_recent = False elif data == '0': send_most_recent = False elif data == 'no': send_most_recent = False elif colname == 'send_email': data = cell.strip() if data == 'true': send_email = True elif data == '1': send_email = True elif data == 'yes': send_email = True else: pass # Unknown column, ignore # Increment column and do the loop again i += 1 # Apply any unapplied defaults if 'type' not in columns: if 'subscriber_type_id' in defaults: newsubscriber.subscriber_type_id = defaults['subscriber_type_id'] if 'details_verified' not in columns: if 'details_verified' in defaults: newsubscriber.details_verified = defaults['details_verified'] if 'country' not in columns: if 'country' in defaults: newsubscriber.country = defaults['country'] # Set some other important attributes newsubscriber.newsletter = newsletter newsubscriber.subscribed_date = datetime.now() newsubscriber.active = True # And finally... newsubscriber.save() # Send welcome email, if applicable if (welcomeemail['importaction'] == '1' or (welcomeemail['importaction'] == '3' and send_email)): message = EmailMessage() message.subject = welcomeemail['subject'] try: message.body = welcomeemail['body'].format( newsletter=newsletter, subscriber=newsubscriber) except Exception: newsubscriber.delete() raise RgImportCsvException('Welcome email format is invalid') message.from_address = welcomeemail['from_address'] message.reply_address = welcomeemail['reply_address'] message.from_name = welcomeemail['from_name'] message.sender = user message.html = welcomeemail['html'] message.status = -1 message.save() recipient = EmailRecipient() recipient.message = message recipient.to_name = newsubscriber.first_name + " " + newsubscriber.last_name recipient.to_address = newsubscriber.email recipient.save() message.status = 0 message.save() # Send most recent newsletter, if applicable if send_most_recent: recipient = EmailRecipient() recipient.message = most_recent_issue recipient.to_name = newsubscriber.first_name + " " + newsubscriber.last_name recipient.to_address = newsubscriber.email recipient.save() # Increment counter subscribers_imported += 1 except SkipRowException: continue # Skip this row # Tell the most recent issue to send with new subscribers, # if applicable most_recent_issue.status = 0 most_recent_issue.save() return subscribers_imported
def emailvisitattendees(request, visit_id): if not request.user.is_staff: raise Http404 chapter = request.user.chapter v = get_object_or_404(SchoolVisit, pk=visit_id) if (v.chapter != chapter) and not request.user.is_superuser: raise Http404 if request.method == 'POST': emailform = EmailAttendeesForm(request.POST, user=request.user, visit=v) if emailform.is_valid(): data = emailform.cleaned_data message = EmailMessage() message.subject = data['subject'] message.body = data['body'] message.from_address = request.user.email message.reply_address = request.user.email message.sender = request.user message.html = True message.from_name = chapter.name message.scheduled = False # Don't send it yet until the recipient list is done message.status = -1 # Save to database so we get a value for the primary key, # which we need for entering the recipient entries message.save() # Start processing recipient list # Send to all invitees if request.POST['invitee_type'] == '1': id_list = EventAttendee.objects.filter(event=v.id).values_list('user_id') users = User.objects.filter(id__in=id_list, is_active=True, email_reminder_optin=True) # Send to invitees who have RSVP'd as attending elif request.POST['invitee_type'] == '2': id_list = EventAttendee.objects.filter(event=v.id, rsvp_status=2).values_list('user_id') users = User.objects.filter(id__in=id_list, is_active=True, email_reminder_optin=True) # Send to invitees who have RSVP'd as not attending elif request.POST['invitee_type'] == '3': id_list = EventAttendee.objects.filter(event=v.id, rsvp_status=4).values_list('user_id') users = User.objects.filter(id__in=id_list, is_active=True, email_reminder_optin=True) # Send to invitees who have yet to RSVP elif request.POST['invitee_type'] == '4': id_list = EventAttendee.objects.filter(event=v.id, rsvp_status=1).values_list('user_id') users = User.objects.filter(id__in=id_list, is_active=True, email_reminder_optin=True) # Send to specifically selected users elif request.POST['invitee_type'] == '5': users = data['memberselect'] for one_user in users: recipient = EmailRecipient() recipient.message = message recipient.user = one_user recipient.to_name = one_user.get_full_name() recipient.to_address = one_user.email recipient.save() message.status = 0 message.save() messages.success(request, message=unicode(_("Email sent succesfully"))) return HttpResponseRedirect('/teaching/' + str(v.pk) + '/') else: emailform = EmailAttendeesForm(None, user=request.user, visit=v) return render_to_response('visit_email.html', {'emailform': emailform, 'visit_id': visit_id}, context_instance=RequestContext(request))
def emailvisitattendees(request, visit_id): if not request.user.is_staff: raise Http404 chapter = request.user.chapter v = get_object_or_404(SchoolVisit, pk=visit_id) if (v.chapter != chapter) and not request.user.is_superuser: raise Http404 if request.method == 'POST': emailform = EmailAttendeesForm(request.POST, user=request.user, visit=v) if emailform.is_valid(): data = emailform.cleaned_data message = EmailMessage() message.subject = data['subject'] message.body = data['body'] message.from_address = request.user.email message.reply_address = request.user.email message.sender = request.user message.html = True message.from_name = chapter.name message.scheduled = False # Don't send it yet until the recipient list is done message.status = -1 # Save to database so we get a value for the primary key, # which we need for entering the recipient entries message.save() # Start processing recipient list # Send to all invitees if request.POST['invitee_type'] == '1': id_list = EventAttendee.objects.filter( event=v.id).values_list('user_id') users = User.objects.filter(id__in=id_list, is_active=True, email_reminder_optin=True) # Send to invitees who have RSVP'd as attending elif request.POST['invitee_type'] == '2': id_list = EventAttendee.objects.filter( event=v.id, rsvp_status=2).values_list('user_id') users = User.objects.filter(id__in=id_list, is_active=True, email_reminder_optin=True) # Send to invitees who have RSVP'd as not attending elif request.POST['invitee_type'] == '3': id_list = EventAttendee.objects.filter( event=v.id, rsvp_status=4).values_list('user_id') users = User.objects.filter(id__in=id_list, is_active=True, email_reminder_optin=True) # Send to invitees who have yet to RSVP elif request.POST['invitee_type'] == '4': id_list = EventAttendee.objects.filter( event=v.id, rsvp_status=1).values_list('user_id') users = User.objects.filter(id__in=id_list, is_active=True, email_reminder_optin=True) # Send to specifically selected users elif request.POST['invitee_type'] == '5': users = data['memberselect'] for one_user in users: recipient = EmailRecipient() recipient.message = message recipient.user = one_user recipient.to_name = one_user.get_full_name() recipient.to_address = one_user.email recipient.save() message.status = 0 message.save() messages.success(request, message=unicode(_("Email sent succesfully"))) return HttpResponseRedirect('/teaching/' + str(v.pk) + '/') else: emailform = EmailAttendeesForm(None, user=request.user, visit=v) return render_to_response('visit_email.html', { 'emailform': emailform, 'visit_id': visit_id }, context_instance=RequestContext(request))
def rsvpemail(request, conf_id): # Superuser check if not request.user.is_superuser: raise Http404 conf = get_object_or_404(Conference, pk=conf_id) chapter = request.user.chapter # Determine if form has been POSTed back if request.method == 'POST': # Validate email form data emailform = EmailAttendeesForm(request.POST, conference=conf, user=request.user) if emailform.is_valid(): data = emailform.cleaned_data # Set up message message = EmailMessage() message.subject = data['subject'] message.body = data['body'] message.from_address = request.user.email message.reply_address = request.user.email message.sender = request.user message.html = True if int(data['from_type']) == 0: message.from_name = "Robogals" elif int(data['from_type']) == 1: message.from_name = request.user.chapter.name else: message.from_name = request.user.get_full_name() message.scheduled = False # Don't send it yet until the recipient list is done message.status = -1 # Save to database so we get a value for the primary key, # which we need for entering the recipient entries message.save() # Start processing recipient list # Insert choices for attending, not attending etc here if request.POST['invitee_type'] == '1': # All # Using `ConferenceAttendee` users = ConferenceAttendee.objects.filter(conference=conf.id) # Using `User` # id_list = ConferenceAttendee.objects.filter(conference=conf.id).values_list('user_id') # users = User.objects.filter(id__in = id_list, is_active=True, email_reminder_optin=True).order_by('last_name') elif request.POST['invitee_type'] == '2': # Selected users = data['memberselect'] for one_user in users: recipient = EmailRecipient() recipient.message = message recipient.to_address = one_user.email # Using `ConferenceAttendee` recipient.user = one_user.user recipient.to_name = one_user.full_name() # Using `User` # recipient.user = one_user # recipient.to_name = one_user.get_full_name() recipient.save() # Send message message.status = 0 message.save() request.user.message_set.create(message=unicode(_("Email sent successfully"))) return HttpResponseRedirect('/conferences/' + str(conf.pk) + '/') else: emailform = EmailAttendeesForm(None, conference=conf, user=request.user) # Display email form return render_to_response('conf_rsvp_email.html', {'conf': conf, 'emailform': emailform}, context_instance=RequestContext(request))
def api(request): if 'api' not in request.GET: return HttpResponse("-1") elif request.GET['api'] != API_SECRET: return HttpResponse("-1") elif 'action' in request.GET: try: n = Newsletter.objects.get(pk=request.GET['newsletter']) except Newsletter.DoesNotExist: return HttpResponse("-1") try: if request.GET['action'] == 'subscribe': email = unquote_plus(request.GET['email']).strip() try: validate_email(email) except ValidationError: valid_email = False else: valid_email = True if not valid_email: return HttpResponse("C") # Invalid email c = NewsletterSubscriber.objects.filter(email=email, newsletter=n, active=True).count() if c != 0: return HttpResponse("B") # Already subscribed if n.pk == 1: users_count = User.objects.filter(is_active=True, email=email, email_newsletter_optin=True).count() if users_count > 0: return HttpResponse("B") # Already subscribed # They've tried to subscribe already, so resend confirmation email p = PendingNewsletterSubscriber.objects.filter(email=email, newsletter=n) if p: p = p[0] else: p = PendingNewsletterSubscriber() p.email = email p.uniqid = md5(SECRET_KEY + email + n.name).hexdigest() p.newsletter = n p.save() confirm_url = n.confirm_url + "pid=" + str(p.pk) + "&key=" + p.uniqid message = EmailMessage() message.subject = n.confirm_subject message.body = n.confirm_email.replace('{email}', email).replace('{url}', confirm_url) message.from_address = n.confirm_from_email message.from_name = n.confirm_from_name message.reply_address = n.confirm_from_email message.sender = n.confirm_from_user message.html = n.confirm_html # Don't send it yet until the recipient list is done message.status = -1 # Save to database so we get a value for the primary key, # which we need for entering the recipient entries message.save() recipient = EmailRecipient() recipient.message = message recipient.to_name = "" recipient.to_address = email recipient.save() message.status = 0 message.save() return HttpResponse("A") # Success! elif request.GET['action'] == 'confirm': pid = unquote_plus(request.GET['id']) key = unquote_plus(request.GET['key']) try: p = PendingNewsletterSubscriber.objects.get(pk=pid, newsletter=n, uniqid=key) except PendingNewsletterSubscriber.DoesNotExist: return HttpResponse("B") try: if n.pk != 1: # Only do the user thing for The Amplifier (id = 1) raise User.DoesNotExist try: u = User.objects.get(email=p.email) except User.MultipleObjectsReturned: # Subscribe the first user with this email address u = User.objects.filter(email=p.email)[0] # This user is already a Robogals member u.email_newsletter_optin = True u.save() except User.DoesNotExist: ns = NewsletterSubscriber() ns.newsletter = n ns.email = p.email ns.active = True ns.details_verified = False ns.save() PendingNewsletterSubscriber.objects.filter(email=p.email, newsletter=n).delete() return HttpResponse("A") elif request.GET['action'] == 'unsubscribe': email = unquote_plus(request.GET['email']).strip() try: ns = NewsletterSubscriber.objects.get(email=email, newsletter=n, active=True) except NewsletterSubscriber.DoesNotExist: # Not on the list. Perhaps subscribed as a Robogals member? if n.pk != 1: # Only do the user thing for The Amplifier (id = 1) return HttpResponse("B") # Not subscribed try: for u in User.objects.filter(email=email): if u.email_newsletter_optin: u.email_newsletter_optin = False u.save() return HttpResponse("A") return HttpResponse("B") # Not subscribed except User.DoesNotExist: return HttpResponse("B") # Not subscribed ns.unsubscribed_date = datetime.now() ns.active = False ns.save() if n.pk == 1: for u in User.objects.filter(is_active=True, email=email, email_newsletter_optin=True): u.email_newsletter_optin = False u.save() return HttpResponse("A") else: return HttpResponse("-1") except KeyError: return HttpResponse("-1") else: return HttpResponse("-1")
def rsvpemail(request, conf_id): # Superuser check if not request.user.is_superuser: raise Http404 conf = get_object_or_404(Conference, pk=conf_id) chapter = request.user.chapter # Determine if form has been POSTed back if request.method == 'POST': # Validate email form data emailform = EmailAttendeesForm(request.POST, conference=conf, user=request.user) if emailform.is_valid(): data = emailform.cleaned_data # Set up message message = EmailMessage() message.subject = data['subject'] message.body = data['body'] message.from_address = request.user.email message.reply_address = request.user.email message.sender = request.user message.html = True if int(data['from_type']) == 0: message.from_name = "Robogals" elif int(data['from_type']) == 1: message.from_name = request.user.chapter.name else: message.from_name = request.user.get_full_name() message.scheduled = False # Don't send it yet until the recipient list is done message.status = -1 # Save to database so we get a value for the primary key, # which we need for entering the recipient entries message.save() # Start processing recipient list # Insert choices for attending, not attending etc here if request.POST['invitee_type'] == '1': # All # Using `ConferenceAttendee` users = ConferenceAttendee.objects.filter(conference=conf.id) # Using `User` # id_list = ConferenceAttendee.objects.filter(conference=conf.id).values_list('user_id') # users = User.objects.filter(id__in = id_list, is_active=True, email_reminder_optin=True).order_by('last_name') elif request.POST['invitee_type'] == '2': # Selected users = data['memberselect'] for one_user in users: recipient = EmailRecipient() recipient.message = message recipient.to_address = one_user.email # Using `ConferenceAttendee` recipient.user = one_user.user recipient.to_name = one_user.full_name() # Using `User` # recipient.user = one_user # recipient.to_name = one_user.get_full_name() recipient.save() # Send message message.status = 0 message.save() messages.success(request, message=unicode(_("Email sent successfully"))) return HttpResponseRedirect('/conferences/' + str(conf.pk) + '/') else: emailform = EmailAttendeesForm(None, conference=conf, user=request.user) # Display email form return render_to_response('conf_rsvp_email.html', { 'conf': conf, 'emailform': emailform }, context_instance=RequestContext(request))
def newtopic(request, forum_id): request.user.forum_last_act = datetime.datetime.now() request.user.save() f = get_object_or_404(Forum, pk=forum_id) g = f.category c = g.chapter user = request.user if (user.is_superuser) or (user.is_staff and ((c == user.chapter) or (c == None))) or ((c == user.chapter) and (g.exec_only == False)) or ((c == None) and (g.exec_only == False)): if request.method == 'POST': topicform = NewTopicForm(request.POST) if topicform.is_valid(): data = topicform.cleaned_data newTopic = Topic() newTopic.forum = f newTopic.posted_by = user newTopic.subject = data['subject'] newTopic.last_post_time = datetime.datetime.now() newTopic.last_post_user = user if Topic.objects.filter(forum=newTopic.forum, subject=newTopic.subject): msg = '- A similar topic already exists' request.user.message_set.create(message=unicode(_(msg))) else: newTopic.save() postMessage = Post() postMessage.topic = newTopic postMessage.posted_by = user postMessage.message = data['message'] postMessage.save() f.last_post_time = datetime.datetime.now() f.last_post_user = user f.save() watchers = f.watchers.all().exclude(pk=request.user.pk) if watchers: message = EmailMessage() message.subject = 'New Topic: ' + newTopic.subject message.body = 'New topic for forum "' + f.name + '" in category "' + g.name +'"\n\nTopic subject: ' + newTopic.subject + ' (started by ' + newTopic.posted_by.get_full_name() + ')\n\nTopic Message:\n' + postMessage.message message.from_name = "myRobogals" message.from_address = "*****@*****.**" message.reply_address = "*****@*****.**" message.sender = User.objects.get(username='******') message.html = False message.email_type = 1 message.status = -1 message.save() for watcher in watchers: recipient = EmailRecipient() recipient.message = message recipient.user = watcher recipient.to_name = watcher.get_full_name() recipient.to_address = watcher.email recipient.save() message.status = 0 message.save() else: request.user.message_set.create(message=unicode(_('- The fields "New Topic" and "Message" can not be empty'))) else: raise Http404 if 'return' in request.GET: return HttpResponseRedirect(request.GET['return']) elif 'return' in request.POST: return HttpResponseRedirect(request.POST['return']) elif c: return HttpResponseRedirect('/forums/' + c.myrobogals_url + '/forum/' + str(f.pk) + '/') else: return HttpResponseRedirect('/forums/' + request.user.chapter.myrobogals_url + '/forum/' + str(f.pk) + '/') else: raise Http404
def invitetovisit(request, visit_id): if not request.user.is_staff: raise Http404 chapter = request.user.chapter v = get_object_or_404(SchoolVisit, pk=visit_id) error = '' if (v.chapter != chapter) and not request.user.is_superuser: raise Http404 if request.method == 'POST': inviteform = InviteForm(request.POST, user=request.user, visit=v) if inviteform.is_valid(): data = inviteform.cleaned_data try: if data['action'] == '1': message = EmailMessage() message.subject = data['subject'] message.body = data['body'] message.from_address = request.user.email message.reply_address = request.user.email message.sender = request.user # message.html = v.chapter.invite_email_html message.html = 1 message.from_name = chapter.name # Don't send it yet until the recipient list is done message.status = -1 # Save to database so we get a value for the primary key, # which we need for entering the recipient entries message.save() # Send to all users who haven't opted out of workshop reminders if request.POST['type'] == '1': users = User.objects.filter(chapter=chapter, is_active=True, email_reminder_optin=True) # Send to chapter committee elif request.POST['type'] == '2': users = User.objects.filter(chapter=chapter, is_active=True, is_staff=True) # Send to all trained users who haven't opted out of workshop reminders elif request.POST['type'] == '4': users = User.objects.filter(chapter=chapter, is_active=True, email_reminder_optin=True, trained=True) # Send to a user list elif request.POST['type'] == '5': ul = data['list'] users = ul.users.all() # Send to specifically selected users else: users = data['memberselect'] for one_user in users: if data['action'] == '1': recipient = EmailRecipient() recipient.message = message recipient.user = one_user recipient.to_name = one_user.get_full_name() recipient.to_address = one_user.email recipient.save() EventAttendee.objects.filter(user=one_user, event=v).delete() ea = EventAttendee() ea.event = v ea.user = one_user if data['action'] == '1': ea.rsvp_status = 1 if data['action'] == '2': ea.rsvp_status = 2 ea.actual_status = 0 ea.save() if data['action'] == '1': # Now mark it as OK to send. The email and all recipients are now in MySQL. # A background script on the server will process the queue. message.status = 0 message.save() if data['action'] == '1': messages.success( request, message=unicode( _("Invitations have been sent to the selected volunteers" ))) if data['action'] == '2': messages.success( request, message=unicode( _("Selected volunteers have been added as attending" ))) return HttpResponseRedirect('/teaching/' + str(v.pk) + '/') except Exception as e: error = e.args[0] else: inviteform = InviteForm(None, user=request.user, visit=v) return render_to_response('visit_invite.html', { 'inviteform': inviteform, 'visit_id': visit_id, 'error': error }, context_instance=RequestContext(request))
def api(request): if 'api' not in request.GET: return HttpResponse("-1") elif request.GET['api'] != API_SECRET: return HttpResponse("-1") elif 'action' in request.GET: try: n = Newsletter.objects.get(pk=request.GET['newsletter']) except Newsletter.DoesNotExist: return HttpResponse("-1") try: if request.GET['action'] == 'subscribe': email = unquote_plus(request.GET['email']).strip() if not email_re.match(email): return HttpResponse("C") # Invalid email c = NewsletterSubscriber.objects.filter(email=email, newsletter=n, active=True).count() if c != 0: return HttpResponse("B") # Already subscribed if n.pk == 1: users_count = User.objects.filter(is_active=True, email=email, email_newsletter_optin=True).count() if users_count > 0: return HttpResponse("B") # Already subscribed try: # They've tried to subscribe already, so resend confirmation email p = PendingNewsletterSubscriber.objects.get(email=email, newsletter=n) except PendingNewsletterSubscriber.DoesNotExist: p = PendingNewsletterSubscriber() p.email = email p.uniqid = md5(SECRET_KEY + email + n.name).hexdigest() p.newsletter = n p.save() confirm_url = n.confirm_url + "pid=" + str(p.pk) + "&key=" + p.uniqid message = EmailMessage() message.subject = n.confirm_subject message.body = n.confirm_email.replace('{email}', email).replace('{url}', confirm_url) message.from_address = n.confirm_from_email message.from_name = n.confirm_from_name message.reply_address = n.confirm_from_email message.sender = n.confirm_from_user message.html = n.confirm_html # Don't send it yet until the recipient list is done message.status = -1 # Save to database so we get a value for the primary key, # which we need for entering the recipient entries message.save() recipient = EmailRecipient() recipient.message = message recipient.to_name = "" recipient.to_address = email recipient.save() message.status = 0 message.save() return HttpResponse("A") # Success! elif request.GET['action'] == 'confirm': pid = unquote_plus(request.GET['id']) key = unquote_plus(request.GET['key']) try: p = PendingNewsletterSubscriber.objects.get(pk=pid, newsletter=n, uniqid=key) except PendingNewsletterSubscriber.DoesNotExist: return HttpResponse("B") try: if n.pk != 1: # Only do the user thing for The Amplifier (id = 1) raise User.DoesNotExist try: u = User.objects.get(email=p.email) except User.MultipleObjectsReturned: # Subscribe the first user with this email address u = User.objects.filter(email=p.email)[0] # This user is already a Robogals member u.email_newsletter_optin = True u.save() except User.DoesNotExist: ns = NewsletterSubscriber() ns.newsletter = n ns.email = p.email ns.active = True ns.details_verified = False ns.save() p.delete() return HttpResponse("A") elif request.GET['action'] == 'unsubscribe': email = unquote_plus(request.GET['email']).strip() try: ns = NewsletterSubscriber.objects.get(email=email, newsletter=n, active=True) except NewsletterSubscriber.DoesNotExist: # Not on the list. Perhaps subscribed as a Robogals member? if n.pk != 1: # Only do the user thing for The Amplifier (id = 1) return HttpResponse("B") # Not subscribed try: for u in User.objects.filter(email=email): if u.email_newsletter_optin: u.email_newsletter_optin = False u.save() return HttpResponse("A") return HttpResponse("B") # Not subscribed except User.DoesNotExist: return HttpResponse("B") # Not subscribed ns.unsubscribed_date = datetime.now() ns.active = False ns.save() if n.pk == 1: for u in User.objects.filter(is_active=True, email=email, email_newsletter_optin=True): u.email_newsletter_optin = False u.save() return HttpResponse("A") else: return HttpResponse("-1") except KeyError: return HttpResponse("-1") else: return HttpResponse("-1")
def writeemail(request): memberstatustypes = MemberStatusType.objects.all() if not request.user.is_staff: raise Http404 if request.method == 'POST': typesel = request.POST['type'] schedsel = request.POST['scheduling'] statussel = request.POST['status'] if 'step' in request.POST: if request.POST['step'] == '1': emailform = WriteEmailForm(request.POST, user=request.user) request.session['emailform'] = emailform elif request.POST['step'] == '2': if 'emailform' not in request.session: raise Http404 emailform = request.session['emailform'] del request.session['emailform'] else: raise Http404 else: raise Http404 if emailform.is_valid(): data = emailform.cleaned_data if request.POST['step'] == '2': message = EmailMessage() message.subject = data['subject'] message.body = data['body'] message.from_address = request.user.email message.reply_address = request.user.email message.sender = request.user message.html = True if request.POST['scheduling'] == '1': message.scheduled = True message.scheduled_date = datetime.combine(data['schedule_date'], data['schedule_time']) try: message.scheduled_date_type = int(data['schedule_zone']) except Exception: message.scheduled_date_type = 1 else: message.scheduled = False if request.POST['type'] == '4': n = data['newsletters'] message.from_name = n.from_name message.from_address = n.from_email message.reply_address = n.from_email message.sender = n.from_user else: message.content_subtype = "html" if int(data['from_type']) == 0: message.from_name = "Robogals" elif int(data['from_type']) == 1: message.from_name = request.user.chapter.name else: message.from_name = request.user.get_full_name() # Don't send it yet until the recipient list is done message.status = -1 # Save to database so we get a value for the primary key, # which we need for entering the recipient entries message.save() if request.POST['type'] == '1': if request.user.is_superuser: # "Email all members worldwide" feature disabled Nov 2010 - too much potential for abuse. # Can be re-enabled by uncommenting the following line, commenting the exception, # and removing the disabled tag from the relevant radio button in email_write.html #users = User.objects.filter(chapter__in=data['chapters'], is_active=True, email_chapter_optin=True) raise Exception else: users = User.objects.filter(chapter=request.user.chapter, is_active=True, email_chapter_optin=True).exclude(email='') elif request.POST['type'] == '2': if request.user.is_superuser: users = User.objects.filter(chapter__in=data['chapters_exec'], is_active=True, is_staff=True).exclude(email='') else: users = User.objects.filter(chapter=request.user.chapter, is_active=True, is_staff=True).exclude(email='') elif request.POST['type'] == '5': ul = data['list'] users = ul.users.all().exclude(email='') elif request.POST['type'] == '4': if request.user.is_superuser: # Special rule for The Amplifier if data['newsletters'].pk == 1: users = User.objects.filter(is_active=True, email_newsletter_optin=True).exclude(email='') else: users = User.objects.none() else: users = data['recipients'] usersfiltered = [] if statussel != '0' and request.POST['type'] != '4': for one_user in users: if one_user.membertype().pk == int(statussel): if request.POST['step'] == '1': usersfiltered.append(one_user) else: if str(one_user.pk) in request.POST.keys(): recipient = EmailRecipient() recipient.message = message recipient.user = one_user recipient.to_name = one_user.get_full_name() recipient.to_address = one_user.email recipient.save() else: for one_user in users: if request.POST['step'] == '1': usersfiltered.append(one_user) else: if str(one_user.pk) in request.POST.keys(): recipient = EmailRecipient() recipient.message = message recipient.user = one_user recipient.to_name = one_user.get_full_name() recipient.to_address = one_user.email recipient.save() subscribers = [] if request.POST['type'] == '4' and request.user.is_superuser: for one_subscriber in NewsletterSubscriber.objects.filter(newsletter=data['newsletters'], active=True): if request.POST['step'] == '1': subscribers.append(one_subscriber) else: if ('sub' + str(one_subscriber.pk)) in request.POST.keys(): recipient = EmailRecipient() recipient.message = message recipient.user = None recipient.to_name = one_subscriber.first_name + " " + one_subscriber.last_name recipient.to_address = one_subscriber.email recipient.save() if request.POST['step'] == '2': # Now mark it as OK to send. The email and all recipients are now in MySQL. # A background script on the server will process the queue. message.status = 0 message.save() if request.POST['step'] == '1': return render_to_response('email_users_confirm.html', {'usersfiltered': usersfiltered, 'subscribers': subscribers, 'type': request.POST['type'], 'scheduling': request.POST['scheduling'], 'status': request.POST['status']}, context_instance=RequestContext(request)) else: return HttpResponseRedirect('/messages/email/done/') else: if request.user.is_superuser: typesel = '2' else: typesel = '1' schedsel = '0' statussel = '1' emailform = WriteEmailForm(None, user=request.user) return render_to_response('email_write.html', {'memberstatustypes': memberstatustypes, 'emailform': emailform, 'chapter': request.user.chapter, 'typesel': typesel, 'schedsel': schedsel, 'statussel': statussel}, context_instance=RequestContext(request))
def invitetovisit(request, visit_id): if not request.user.is_staff: raise Http404 chapter = request.user.chapter v = get_object_or_404(SchoolVisit, pk=visit_id) error = '' if (v.chapter != chapter) and not request.user.is_superuser: raise Http404 if request.method == 'POST': inviteform = InviteForm(request.POST, user=request.user, visit=v) if inviteform.is_valid(): data = inviteform.cleaned_data try: if data['action'] == '1': message = EmailMessage() message.subject = data['subject'] message.body = data['body'] message.from_address = request.user.email message.reply_address = request.user.email message.sender = request.user # message.html = v.chapter.invite_email_html message.html = 1 message.from_name = chapter.name # Don't send it yet until the recipient list is done message.status = -1 # Save to database so we get a value for the primary key, # which we need for entering the recipient entries message.save() # Send to all users who haven't opted out of workshop reminders if request.POST['type'] == '1': users = User.objects.filter(chapter=chapter, is_active=True, email_reminder_optin=True) # Send to chapter committee elif request.POST['type'] == '2': users = User.objects.filter(chapter=chapter, is_active=True, is_staff=True) # Send to all trained users who haven't opted out of workshop reminders elif request.POST['type'] == '4': users = User.objects.filter(chapter=chapter, is_active=True, email_reminder_optin=True, trained=True) # Send to a user list elif request.POST['type'] == '5': ul = data['list'] users = ul.users.all() # Send to specifically selected users else: users = data['memberselect'] for one_user in users: if data['action'] == '1': recipient = EmailRecipient() recipient.message = message recipient.user = one_user recipient.to_name = one_user.get_full_name() recipient.to_address = one_user.email recipient.save() EventAttendee.objects.filter(user=one_user, event=v).delete() ea = EventAttendee() ea.event = v ea.user = one_user if data['action'] == '1': ea.rsvp_status = 1 if data['action'] == '2': ea.rsvp_status = 2 ea.actual_status = 0 ea.save() if data['action'] == '1': # Now mark it as OK to send. The email and all recipients are now in MySQL. # A background script on the server will process the queue. message.status = 0 message.save() if data['action'] == '1': messages.success(request, message=unicode(_("Invitations have been sent to the selected volunteers"))) if data['action'] == '2': messages.success(request, message=unicode(_("Selected volunteers have been added as attending"))) return HttpResponseRedirect('/teaching/' + str(v.pk) + '/') except Exception as e: error = e.args[0] else: inviteform = InviteForm(None, user=request.user, visit=v) return render_to_response('visit_invite.html', {'inviteform': inviteform, 'visit_id': visit_id, 'error': error}, context_instance=RequestContext(request))
def importcsv(filerows, welcomeemail, defaults, chapter, updateuser, ignore_email): columns=None users_imported=0 username_pos=0 users_updated=0 existing_users=0 existing_emails=0 count=-1 username_field_exists_flag=False user_already_exists=False msg="" if 'date_joined' not in defaults: defaults['date_joined'] = datetime.now() elif defaults['date_joined'] == None: defaults['date_joined'] = datetime.now() for row in filerows: if any(row): # Create new user newuser = User() count+=1 user_already_exists_flag=False # Get column names from first row, also get the positions of the fields so that we can extract their values # using their positions later. if (columns == None): columns = row if 'first_name' not in columns: raise RgImportCsvException(_('You must specify a first_name field')) else: first_name_pos=columns.index('first_name') if 'last_name' not in columns: raise RgImportCsvException(_('You must specify a last_name field')) else: last_name_pos=columns.index('last_name') if 'email' not in columns: raise RgImportCsvException(_('You must specify an email field')) else: email_pos = columns.index('email') if 'username' in columns: username_pos=columns.index('username') username_field_exists_flag=True if 'mobile' in columns: mobile_pos=columns.index('mobile') continue # Process row i = 0; # extracting the values of the username, email, first_name and last_name fields for each row. if username_field_exists_flag: uname=row[username_pos] else: uname = '' email=row[email_pos] first_name=row[first_name_pos] last_name=row[last_name_pos] # now remove all the whitespaces from the extracted values. uname_data=uname.strip() email_data=email.strip() first_name_data=first_name.strip() last_name_data=last_name.strip() # check if any of the values is None or empty for a row. If yes, form an error message and ignore that row. if first_name_data == None or first_name_data == '': msg += ("<br>First name not provided for row %d - row ignored.") % count continue if last_name_data == None or last_name_data == '' : msg += ("<br>Last name not provided for row %d - row ignored.") % count continue if email_data == None or email_data == '' : msg += ("<br>Email not provided for row %d - row ignored.") % count continue # check if the username exists, if yes, check if the 'updateuser' checkbox is ticked. If it is ticked, # then get the row with the matching username (and, as we will see, replace its contents). Otherwise, ignore. # Also, they must be from the same chapter if not check_username(uname_data): user_already_exists_flag = True if updateuser: newuser = User.objects.get(username=uname_data) if newuser.chapter == chapter: existing_users += 1 else: msg += ("<br>Row %d has a username clash (%s) with another chapter - row ignored") % (count, uname_data) continue else: msg += ("<br>Row %d has a username clash (%s) - row ignored") % (count, uname_data) continue # check if the email exists for any user, if yes, check if the 'ignore_email' checkbox is ticked. If it is not ticked, # then get the row with the matching username (and, as we will see, replace its contents). Otherwise, ignore. # Also, they must be from the same chapter elif not check_email_and_chapter(email_data, chapter): existing_emails+=1 if ignore_email: msg += ("<br>Row %d's email address (%s) matches an existing user - row ignored") % (count, email_data) continue for cell in row: colname = columns[i] if colname == 'first_name': stringval(colname, cell, newuser, defaults) elif colname == 'last_name': stringval(colname, cell, newuser, defaults) elif colname == 'email': stringval(colname, cell, newuser, defaults) elif colname == 'username': data = cell.strip() if data != "": new_username = data else: new_username = generate_unique_username(row, columns) newuser.username = new_username elif colname == 'password': data = cell.strip() if data != "": plaintext_password = data else: plaintext_password = User.objects.make_random_password(6) newuser.set_password(plaintext_password) elif colname == 'alt_email': stringval(colname, cell, newuser, defaults) elif colname == 'mobile': num = cell.strip().replace(' ','').replace('+','') if num != '': regexes = MobileRegex.objects.filter(collection=chapter.mobile_regexes) try: number_valid = False for regex in regexes: matches = re.compile(regex.regex).findall(num) if matches == []: matches = re.compile(regex.regex).findall("0" + num) if matches == []: continue else: num = "0" + num num = regex.prepend_digits + num[regex.strip_digits:] number_valid = True except ValueError: number_valid = False if number_valid: newuser.mobile = num elif colname == 'date_joined': dateval(colname, cell, newuser, defaults) elif colname == 'dob': dateval(colname, cell, newuser, defaults) elif colname == 'gender': numval(colname, cell, newuser, defaults, [0, 1, 2]) elif colname == 'course': stringval(colname, cell, newuser, defaults) elif colname == 'uni_start': dateval(colname, cell, newuser, defaults) elif colname == 'uni_end': dateval(colname, cell, newuser, defaults) elif colname == 'university_id': unis = University.objects.all() uni_ids = [-1] for uni in unis: uni_ids.append(uni.pk) numval(colname, cell, newuser, defaults, uni_ids) if getattr(newuser, 'university_id', 0) == -1: newuser.university_id = chapter.university_id elif colname == 'course_type': numval(colname, cell, newuser, defaults, [1, 2]) elif colname == 'student_type': numval(colname, cell, newuser, defaults, [1, 2]) elif colname == 'student_number': stringval(colname, cell, newuser, defaults) elif colname == 'privacy': numval(colname, cell, newuser, defaults, [0, 5, 10, 20]) elif colname == 'dob_public': boolval(colname, cell, newuser, defaults) elif colname == 'email_public': boolval(colname, cell, newuser, defaults) elif colname == 'email_chapter_optin': boolval(colname, cell, newuser, defaults) elif colname == 'mobile_marketing_optin': boolval(colname, cell, newuser, defaults) elif colname == 'email_reminder_optin': boolval(colname, cell, newuser, defaults) elif colname == 'mobile_reminder_optin': boolval(colname, cell, newuser, defaults) elif colname == 'email_newsletter_optin': boolval(colname, cell, newuser, defaults) else: pass # Unknown column, ignore # Increment column and do the loop again i += 1 # If we still don't have a username and/or password # by this stage, let's generate one if getattr(newuser, 'username', '') == '': new_username = generate_unique_username(row, columns) newuser.username = new_username if getattr(newuser, 'password', '') == '': plaintext_password = User.objects.make_random_password(6) newuser.set_password(plaintext_password) # And finally... newuser.chapter = chapter newuser.save() # If updating an existing user, we don't need to do the rest if user_already_exists_flag: continue # Should be the default at the model-level, # but just to be sure... newuser.is_active = True newuser.is_staff = False newuser.is_superuser = False # Apply any unapplied defaults for key, value in defaults.iteritems(): if key not in columns: setattr(newuser, key, value) newuser.save() # Must be called after newuser.save() because the primary key # is required for these mt = MemberStatus(user_id=newuser.pk, statusType_id=1, status_date_start=newuser.date_joined.date()) mt.save() # Send welcome email if welcomeemail: message = EmailMessage() try: message.subject = welcomeemail['subject'].format( chapter=chapter, user=newuser, plaintext_password=plaintext_password) except Exception: newuser.delete() raise RgImportCsvException(_('Welcome email subject format is invalid')) try: message.body = welcomeemail['body'].format( chapter=chapter, user=newuser, plaintext_password=plaintext_password) except Exception: newuser.delete() raise RgImportCsvException(_('Welcome email format is invalid')) message.from_address = '*****@*****.**' message.reply_address = '*****@*****.**' message.from_name = chapter.name message.sender = User.objects.get(username='******') message.html = welcomeemail['html'] message.status = -1 message.save() recipient = EmailRecipient() recipient.message = message recipient.user = newuser recipient.to_name = newuser.get_full_name() recipient.to_address = newuser.email recipient.save() message.status = 0 message.save() users_imported += 1 return (users_imported, existing_users, existing_emails, msg)
def edituser(request, username, chapter=None): pwerr = '' usererr = '' new_username = '' if username == '': join = True u = User() if request.user.is_superuser or (request.user.is_staff and request.user.chapter == chapter): adduser = True else: adduser = False else: join = False adduser = False if not request.user.is_authenticated(): return HttpResponseRedirect("/login/?next=/profile/edit/") u = get_object_or_404(User, username__exact=username) chapter = u.chapter if join or request.user.is_superuser or request.user.id == u.id or (request.user.is_staff and request.user.chapter == u.chapter): if request.method == 'POST': if join: new_username = request.POST['username'].strip() formpart1 = FormPartOne(request.POST, chapter=chapter, user_id=u.id) formpart2 = FormPartTwo(request.POST, chapter=chapter) formpart3 = FormPartThree(request.POST, chapter=chapter) formpart4 = FormPartFour(request.POST, chapter=chapter) formpart5 = FormPartFive(request.POST, chapter=chapter) if formpart1.is_valid() and formpart2.is_valid() and formpart3.is_valid() and formpart4.is_valid() and formpart5.is_valid(): if join: username_len = len(new_username) if username_len < 3: usererr = _('Your username must be 3 or more characters') elif username_len > 30: usererr = _('Your username must be less than 30 characters') matches = re.compile(r'^\w+$').findall(new_username) if matches == []: usererr = _('Your username must contain only letters, numbers and underscores') else: try: usercheck = User.objects.get(username=new_username) except User.DoesNotExist: if request.POST['password1'] == request.POST['password2']: if len(request.POST['password1']) < 5: pwerr = _('Your password must be at least 5 characters long') else: u = User.objects.create_user(new_username, '', request.POST['password1']) u.chapter = chapter mt = MemberStatus(user_id=u.pk, statusType_id=1) mt.save() u.is_active = True u.is_staff = False u.is_superuser = False u.save() else: pwerr = _('The password and repeated password did not match. Please try again') else: usererr = _('That username is already taken') if request.user.is_staff and request.user != u: if len(request.POST['password1']) > 0: if request.POST['password1'] == request.POST['password2']: u.set_password(request.POST['password1']) else: pwerr = _('The password and repeated password did not match. Please try again') if pwerr == '' and usererr == '': data = formpart1.cleaned_data u.first_name = data['first_name'] u.last_name = data['last_name'] u.email = data['email'] u.alt_email = data['alt_email'] u.mobile = data['mobile'] u.gender = data['gender'] if 'student_number' in data: u.student_number = data['student_number'] if 'union_member' in data: u.union_member = data['union_member'] if 'tshirt' in data: u.tshirt = data['tshirt'] data = formpart2.cleaned_data u.privacy = data['privacy'] u.dob_public = data['dob_public'] u.email_public = data['email_public'] data = formpart3.cleaned_data u.dob = data['dob'] u.course = data['course'] u.uni_start = data['uni_start'] u.uni_end = data['uni_end'] u.university = data['university'] u.course_type = data['course_type'] u.student_type = data['student_type'] u.bio = data['bio'] #u.job_title = data['job_title'] #u.company = data['company'] data = formpart4.cleaned_data u.email_reminder_optin = data['email_reminder_optin'] u.email_chapter_optin = data['email_chapter_optin'] u.mobile_reminder_optin = data['mobile_reminder_optin'] u.mobile_marketing_optin = data['mobile_marketing_optin'] u.email_newsletter_optin = data['email_newsletter_optin'] data = formpart5.cleaned_data if 'internal_notes' in data: u.internal_notes = data['internal_notes'] if 'trained' in data: u.trained = data['trained'] u.save() if 'return' in request.POST: request.user.message_set.create(message=unicode(_("Profile and settings updated!"))) return HttpResponseRedirect(request.POST['return']) elif join: if chapter.welcome_email_enable: message = EmailMessage() message.subject = chapter.welcome_email_subject try: message.subject = chapter.welcome_email_subject.format( chapter=chapter, user=u, plaintext_password=request.POST['password1']) except Exception: message.subject = chapter.welcome_email_subject try: message.body = chapter.welcome_email_msg.format( chapter=chapter, user=u, plaintext_password=request.POST['password1']) except Exception: message.body = chapter.welcome_email_msg message.from_address = '*****@*****.**' message.reply_address = '*****@*****.**' message.from_name = chapter.name message.sender = User.objects.get(username='******') message.html = chapter.welcome_email_html message.status = -1 message.save() recipient = EmailRecipient() recipient.message = message recipient.user = u recipient.to_name = u.get_full_name() recipient.to_address = u.email recipient.save() message.status = 0 message.save() return HttpResponseRedirect("/welcome/" + chapter.myrobogals_url + "/") else: request.user.message_set.create(message=unicode(_("Profile and settings updated!"))) return HttpResponseRedirect("/profile/" + username + "/") else: if join: formpart1 = FormPartOne(None, chapter=chapter, user_id=0) formpart2 = FormPartTwo(None, chapter=chapter) formpart3 = FormPartThree(None, chapter=chapter) formpart4 = FormPartFour(None, chapter=chapter) formpart5 = FormPartFive(None, chapter=chapter) else: if u.tshirt: tshirt_id = u.tshirt.pk else: tshirt_id = None formpart1 = FormPartOne({ 'first_name': u.first_name, 'last_name': u.last_name, 'email': u.email, 'alt_email': u.alt_email, 'mobile': u.mobile, 'gender': u.gender, 'student_number': u.student_number, 'union_member': u.union_member, 'tshirt': tshirt_id}, chapter=chapter, user_id=u.pk) formpart2 = FormPartTwo({ 'privacy': u.privacy, 'dob_public': u.dob_public, 'email_public': u.email_public}, chapter=chapter) if u.university: uni = u.university.pk else: uni = None formpart3 = FormPartThree({ 'dob': u.dob, 'course': u.course, 'uni_start': u.uni_start, 'uni_end': u.uni_end, 'university': uni, 'job_title': u.job_title, 'company': u.company, 'course_type': u.course_type, 'student_type': u.student_type, 'bio': u.bio}, chapter=chapter) formpart4 = FormPartFour({ 'email_reminder_optin': u.email_reminder_optin, 'email_chapter_optin': u.email_chapter_optin, 'mobile_reminder_optin': u.mobile_reminder_optin, 'mobile_marketing_optin': u.mobile_marketing_optin, 'email_newsletter_optin': u.email_newsletter_optin}, chapter=chapter) formpart5 = FormPartFive({ 'internal_notes': u.internal_notes, 'trained': u.trained}, chapter=chapter) if 'return' in request.GET: return_url = request.GET['return'] elif 'return' in request.POST: return_url = request.POST['return'] else: return_url = '' chpass = (join or (request.user.is_staff and request.user != u)) exec_fields = request.user.is_superuser or (request.user.is_staff and request.user.chapter == chapter) return render_to_response('profile_edit.html', {'join': join, 'adduser': adduser, 'chpass': chpass, 'exec_fields': exec_fields, 'formpart1': formpart1, 'formpart2': formpart2, 'formpart3': formpart3, 'formpart4': formpart4, 'formpart5': formpart5, 'u': u, 'chapter': chapter, 'usererr': usererr, 'pwerr': pwerr, 'new_username': new_username, 'return': return_url}, context_instance=RequestContext(request)) else: raise Http404 # don't have permission to change
def importcsv(filerows, welcomeemail, defaults, newsletter, user): columns = None subscribers_imported = 0 most_recent_issue = newsletter.get_most_recent() if defaults["type"]: defaults["subscriber_type_id"] = defaults["type"].pk countries = Country.objects.all() country_ids = [] for country in countries: country_ids.append(country.pk) for row in filerows: try: # Get column names from first row if columns == None: columns = row if "email" not in columns: raise RgImportCsvException("You must specify an email field") continue # Create new user newsubscriber = NewsletterSubscriber() # Process row i = 0 send_most_recent = defaults["send_most_recent"] send_email = False for cell in row: colname = columns[i] if colname == "email": stringval(colname, cell, newsubscriber, defaults) if not email_re.match(newsubscriber.email): raise SkipRowException if ( NewsletterSubscriber.objects.filter(email=newsubscriber.email, newsletter=newsletter).count() > 0 ): raise SkipRowException # This email address is already subscribed elif colname == "first_name": stringval(colname, cell, newsubscriber, defaults) elif colname == "last_name": stringval(colname, cell, newsubscriber, defaults) elif colname == "company": stringval(colname, cell, newsubscriber, defaults) elif colname == "type": types = SubscriberType.objects.all() type_ids = [] for type in types: type_ids.append(type.pk) numval("subscriber_type_id", cell, newsubscriber, defaults, type_ids) elif colname == "country": if cell in country_ids: stringval("country_id", cell, newsubscriber, defaults) else: newsubscriber.country = defaults["country"] elif colname == "details_verified": boolval(colname, cell, newsubscriber, defaults) elif colname == "send_most_recent": data = cell.strip() if data == "true": send_most_recent = True elif data == "1": send_most_recent = True elif data == "yes": send_most_recent = True if data == "false": send_most_recent = False elif data == "0": send_most_recent = False elif data == "no": send_most_recent = False elif colname == "send_email": data = cell.strip() if data == "true": send_email = True elif data == "1": send_email = True elif data == "yes": send_email = True else: pass # Unknown column, ignore # Increment column and do the loop again i += 1 # Apply any unapplied defaults if "type" not in columns: if "subscriber_type_id" in defaults: newsubscriber.subscriber_type_id = defaults["subscriber_type_id"] if "details_verified" not in columns: if "details_verified" in defaults: newsubscriber.details_verified = defaults["details_verified"] if "country" not in columns: if "country" in defaults: newsubscriber.country = defaults["country"] # Set some other important attributes newsubscriber.newsletter = newsletter newsubscriber.subscribed_date = datetime.now() newsubscriber.active = True # And finally... newsubscriber.save() # Send welcome email, if applicable if welcomeemail["importaction"] == "1" or (welcomeemail["importaction"] == "3" and send_email): message = EmailMessage() message.subject = welcomeemail["subject"] try: message.body = welcomeemail["body"].format(newsletter=newsletter, subscriber=newsubscriber) except Exception: newsubscriber.delete() raise RgImportCsvException("Welcome email format is invalid") message.from_address = welcomeemail["from_address"] message.reply_address = welcomeemail["reply_address"] message.from_name = welcomeemail["from_name"] message.sender = user message.html = welcomeemail["html"] message.status = -1 message.save() recipient = EmailRecipient() recipient.message = message recipient.to_name = newsubscriber.first_name + " " + newsubscriber.last_name recipient.to_address = newsubscriber.email recipient.save() message.status = 0 message.save() # Send most recent newsletter, if applicable if send_most_recent: recipient = EmailRecipient() recipient.message = most_recent_issue recipient.to_name = newsubscriber.first_name + " " + newsubscriber.last_name recipient.to_address = newsubscriber.email recipient.save() # Increment counter subscribers_imported += 1 except SkipRowException: continue # Skip this row # Tell the most recent issue to send with new subscribers, # if applicable most_recent_issue.status = 0 most_recent_issue.save() return subscribers_imported