Esempio n. 1
0
def subtonews(first_name, last_name, email, chapter_id):
        cursor = connection.cursor()
        cursor.execute('SELECT u.id, u.email_chapter_optin FROM auth_user as u, auth_memberstatus as ms WHERE u.email = "' + email + '" AND u.id = ms.user_id AND ms.status_date_end IS NULL AND ms.statusType_id = 8 AND u.chapter_id = ' + str(chapter_id))
        user = cursor.fetchone()
        if user:
        	if int(user[1]) == 1:
        		raise SubToNewsException(_('That email address is already subscribed'))
        	else:
        		# reinstate a previous subscriber's subscription
        		user = User.objects.get(pk=user[0])
        		user.email_chapter_optin = True
        		user.first_name = first_name
        		user.last_name = last_name
        		user.save()
        else:
        	user = User()
        	columns = ['first_name', 'last_name', 'email']
        	row = [first_name, last_name, email]
        	user.username = generate_unique_username(row, columns)
        	user.first_name = first_name
        	user.last_name = last_name
        	user.email = email
        	user.chapter_id = chapter_id
        	user.email_chapter_optin = True
        	user.date_joined = datetime.now()
		user.save()

		# Must be called after save() because the primary key
		# is required for these
		mt = MemberStatus(user_id=user.pk, statusType_id=8)
		mt.save()
Esempio n. 2
0
def editstatus(request, chapterurl):
	c = get_object_or_404(Group, myrobogals_url__exact=chapterurl)
	memberstatustypes = MemberStatusType.objects.all()
	if request.user.is_superuser or (request.user.is_staff and (c == request.user.chapter)):
		users = []
		if request.method == 'POST':
			ulform = EditStatusForm(request.POST, user=request.user)
			if ulform.is_valid():
				data = ulform.cleaned_data
				status = data['status']
				users = data['users'] #l:queryset
				users_already = ""
				users_changed = ""
				for user in users:
					u = User.objects.get(username__exact = user.username)
					old_status = u.memberstatus_set.get(status_date_end__isnull=True)
					if old_status.statusType == MemberStatusType.objects.get(pk=int(status)):
						if(users_already):						
							users_already = users_already + ", " + u.username
						else:
							users_already = u.username
					else:
						if user.membertype().description != 'Inactive':
							old_status.status_date_end = date.today()
							old_status.save()
						new_status=MemberStatus()
						new_status.user = u
						new_status.statusType = MemberStatusType.objects.get(pk=int(status))
						new_status.status_date_start = date.today()
						new_status.save()
						if(users_changed):						
							users_changed = users_changed + ", " + u.username
						else:
							users_changed = u.username
				if(users_already):
					request.user.message_set.create(message=unicode(_("%(usernames)s are already marked as %(type)s") % {'usernames': users_already, 'type': MemberStatusType.objects.get(pk=int(status)).description}))
				if(users_changed):
					request.user.message_set.create(message=unicode(_("%(usernames)s have been marked as %(type)s") % {'usernames': users_changed, 'type': new_status.statusType.description}))
				return HttpResponseRedirect('/chapters/' + chapterurl + '/edit/users/')
		else:
			ulform = EditStatusForm(None, user=request.user)
			return render_to_response('edit_user_status.html', {'ulform': ulform, 'chapter': c, 'memberstatustypes': memberstatustypes}, context_instance=RequestContext(request))
Esempio n. 3
0
def subtonews(first_name, last_name, email, chapter_id):
    cursor = connection.cursor()
    cursor.execute(
        'SELECT u.id, u.email_chapter_optin FROM auth_user as u, auth_memberstatus as ms WHERE u.email = "'
        + email +
        '" AND u.id = ms.user_id AND ms.status_date_end IS NULL AND ms.statusType_id = 8 AND u.chapter_id = '
        + str(chapter_id))
    user = cursor.fetchone()
    if user:
        if int(user[1]) == 1:
            raise SubToNewsException(
                _('That email address is already subscribed'))
        else:
            # reinstate a previous subscriber's subscription
            user = User.objects.get(pk=user[0])
            user.email_chapter_optin = True
            user.first_name = first_name
            user.last_name = last_name
            user.save()
    else:
        user = User()
        columns = ['first_name', 'last_name', 'email']
        row = [first_name, last_name, email]
        user.username = generate_unique_username(row, columns)
        user.first_name = first_name
        user.last_name = last_name
        user.email = email
        user.chapter_id = chapter_id
        user.email_chapter_optin = True
        user.date_joined = datetime.now()
        user.save()

        # Must be called after save() because the primary key
        # is required for these
        mt = MemberStatus(user_id=user.pk, statusType_id=8)
        mt.save()
Esempio n. 4
0
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
Esempio n. 5
0
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)
Esempio n. 6
0
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)
                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)
Esempio n. 7
0
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