def selectList_old(self, request, tl, one, two, module, extra, prog): """ Allow use of the "old style" user selector if that is desired for generating a list of users. """ from esp.users.views import get_user_list from esp.users.models import User from esp.users.models import PersistentQueryFilter if not request.GET.has_key('filterid'): filterObj, found = get_user_list(request, self.program.getLists(True)) else: filterid = request.GET['filterid'] filterObj = PersistentQueryFilter.getFilterFromID( filterid, ESPUser) found = True if not found: return filterObj return self.generateList(request, tl, one, two, module, extra, prog, filterObj=filterObj)
def commprev(self, request, tl, one, two, module, extra, prog): from esp.users.models import PersistentQueryFilter from django.conf import settings filterid, listcount, subject, body = [request.POST['filterid'], request.POST['listcount'], request.POST['subject'], request.POST['body'] ] sendto_fn_name = request.POST.get('sendto_fn_name', MessageRequest.SEND_TO_SELF_REAL) # Set From address if request.POST.get('from', '').strip(): fromemail = request.POST['from'] else: # String together an address like [email protected] fromemail = '%s@%s' % (request.user.username, settings.SITE_INFO[1]) # Set Reply-To address if request.POST.get('replyto', '').strip(): replytoemail = request.POST['replyto'] else: replytoemail = fromemail try: filterid = int(filterid) except: raise ESPError("Corrupted POST data! Please contact us at [email protected] and tell us how you got this error, and we'll look into it.") userlist = PersistentQueryFilter.getFilterFromID(filterid, ESPUser).getList(ESPUser) try: firstuser = userlist[0] except: raise ESPError("You seem to be trying to email 0 people! Please go back, edit your search, and try again.") MessageRequest.assert_is_valid_sendto_fn_or_ESPError(sendto_fn_name) # If they were trying to use HTML, don't sanitize the content. if '<html>' not in body: htmlbody = body.replace('<', '<').replace('>', '>').replace('\n', '<br />') else: htmlbody = body contextdict = {'user' : ActionHandler(firstuser, firstuser), 'program': ActionHandler(self.program, firstuser) } renderedtext = Template(htmlbody).render(DjangoContext(contextdict)) return render_to_response(self.baseDir()+'preview.html', request, {'filterid': filterid, 'sendto_fn_name': sendto_fn_name, 'listcount': listcount, 'subject': subject, 'from': fromemail, 'replyto': replytoemail, 'body': body, 'renderedtext': renderedtext})
def filter_from_postdata(self, program, data): """ Wraps the query_from_postdata function above to return a PersistentQueryFilter. """ query = self.query_from_postdata(program, data) filterObj = PersistentQueryFilter.create_from_Q(ESPUser, query) if 'base_list' in data and 'recipient_type' in data: filterObj.useful_name = 'Program list: %s' % data['base_list'] elif 'combo_base_list' in data: filterObj.useful_name = 'Custom user list' filterObj.save() return filterObj
def commfinal(self, request, tl, one, two, module, extra, prog): from esp.dbmail.models import MessageRequest from esp.users.models import PersistentQueryFilter announcements = self.program_anchor_cached().tree_create( ['Announcements']) filterid, fromemail, replytoemail, subject, body = [ request.POST['filterid'], request.POST['from'], request.POST['replyto'], request.POST['subject'], request.POST['body'] ] try: filterid = int(filterid) except: raise ESPError( ), "Corrupted POST data! Please contact us at [email protected] and tell us how you got this error, and we'll look into it." filterobj = PersistentQueryFilter.getFilterFromID(filterid, ESPUser) variable_modules = {'user': request.user, 'program': self.program} newmsg_request = MessageRequest.createRequest( var_dict=variable_modules, subject=subject, recipients=filterobj, sender=fromemail, creator=request.user, msgtext=body, special_headers_dict={ 'Reply-To': replytoemail, }, ) newmsg_request.save() # now we're going to process everything # nah, we'll do this later. #newmsg_request.process() numusers = filterobj.getList(ESPUser).distinct().count() from django.conf import settings if hasattr(settings, 'EMAILTIMEOUT') and \ settings.EMAILTIMEOUT is not None: est_time = settings.EMAILTIMEOUT * numusers else: est_time = 1.5 * numusers # assert False, self.baseDir()+'finished.html' return render_to_response(self.baseDir() + 'finished.html', request, (prog, tl), {'time': est_time})
def commfinal(self, request, tl, one, two, module, extra, prog): from esp.dbmail.models import MessageRequest from esp.users.models import PersistentQueryFilter filterid, fromemail, replytoemail, subject, body = [ request.POST['filterid'], request.POST['from'], request.POST['replyto'], request.POST['subject'], request.POST['body'] ] sendto_fn_name = request.POST.get('sendto_fn_name', MessageRequest.SEND_TO_SELF_REAL) try: filterid = int(filterid) except: raise ESPError("Corrupted POST data! Please contact us at [email protected] and tell us how you got this error, and we'll look into it.") filterobj = PersistentQueryFilter.getFilterFromID(filterid, ESPUser) sendto_fn = MessageRequest.assert_is_valid_sendto_fn_or_ESPError(sendto_fn_name) variable_modules = {'user': request.user, 'program': self.program} newmsg_request = MessageRequest.createRequest(var_dict = variable_modules, subject = subject, recipients = filterobj, sendto_fn_name = sendto_fn_name, sender = fromemail, creator = request.user, msgtext = body, special_headers_dict = { 'Reply-To': replytoemail, }, ) newmsg_request.save() # now we're going to process everything # nah, we'll do this later. #newmsg_request.process() numusers = self.approx_num_of_recipients(filterobj, sendto_fn) from django.conf import settings if hasattr(settings, 'EMAILTIMEOUT') and \ settings.EMAILTIMEOUT is not None: est_time = settings.EMAILTIMEOUT * numusers else: est_time = 1.5 * numusers return render_to_response(self.baseDir()+'finished.html', request, {'time': est_time})
def filter_from_postdata(self, program, data): """ Wraps the query_from_postdata function above to return a PersistentQueryFilter. """ query = self.query_from_postdata(program, data) #TODO-determine best location to inject subquery #the string subquery should be assigned to .extra of the resultant filter filterObj = PersistentQueryFilter.create_from_Q(ESPUser, query) if 'base_list' in data and 'recipient_type' in data: filterObj.useful_name = 'Program list: %s' % data['base_list'] elif 'combo_base_list' in data: filterObj.useful_name = 'Custom user list' filterObj.save() return filterObj
def ajaxteachertext(self, request, tl, one, two, module, extra, prog): """ POST to this view to text a teacher a reminder to check-in. POST data: 'username': The teacher's username. 'section': Section ID number. """ if GroupTextModule.is_configured(): if 'username' in request.POST and 'section' in request.POST: sec = ClassSection.objects.get(id=request.POST['section']) teacher = PersistentQueryFilter.create_from_Q(ESPUser, Q(username=request.POST['username'])) message = "Don't forget to check-in for your " + one + " class that is scheduled for " + sec.start_time().pretty_time(True) + "!" GroupTextModule.sendMessages(teacher, message, True) return {'message': "Texted teacher"} else: return {'message': "Username and/or section not provided"} else: return {'message': "Twilio not configured"}
def verify_email(self): import string import random from esp.users.models import PersistentQueryFilter from esp.dbmail.models import MessageRequest from django.template import loader symbols = string.ascii_uppercase + string.digits code = "".join([random.choice(symbols) for x in range(30)]) regProf = RegistrationProfile.getLastForProgram( get_current_request().user, self.program) if regProf.email_verified: return self.goToCore(tl) if request.method == 'POST' and request.POST.has_key('verify_me'): # create the variable modules variable_modules = { 'program': self.program, 'user': get_current_request().user } # get the filter object filterobj = PersistentQueryFilter.getFilterFromQ( Q(id=get_current_request().user.id), User, 'User %s' % get_current_request().user.username) newmsg_request = MessageRequest.createRequest( var_dict=variable_modules, subject='[ESP] Email Verification For esp.mit.edu', recipients=filterobj, sender='"MIT Educational Studies Program" <*****@*****.**>', creator=self, msgtext=loader.find_template_source('email/verify')[0]) newmsg_request.save() return render_to_response(self.baseDir() + 'emailsent.html', request, {}) return render_to_response(self.baseDir() + 'sendemail.html', request, {})
def mailinglabel(self, request, tl, one, two, module, extra, prog): """ This function will allow someone to generate mailing labels. """ from esp.users.views import get_user_list combine = True if extra is None or extra.strip() == '': return render_to_response( self.baseDir() + 'mailinglabel_index.html', request, {}) if 'nocombine' in extra.strip().lower(): combine = False if 'schools' in extra.strip(): if request.method == 'POST': if 'filter_id' in request.POST: """ A filter was passed. """ f = PersistentQueryFilter.objects.get( id=request.POST['filter_id']) combine = (request.POST['combine'].upper() in ('TRUE', '1', 'T')) infos = f.getList(ContactInfo).distinct() else: form = SchoolSelectForm(request.POST) if form.is_valid(): try: zipc = ZipCode.objects.get( zip_code=form.cleaned_data['zip_code']) except: raise ESPError( 'Please enter a valid US zipcode. "%s" is not valid.' % form.cleaned_data['zip_code'], log=False) zipcodes = zipc.close_zipcodes( form.cleaned_data['proximity']) combine = form.cleaned_data['combine_addresses'] Q_infos = Q(k12school__id__isnull=False, address_zip__in=zipcodes) grades = form.cleaned_data['grades'].strip().split(',') if len(form.cleaned_data['grades_exclude'].strip() ) == 0: grades_exclude = [] else: grades_exclude = form.cleaned_data[ 'grades_exclude'].strip().split(',') if len(grades) > 0: Q_grade = reduce(operator.or_, [ Q(k12school__grades__contains=grade) for grade in grades ]) Q_infos &= Q_grade if len(grades_exclude) > 0: Q_grade = reduce(operator.or_, [ Q(k12school__grades__contains=grade) for grade in grades_exclude ]) Q_infos &= ~Q_grade f = PersistentQueryFilter.create_from_Q( ContactInfo, Q_infos, description= "All ContactInfos for K12 schools with grades %s and %s miles from zipcode %s." % (form.cleaned_data['grades'], form.cleaned_data['proximity'], form.cleaned_data['zip_code'])) num_schools = ContactInfo.objects.filter( Q_infos).distinct().count() return render_to_response( self.baseDir() + 'schools_confirm.html', request, { 'filter': f, 'num': num_schools, 'combine': combine }) else: return render_to_response( self.baseDir() + 'selectschools.html', request, {'form': form}) else: form = SchoolSelectForm(initial={ 'zip_code': '02139', 'combine_addresses': True }) return render_to_response( self.baseDir() + 'selectschools.html', request, {'form': form}) else: filterObj, found = get_user_list(request, self.program.getLists(True)) if not found: return filterObj infos = [ user.getLastProfile().contact_user for user in ESPUser.objects.filter(filterObj.get_Q()).distinct() ] infos_filtered = [ info for info in infos if (info != None and info.undeliverable != True) ] output = MailingLabels.gen_addresses(infos, combine) if 'csv' in extra.strip(): response = HttpResponse('\n'.join(output), content_type='text/plain') return response
def selectList(self, request, tl, one, two, module, extra, prog): """ Select the type of list that is requested. """ from esp.users.views import get_user_list from esp.users.models import User from esp.users.models import PersistentQueryFilter if not request.GET.has_key('filterid'): filterObj, found = get_user_list(request, self.program.getLists(True)) else: filterid = request.GET['filterid'] filterObj = PersistentQueryFilter.getFilterFromID( filterid, ESPUser) found = True if not found: return filterObj if request.method == 'POST' and 'fields' in request.POST: form = ListGenForm(request.POST) if form.is_valid(): lists = [] lists_indices = {} split_by = form.cleaned_data['split_by'] labels_dict = UserAttributeGetter.getFunctions() fields = [labels_dict[f] for f in form.cleaned_data['fields']] # If a split field is specified, make sure we fetch its data if split_by and labels_dict[split_by] not in fields: fields.append(labels_dict[split_by]) output_type = form.cleaned_data['output_type'] users = list( ESPUser.objects.filter( filterObj.get_Q()).filter(is_active=True).distinct()) users.sort() for u in users: ua = UserAttributeGetter(u, self.program) user_fields = [ ua.get(x) for x in form.cleaned_data['fields'] ] u.fields = user_fields # Add information for split lists if desired if split_by: if ua.get(split_by) not in lists_indices: lists.append({ 'key': labels_dict[split_by], 'value': ua.get(split_by), 'users': [] }) lists_indices[ua.get(split_by)] = len(lists) - 1 lists[lists_indices[ua.get(split_by)]]['users'].append( u) if split_by: lists.sort(key=lambda x: x['value']) else: lists.append({'users': users}) if output_type == 'csv': # properly speaking, this should be text/csv, but that # causes Chrome to open in an external editor, which is # annoying mimetype = 'text/plain' elif output_type == 'html': mimetype = 'text/html' else: # WTF? mimetype = 'text/html' return render_to_response( self.baseDir() + ('list_%s.html' % output_type), request, (prog, tl), { 'users': users, 'lists': lists, 'fields': fields, 'listdesc': filterObj.useful_name }, mimetype=mimetype, ) else: return render_to_response(self.baseDir() + 'options.html', request, (prog, tl), { 'form': form, 'filterid': filterObj.id }) else: form = ListGenForm() return render_to_response(self.baseDir() + 'options.html', request, (prog, tl), { 'form': form, 'filterid': filterObj.id })
def get_user_list(request, listDict2, extra=''): """ Get a list of users from some complicated mixture of other lists. The listDict must be of the form: {'list1_key': {'list: Q_Object, 'description': "UseFul_Description"} ... } This will return a tuple (userlist_or_response, found_list). If found_list is True, then userlist_or_response is a UserList object. Otherwise, it returns a response that's expected to be returned to django. """ if type(listDict2) != dict or len(listDict2) == 0: raise ESPError(), 'User lists were not specified correctly!' listDict = {} for key, value in listDict2.items(): listDict[key] = {'list': getQForUser(value['list']), 'description': value['description']} if request.POST.has_key('select_mailman'): from esp.mailman import list_members import operator lists = request.POST.getlist('select_mailman') all_list_members = reduce(operator.or_, (list_members(x) for x in lists)) filterObj = PersistentQueryFilter.getFilterFromQ(Q(id__in=[x.id for x in all_list_members]), ESPUser, 'Custom Mailman filter: ' + ", ".join(lists)) if request.POST['submitform'] == 'I want to search within this list': getUser, found = search_for_user(request, ESPUser.objects.filter(filterObj.get_Q()).distinct(), filterObj.id, True) if found: if type(getUser) == User or type(getUser) == ESPUser: newfilterObj = PersistentQueryFilter.getFilterFromQ(Q(id = getUser.id), ESPUser, 'User %s' % getUser.username) else: newfilterObj = PersistentQueryFilter.getFilterFromQ(filterObj.get_Q() & getUser, ESPUser, 'Custom user filter') return (newfilterObj, True) else: return (getUser, False) elif request.POST['submitform'] == 'I want a subset of this list': getUsers, found = get_user_checklist(request, ESPUser.objects.filter(filterObj.get_Q()).distinct(), filterObj.id) if found: newfilterObj = PersistentQueryFilter.getFilterFromQ(getUsers, ESPUser, 'Custom list') return (newfilterObj, True) else: return (getUsers, False) return (filterObj, True) # We got the list, return it. if request.POST.has_key('submit_checklist') and \ request.POST['submit_checklist'] == 'true': # If we're coming back after having checked off users from a checklist... filterObj = PersistentQueryFilter.getFilterFromID(request.POST['extra'], ESPUser) getUsers, found = get_user_checklist(request, ESPUser.objects.filter(filterObj.get_Q()).distinct(), filterObj.id) if found: # want to make a PersistentQueryFilter out of this returned query newfilterObj = PersistentQueryFilter.getFilterFromQ(getUsers, ESPUser, 'Custom list') return (newfilterObj, True) else: return (getUsers, False) if request.POST.has_key('submit_user_list') and \ request.POST['submit_user_list'] == 'true': # If a user list was submitted.... import operator # map of operators that can be done on lists (appropriately, Q Objects) opmapping = {'and' : operator.and_, 'or' : operator.or_, 'not' : (lambda x: ~x), # aseering 7/12/2008 -- Should work with Django SVN HEAD 'ident': (lambda x: x) # for completeness } # this is the "first" list...the list we start with. if listDict.has_key(request.POST['base_list']): curList = listDict[request.POST['base_list']]['list'] else: raise ESPError(), 'I do not know of list "%s".' % request.POST['base_list'] # we start with all the sparated lists, and apply the and'd lists onto the or'd lists before # we or. This closely represents the sentence (it's not as powerful, but makes "sense") separated = {'or': [curList], 'and': []} # use double-commas because it's safer? keys = request.POST['keys'].split(',,') for key in keys: if request.POST.has_key('operator_'+key) and \ request.POST['operator_'+key] and \ request.POST['operator_'+key] != 'ignore': # and it's not ignore (it should be 'and' or 'or') # We are adding to the list of 'and'd' lists and 'or'd' lists. separated[request.POST['operator_'+key]].append(opmapping[request.POST['not_'+key]](listDict[key]['list'])) # ^ - now separated has all the necessary Q objects. # essentially the below turns: a OR b AND c OR d ... into: (a AND c) or (b AND c) or (d AND c) # now we can apply the ands on all the or'd lists separately for i in range(len(separated['or'])): for j in range(len(separated['and'])): separated['or'][i] = opmapping['and'](separated['or'][i], separated['and'][j]) # and now we OR the leftover ors curList = separated['or'][0] for List in separated['or'][1:]: curList = opmapping['or'](curList, List) filterObj = PersistentQueryFilter.getFilterFromQ(curList, ESPUser, request.POST['finalsent']) if request.POST['submitform'] == 'I want to search within this list': getUser, found = search_for_user(request, ESPUser.objects.filter(filterObj.get_Q()).distinct(), filterObj.id, True) if found: if type(getUser) == User or type(getUser) == ESPUser: newfilterObj = PersistentQueryFilter.getFilterFromQ(Q(id = getUser.id), ESPUser, 'User %s' % getUser.username) else: newfilterObj = PersistentQueryFilter.getFilterFromQ(filterObj.get_Q() & getUser, ESPUser, 'Custom user filter') return (newfilterObj, True) else: return (getUser, False) elif request.POST['submitform'] == 'I want a subset of this list': getUsers, found = get_user_checklist(request, ESPUser.objects.filter(filterObj.get_Q()).distinct(), filterObj.id) if found: newfilterObj = PersistentQueryFilter.getFilterFromQ(getUsers, ESPUser, 'Custom list') return (newfilterObj, True) else: return (getUsers, False) return (filterObj, True) # We got the list, return it. # if we found a single user: if request.method == 'GET' and request.GET.has_key('op') and request.GET['op'] == 'usersearch': filterObj = PersistentQueryFilter.getFilterFromID(request.GET['extra'], ESPUser) getUser, found = search_for_user(request, ESPUser.objects.filter(filterObj.get_Q()).distinct(), filterObj.id, True) if found: if type(getUser) == User or type(getUser) == ESPUser: newfilterObj = PersistentQueryFilter.getFilterFromQ(Q(id = getUser.id), ESPUser, 'User %s' % getUser.username) else: newfilterObj = PersistentQueryFilter.getFilterFromQ(filterObj.get_Q() & getUser, ESPUser, 'Custom user filter') if 'usersearch_containers' in request.session: request.POST, request.GET = request.session['usersearch_containers'] del request.session['usersearch_containers'] return (newfilterObj, True) else: return (getUser, False) if request.GET.has_key('advanced') or not settings.USE_MAILMAN: # we're going to prepare a list to send out. arrLists = [] pickled_post = pickle.dumps(request.POST) pickled_get = pickle.dumps(request.GET) request.session['usersearch_containers'] = (pickled_post, pickled_get) for key, value in listDict.items(): arrLists.append(DBList(key = key, QObject = value['list'], description = value['description'].strip('.'))) # prepare a nice list thing. arrLists.sort(reverse=True) return (render_to_response('users/create_list.html', request, None, {'lists': arrLists}), False) # No, we didn't find it yet... else: from esp.mailman import all_lists public_lists = all_lists() nonpublic_lists = list( set(all_lists(show_nonpublic=True)) - set(public_lists) ) return (render_to_response('users/select_mailman_list.html', request, None, {'public_lists': public_lists, 'nonpublic_lists': nonpublic_lists}), False) # No, we didn't find it yet...
filename = '/home/pricem/past_students.txt' file = open(filename) data = file.readlines() file.close() addr_list = [] for line in data: addr_list.append(line.strip()) print 'Read %d addresses' % len(addr_list) addr_list = list(set(addr_list)) print 'Found %d distinct addresses' % len(addr_list) idmap = {} users = ESPUser.objects.filter(email__in=addr_list).order_by('-id') for u in users: if u.email not in idmap: idmap[u.email] = u.id id_list = idmap.values() user_q = Q(id__in=id_list) pqf = PersistentQueryFilter.create_from_Q(User, user_q, 'Custom list generated from e-mail addresses') print 'Found %d users' % ESPUser.objects.filter(user_q).distinct().count() print 'Created filter. Edit and send your e-mail at: %s' % (""" %s?extra=%d&op=usersearch&userid=&username=&last_name=&first_name=&email=&zipdistance_exclude=&zipdistance=&zipcode=02139&states=&grade_min=7&grade_max=13&submitform=Use+Filtered+List""" % (url, pqf.id))
def commprev(self, request, tl, one, two, module, extra, prog): from esp.users.models import PersistentQueryFilter from django.conf import settings filterid, listcount, subject, body = [ request.POST['filterid'], request.POST['listcount'], request.POST['subject'], request.POST['body'] ] # Set From address if request.POST.has_key('from') and \ len(request.POST['from'].strip()) > 0: fromemail = request.POST['from'] else: # String together an address like [email protected] fromemail = '%s@%s' % (request.user.username, settings.SITE_INFO[1]) # Set Reply-To address if request.POST.has_key('replyto') and len( request.POST['replyto'].strip()) > 0: replytoemail = request.POST['replyto'] else: replytoemail = fromemail try: filterid = int(filterid) except: raise ESPError( ), "Corrupted POST data! Please contact us at [email protected] and tell us how you got this error, and we'll look into it." userlist = PersistentQueryFilter.getFilterFromID( filterid, ESPUser).getList(ESPUser) try: firstuser = userlist[0] except: raise ESPError( ), "You seem to be trying to email 0 people! Please go back, edit your search, and try again." # If they were trying to use HTML, don't sanitize the content. if '<html>' not in body: htmlbody = body.replace('<', '<').replace('>', '>').replace( '\n', '<br />') else: htmlbody = body esp_firstuser = ESPUser(firstuser) contextdict = { 'user': ActionHandler(esp_firstuser, esp_firstuser), 'program': ActionHandler(self.program, esp_firstuser) } # Save the current context processors - we will disable them for rendering e-mail old_context_processors = settings.TEMPLATE_CONTEXT_PROCESSORS settings.TEMPLATE_CONTEXT_PROCESSORS = [] # Render the e-mail using the unaltered context renderedtext = Template(htmlbody).render(Context(contextdict)) # Restore context processors for future template rendering settings.TEMPLATE_CONTEXT_PROCESSORS = old_context_processors return render_to_response( self.baseDir() + 'preview.html', request, (prog, tl), { 'filterid': filterid, 'listcount': listcount, 'subject': subject, 'from': fromemail, 'replyto': replytoemail, 'body': body, 'renderedtext': renderedtext })