def process_mailman(self, user, class_id, section_num, user_type):
        if not (settings.USE_MAILMAN and 'mailman_moderator' in settings.DEFAULT_EMAIL_ADDRESSES.keys()):
            return
        try:
            cls = ClassSubject.objects.get(id=int(class_id))
            section = filter(lambda s: s.index() == int(section_num), cls.sections.all())[0]
        except:
            return

        # Create a section list in Mailman,
        # then bounce this e-mail off to it

        list_name = "%s-%s" % (section.emailcode(), user_type)

        create_list(list_name, settings.DEFAULT_EMAIL_ADDRESSES['mailman_moderator'])
        load_list_settings(list_name, "lists/class_mailman.config")

        if user_type != "teachers":
            add_list_members(list_name, section.students())

            apply_list_settings(list_name, {
                'moderator': [
                    settings.DEFAULT_EMAIL_ADDRESSES['mailman_moderator'],
                    '%s-teachers@%s' % (cls.emailcode(),
                                        Site.objects.get_current().domain),
                    # In theory this is redundant, but it's included just in
                    # case.
                    cls.parent_program.director_email,
                ],
                'owner': [
                    settings.DEFAULT_EMAIL_ADDRESSES['mailman_moderator'],
                    cls.parent_program.director_email,
                ],
                'subject_prefix': "[%s]" % (cls.parent_program.niceName(),),
            })
            logger.info("Settings applied...")
            send_mail("[ESP] Activated class mailing list: %s@%s" % (list_name, Site.objects.get_current().domain),
                      render_to_string("mailman/new_list_intro_teachers.txt",
                                       { 'classname': str(cls),
                                         'mod_password': set_list_moderator_password(list_name) }),
                      settings.DEFAULT_EMAIL_ADDRESSES['default'], ["%s-teachers@%s" % (cls.emailcode(), Site.objects.get_current().domain), ])
        else:
            apply_list_settings(list_name, {'default_member_moderation': False})
            apply_list_settings(list_name, {'generic_nonmember_action': 0})
            apply_list_settings(list_name, {'acceptable_aliases': "%s.*-(students|class)-.*@%s" % (cls.emailcode(), Site.objects.get_current().domain)})
            apply_list_settings(list_name, {'subject_prefix': "[%s]" % (cls.parent_program.niceName(),)})

        logger.info("Settings applied still...")
        add_list_member(list_name, cls.parent_program.director_email)
        add_list_members(list_name, cls.get_teachers())
        if 'archive' in settings.DEFAULT_EMAIL_ADDRESSES:
            add_list_member(list_name, settings.DEFAULT_EMAIL_ADDRESSES['archive'])
        logger.info("Members added")

        self.recipients = ["%s@%s" % (list_name, Site.objects.get_current().domain)]
        self.send = True
示例#2
0
 def update_mailman_lists(self, delete=True):
     if hasattr(settings, 'USE_MAILMAN') and settings.USE_MAILMAN:
         program_list = "%s_%s-students" % (self.program.program_type, self.program.program_instance)
         self.clear_mailman_list(program_list)
         # Add all registered students into the program mailing list, even
         # if they didn't get enrolled into any classes.
         add_list_members(program_list, ESPUser.objects.filter(id__in=list(self.student_ids)).distinct())
         for i in range(self.num_sections):
             section = ClassSection.objects.get(id=self.section_ids[i])
             list_names = ["%s-%s" % (section.emailcode(), "students"), "%s-%s" % (section.parent_class.emailcode(), "students")]
             student_ids = self.student_ids[numpy.nonzero(self.student_sections[:,i])]
             students = ESPUser.objects.filter(id__in=student_ids).distinct()
             for list_name in list_names:
                 self.clear_mailman_list(list_name)
                 add_list_members(list_name, students)
示例#3
0
def update_membership(base_users, list_name, add=False, dry_run=DRY_RUN):
    current_members = set(mailman.list_contents(list_name))
    print """Updating list "%s", which currently has %s users.""" % (
        list_name, len(current_members))
    if dry_run:
        print "(This is a dry run.)"

    users_to_maybe_remove = ESPUser.objects.filter(is_active=False)
    users_not_to_remove = ESPUser.objects.filter(is_active=True)
    users_to_remove = users_to_maybe_remove.exclude(
        email__in=users_not_to_remove.values('email'))
    members_to_remove = current_members & set(
        users_to_remove.values_list('email', flat=True))
    print "Removing %s users..." % len(members_to_remove),
    if not dry_run:
        out, err = mailman.remove_list_member(list_name, members_to_remove)
        if out:
            print "stdout:"
            print out
        if err:
            print "sterr:"
            print err
    print "removed."

    if add:
        users_to_maybe_add = base_users.filter(is_active=True)
        users_not_to_add = ESPUser.objects.filter(is_active=False)
        users_to_add = users_to_maybe_add.exclude(
            email__in=users_not_to_add.values('email'))
        print "Adding %s users..." % len(users_to_add),
        if not dry_run:
            out, err = mailman.add_list_members(list_name, users_to_add)
            if out:
                print "stdout:"
                print out
            if err:
                print "sterr:"
                print err
        print "added."
    else:
        print "User adding disabled."

    new_members = mailman.list_contents(list_name)
    print """List "%s" now contains %s users.""" % (list_name,
                                                    len(new_members))
    print
def update_membership(base_users, list_name, add=False, dry_run=DRY_RUN):
    current_members = set(mailman.list_contents(list_name))
    print """Updating list "%s", which currently has %s users.""" % (
        list_name, len(current_members))
    if dry_run:
        print "(This is a dry run.)"

    users_to_maybe_remove = ESPUser.objects.filter(is_active=False)
    users_not_to_remove = ESPUser.objects.filter(is_active=True)
    users_to_remove = users_to_maybe_remove.exclude(
        email__in=users_not_to_remove.values('email'))
    members_to_remove = current_members & set(
        users_to_remove.values_list('email', flat=True))
    print "Removing %s users..." % len(members_to_remove),
    if not dry_run:
        out, err = mailman.remove_list_member(list_name, members_to_remove)
        if out:
            print "stdout:"
            print out
        if err:
            print "sterr:"
            print err
    print "removed."

    if add:
        users_to_maybe_add = base_users.filter(is_active=True)
        users_not_to_add = ESPUser.objects.filter(is_active=False)
        users_to_add = users_to_maybe_add.exclude(
            email__in=users_not_to_add.values('email'))
        print "Adding %s users..." % len(users_to_add),
        if not dry_run:
            out, err = mailman.add_list_members(list_name, users_to_add)
            if out:
                print "stdout:"
                print out
            if err:
                print "sterr:"
                print err
        print "added."
    else:
        print "User adding disabled."

    new_members = mailman.list_contents(list_name)
    print """List "%s" now contains %s users.""" % (
        list_name, len(new_members))
    print
    def coteachers(self, request, tl, one, two, module, extra, prog):
        if not 'clsid' in request.POST:
            return self.goToCore(tl)  # just fails.

        if extra == 'nojs':
            ajax = False
        else:
            ajax = True

        classes = ClassSubject.objects.filter(id=request.POST['clsid'])
        if len(classes) != 1 or not request.user.canEdit(classes[0]):
            return render_to_response(self.baseDir() + 'cannoteditclass.html',
                                      request, {})

        cls = classes[0]

        # set txtTeachers and coteachers....
        if not 'coteachers' in request.POST:
            coteachers = cls.get_teachers()
            coteachers = [
                user for user in coteachers if user.id != request.user.id
            ]

            txtTeachers = ",".join([str(user.id) for user in coteachers])

        else:
            txtTeachers = request.POST['coteachers']
            coteachers = txtTeachers.split(',')
            coteachers = [x for x in coteachers if x != '']
            coteachers = [
                ESPUser.objects.get(id=userid) for userid in coteachers
            ]
            add_list_members(
                "%s_%s-teachers" % (prog.program_type, prog.program_instance),
                coteachers)

        op = ''
        if 'op' in request.POST:
            op = request.POST['op']

        conflictingusers = []
        error = False

        if op == 'add':

            if len(request.POST['teacher_selected'].strip()) == 0:
                error = 'Error - Please click on the name when it drops down.'

            elif (request.POST['teacher_selected'] == str(request.user.id)):
                error = 'Error - You cannot select yourself as a coteacher!'
            elif request.POST['teacher_selected'] in txtTeachers.split(','):
                error = 'Error - You already added this teacher as a coteacher!'

            if error:
                return render_to_response(
                    self.baseDir() + 'coteachers.html', request, {
                        'class': cls,
                        'ajax': ajax,
                        'txtTeachers': txtTeachers,
                        'coteachers': coteachers,
                        'error': error,
                        'conflicts': []
                    })

            # add schedule conflict checking here...
            teacher = ESPUser.objects.get(id=request.POST['teacher_selected'])

            if cls.conflicts(teacher):
                conflictingusers.append(teacher.first_name + ' ' +
                                        teacher.last_name)
            else:
                coteachers.append(teacher)
                txtTeachers = ",".join(
                    [str(coteacher.id) for coteacher in coteachers])

        elif op == 'del':
            ids = request.POST.getlist('delete_coteachers')
            newcoteachers = []
            for coteacher in coteachers:
                if str(coteacher.id) not in ids:
                    newcoteachers.append(coteacher)

            coteachers = newcoteachers
            txtTeachers = ",".join(
                [str(coteacher.id) for coteacher in coteachers])

        elif op == 'save':
            old_coteachers_set = set(cls.get_teachers())
            new_coteachers_set = set(coteachers)

            to_be_added = new_coteachers_set - old_coteachers_set
            to_be_deleted = old_coteachers_set - new_coteachers_set

            # don't delete the current user
            if request.user in to_be_deleted:
                to_be_deleted.remove(request.user)

            for teacher in to_be_added:
                if cls.conflicts(teacher):
                    conflictingusers.append(teacher.first_name + ' ' +
                                            teacher.last_name)

            if len(conflictingusers) == 0:
                # remove some old coteachers
                for teacher in to_be_deleted:
                    cls.removeTeacher(teacher)

                # add bits for all new coteachers
                ccc = ClassCreationController(self.program)
                for teacher in to_be_added:
                    ccc.associate_teacher_with_class(cls, teacher)
                ccc.send_class_mail_to_directors(cls)
                return self.goToCore(tl)

        return render_to_response(
            self.baseDir() + 'coteachers.html', request, {
                'class': cls,
                'ajax': ajax,
                'txtTeachers': txtTeachers,
                'coteachers': coteachers,
                'conflicts': conflictingusers
            })
示例#6
0
def newprogram(request):
    template_prog = None
    template_prog_id = None
    if 'template_prog' in request.GET and (
            int(request.GET["template_prog"])
    ) != 0:  # if user selects None which value is 0,so we need to check for 0.
        #try:
        template_prog_id = int(request.GET["template_prog"])
        tprogram = Program.objects.get(id=template_prog_id)
        template_prog = {}
        template_prog.update(tprogram.__dict__)
        del template_prog["id"]
        template_prog["program_type"] = tprogram.program_type
        template_prog["program_modules"] = tprogram.program_modules.all(
        ).values_list("id", flat=True)
        template_prog["class_categories"] = tprogram.class_categories.all(
        ).values_list("id", flat=True)
        '''
        As Program Name should be new for each new program created then it is better to not to show old program names in input box .
        template_prog["term"] = tprogram.program_instance()
        template_prog["term_friendly"] = tprogram.niceName()
        '''

        student_reg_bits = list(
            Permission.objects.filter(
                permission_type__startswith='Student',
                program=template_prog_id).order_by('-start_date'))
        if len(student_reg_bits) > 0:
            newest_bit = student_reg_bits[0]
            oldest_bit = student_reg_bits[-1]

            template_prog["student_reg_start"] = oldest_bit.start_date
            template_prog["student_reg_end"] = newest_bit.end_date

        teacher_reg_bits = list(
            Permission.objects.filter(
                permission_type__startswith='Teacher',
                program=template_prog_id).order_by('-start_date'))
        if len(teacher_reg_bits) > 0:
            newest_bit = teacher_reg_bits[0]
            oldest_bit = teacher_reg_bits[-1]

            template_prog["teacher_reg_start"] = oldest_bit.start_date
            template_prog["teacher_reg_end"] = newest_bit.end_date

        pac = ProgramAccountingController(tprogram)
        line_items = pac.get_lineitemtypes(
            required_only=True).values('amount_dec')

        template_prog["base_cost"] = int(
            sum(x["amount_dec"] for x in line_items))
        template_prog["sibling_discount"] = tprogram.sibling_discount

    if 'checked' in request.GET:
        # Our form's anchor is wrong, because the form asks for the parent of the anchor that we really want.
        # Don't bother trying to fix the form; just re-set the anchor when we're done.
        context = pickle.loads(request.session['context_str'])
        pcf = ProgramCreationForm(context['prog_form_raw'])
        if pcf.is_valid():

            new_prog = pcf.save(commit=True)

            commit_program(new_prog, context['perms'], context['modules'],
                           context['cost'], context['sibling_discount'])

            # Create the default resource types now
            default_restypes = Tag.getProgramTag('default_restypes',
                                                 program=new_prog)
            if default_restypes:
                resource_type_labels = json.loads(default_restypes)
                resource_types = [
                    ResourceType.get_or_create(x, new_prog)
                    for x in resource_type_labels
                ]

            #   Force all ProgramModuleObjs and their extensions to be created now
            new_prog.getModules()

            manage_url = '/manage/' + new_prog.url + '/resources'

            if settings.USE_MAILMAN and 'mailman_moderator' in settings.DEFAULT_EMAIL_ADDRESSES.keys(
            ):
                # While we're at it, create the program's mailing list
                mailing_list_name = "%s_%s" % (new_prog.program_type,
                                               new_prog.program_instance)
                teachers_list_name = "%s-%s" % (mailing_list_name, "teachers")
                students_list_name = "%s-%s" % (mailing_list_name, "students")

                create_list(
                    students_list_name,
                    settings.DEFAULT_EMAIL_ADDRESSES['mailman_moderator'])
                create_list(
                    teachers_list_name,
                    settings.DEFAULT_EMAIL_ADDRESSES['mailman_moderator'])

                load_list_settings(teachers_list_name,
                                   "lists/program_mailman.config")
                load_list_settings(students_list_name,
                                   "lists/program_mailman.config")

                apply_list_settings(
                    teachers_list_name, {
                        'owner': [
                            settings.
                            DEFAULT_EMAIL_ADDRESSES['mailman_moderator'],
                            new_prog.director_email
                        ]
                    })
                apply_list_settings(
                    students_list_name, {
                        'owner': [
                            settings.
                            DEFAULT_EMAIL_ADDRESSES['mailman_moderator'],
                            new_prog.director_email
                        ]
                    })

                if 'archive' in settings.DEFAULT_EMAIL_ADDRESSES.keys():
                    add_list_members(students_list_name, [
                        new_prog.director_email,
                        settings.DEFAULT_EMAIL_ADDRESSES['archive']
                    ])
                    add_list_members(teachers_list_name, [
                        new_prog.director_email,
                        settings.DEFAULT_EMAIL_ADDRESSES['archive']
                    ])

            return HttpResponseRedirect(manage_url)
        else:
            raise ESPError("Improper form data submitted.", log=False)

    #   If the form has been submitted, process it.
    if request.method == 'POST':
        form = ProgramCreationForm(request.POST)

        if form.is_valid():
            temp_prog = form.save(commit=False)
            perms, modules = prepare_program(temp_prog, form.cleaned_data)
            #   Save the form's raw data instead of the form itself, or its clean data.
            #   Unpacking of the data happens at the next step.

            context_pickled = pickle.dumps({
                'prog_form_raw':
                form.data,
                'perms':
                perms,
                'modules':
                modules,
                'cost':
                form.cleaned_data['base_cost'],
                'sibling_discount':
                form.cleaned_data['sibling_discount']
            })
            request.session['context_str'] = context_pickled

            return render_to_response('program/newprogram_review.html',
                                      request, {
                                          'prog': temp_prog,
                                          'perms': perms,
                                          'modules': modules
                                      })

    else:
        #   Otherwise, the default view is a blank form.
        if template_prog:
            form = ProgramCreationForm(template_prog)
        else:
            form = ProgramCreationForm()

    return render_to_response(
        'program/newprogram.html', request, {
            'form': form,
            'programs': Program.objects.all().order_by('-id'),
            'template_prog_id': template_prog_id
        })
示例#7
0
def newprogram(request):
    template_prog = None
    template_prog_id = None
    if 'template_prog' in request.GET and (int(request.GET["template_prog"])) != 0:       # if user selects None which value is 0,so we need to check for 0.
       #try:
        template_prog_id = int(request.GET["template_prog"])
        tprogram = Program.objects.get(id=template_prog_id)
        template_prog = {}
        template_prog.update(tprogram.__dict__)
        del template_prog["id"]
        template_prog["program_type"] = tprogram.program_type
        template_prog["program_modules"] = tprogram.program_modules.all().values_list("id", flat=True)
        template_prog["class_categories"] = tprogram.class_categories.all().values_list("id", flat=True)
        '''
        As Program Name should be new for each new program created then it is better to not to show old program names in input box .
        template_prog["term"] = tprogram.program_instance()
        template_prog["term_friendly"] = tprogram.niceName()
        '''

        student_reg_bits = list(Permission.objects.filter(permission_type__startswith='Student', program=template_prog_id).order_by('-start_date'))
        if len(student_reg_bits) > 0:
            newest_bit = student_reg_bits[0]
            oldest_bit = student_reg_bits[-1]

            template_prog["student_reg_start"] = oldest_bit.start_date
            template_prog["student_reg_end"] = newest_bit.end_date

        teacher_reg_bits = list(Permission.objects.filter(permission_type__startswith='Teacher', program=template_prog_id).order_by('-start_date'))
        if len(teacher_reg_bits) > 0:
            newest_bit = teacher_reg_bits[0]
            oldest_bit = teacher_reg_bits[-1]

            template_prog["teacher_reg_start"] = oldest_bit.start_date
            template_prog["teacher_reg_end"] = newest_bit.end_date

        pac = ProgramAccountingController(tprogram)
        line_items = pac.get_lineitemtypes(required_only=True).values('amount_dec')

        template_prog["base_cost"] = int(sum(x["amount_dec"] for x in line_items))
        template_prog["sibling_discount"] = tprogram.sibling_discount

    if 'checked' in request.GET:
        # Our form's anchor is wrong, because the form asks for the parent of the anchor that we really want.
        # Don't bother trying to fix the form; just re-set the anchor when we're done.
        context = pickle.loads(request.session['context_str'])
        pcf = ProgramCreationForm(context['prog_form_raw'])
        if pcf.is_valid():

            new_prog = pcf.save(commit = True)

            commit_program(new_prog, context['perms'], context['modules'], context['cost'], context['sibling_discount'])

            # Create the default resource types now
            default_restypes = Tag.getProgramTag('default_restypes', program=new_prog)
            if default_restypes:
                resource_type_labels = json.loads(default_restypes)
                resource_types = [ResourceType.get_or_create(x, new_prog) for x in resource_type_labels]

            #   Force all ProgramModuleObjs and their extensions to be created now
            new_prog.getModules()

            manage_url = '/manage/' + new_prog.url + '/resources'

            if settings.USE_MAILMAN and 'mailman_moderator' in settings.DEFAULT_EMAIL_ADDRESSES.keys():
                # While we're at it, create the program's mailing list
                mailing_list_name = "%s_%s" % (new_prog.program_type, new_prog.program_instance)
                teachers_list_name = "%s-%s" % (mailing_list_name, "teachers")
                students_list_name = "%s-%s" % (mailing_list_name, "students")

                create_list(students_list_name, settings.DEFAULT_EMAIL_ADDRESSES['mailman_moderator'])
                create_list(teachers_list_name, settings.DEFAULT_EMAIL_ADDRESSES['mailman_moderator'])

                load_list_settings(teachers_list_name, "lists/program_mailman.config")
                load_list_settings(students_list_name, "lists/program_mailman.config")

                apply_list_settings(teachers_list_name, {'owner': [settings.DEFAULT_EMAIL_ADDRESSES['mailman_moderator'], new_prog.director_email]})
                apply_list_settings(students_list_name, {'owner': [settings.DEFAULT_EMAIL_ADDRESSES['mailman_moderator'], new_prog.director_email]})

                if 'archive' in settings.DEFAULT_EMAIL_ADDRESSES.keys():
                    add_list_members(students_list_name, [new_prog.director_email, settings.DEFAULT_EMAIL_ADDRESSES['archive']])
                    add_list_members(teachers_list_name, [new_prog.director_email, settings.DEFAULT_EMAIL_ADDRESSES['archive']])


            return HttpResponseRedirect(manage_url)
        else:
            raise ESPError("Improper form data submitted.", log=False)


    #   If the form has been submitted, process it.
    if request.method == 'POST':
        form = ProgramCreationForm(request.POST)

        if form.is_valid():
            temp_prog = form.save(commit=False)
            perms, modules = prepare_program(temp_prog, form.cleaned_data)
            #   Save the form's raw data instead of the form itself, or its clean data.
            #   Unpacking of the data happens at the next step.

            context_pickled = pickle.dumps({'prog_form_raw': form.data, 'perms': perms, 'modules': modules, 'cost': form.cleaned_data['base_cost'], 'sibling_discount': form.cleaned_data['sibling_discount']})
            request.session['context_str'] = context_pickled

            return render_to_response('program/newprogram_review.html', request, {'prog': temp_prog, 'perms':perms, 'modules': modules})

    else:
        #   Otherwise, the default view is a blank form.
        if template_prog:
            form = ProgramCreationForm(template_prog)
        else:
            form = ProgramCreationForm()

    return render_to_response('program/newprogram.html', request, {'form': form, 'programs': Program.objects.all().order_by('-id'),'template_prog_id':template_prog_id})
示例#8
0
    def process_mailman(self, user, class_id, user_type):
        if not (settings.USE_MAILMAN and 'mailman_moderator'
                in settings.DEFAULT_EMAIL_ADDRESSES.keys()):
            return
        try:
            cls = ClassSubject.objects.get(id=class_id)
            sections = cls.sections.all()
        except ESPUser.DoesNotExist:
            return

        # Create a class list in Mailman,
        # then bounce this e-mail off to it

        list_name = "%s-%s" % (cls.emailcode(), user_type)

        create_list(list_name,
                    settings.DEFAULT_EMAIL_ADDRESSES['mailman_moderator'])
        load_list_settings(list_name, "lists/class_mailman.config")

        if user_type != "teachers":
            for section in sections:
                add_list_members(list_name, section.students())

            apply_list_settings(
                list_name,
                {
                    'moderator': [
                        settings.DEFAULT_EMAIL_ADDRESSES['mailman_moderator'],
                        '%s-teachers@%s' %
                        (cls.emailcode(), Site.objects.get_current().domain),
                        # In theory this is redundant, but it's included just in
                        # case.
                        cls.parent_program.director_email,
                    ],
                    'owner': [
                        settings.DEFAULT_EMAIL_ADDRESSES['mailman_moderator'],
                        cls.parent_program.director_email,
                    ],
                    'subject_prefix':
                    "[%s]" % (cls.parent_program.niceName(), ),
                })
            send_mail(
                "[ESP] Activated class mailing list: %s@%s" %
                (list_name, Site.objects.get_current().domain),
                render_to_string(
                    "mailman/new_list_intro_teachers.txt", {
                        'classname': str(cls),
                        'mod_password': set_list_moderator_password(list_name)
                    }), settings.DEFAULT_EMAIL_ADDRESSES['default'], [
                        "%s-teachers@%s" %
                        (cls.emailcode(), Site.objects.get_current().domain),
                    ])
        else:
            apply_list_settings(list_name,
                                {'default_member_moderation': False})
            apply_list_settings(list_name, {'generic_nonmember_action': 0})
            apply_list_settings(
                list_name, {
                    'acceptable_aliases':
                    "%s.*-(students|class)-.*@%s" %
                    (cls.emailcode(), Site.objects.get_current().domain)
                })
            apply_list_settings(
                list_name,
                {'subject_prefix': "[%s]" % (cls.parent_program.niceName(), )})

        add_list_member(list_name, cls.parent_program.director_email)
        add_list_members(list_name, cls.get_teachers())
        if 'archive' in settings.DEFAULT_EMAIL_ADDRESSES:
            add_list_member(list_name,
                            settings.DEFAULT_EMAIL_ADDRESSES['archive'])

        self.recipients = [
            "%s@%s" % (list_name, Site.objects.get_current().domain)
        ]

        self.send = True