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
Example #2
0
    def process_mailman(self, user, class_id, user_type):
        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, "*****@*****.**")
        load_list_settings(list_name, "lists/class_mailman.config")

        if user_type != "teachers":
            for section in sections:
                add_list_member(list_name,
                                [x.email for x in section.students()])

            apply_list_settings(
                list_name, {
                    'moderator': [
                        '*****@*****.**',
                        '*****@*****.**' % cls.emailcode()
                    ]
                })
            send_mail(
                "[ESP] Activated class mailing list: %[email protected]" %
                list_name,
                render_to_string(
                    "mailman/new_list_intro_teachers.txt", {
                        'classname': str(cls),
                        'mod_password': set_list_moderator_password(list_name)
                    }), "*****@*****.**", [
                        "*****@*****.**" % cls.emailcode(),
                    ])
        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-.*@esp.mit.edu" % (cls.emailcode(), )
                })

        add_list_member(list_name, [cls.parent_program.director_email])
        add_list_member(list_name, [x.email for x in cls.teachers()])

        self.recipients = ["*****@*****.**" % list_name]

        self.send = True
Example #3
0
    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_member(list_name, ["%s %s <%s>" % (x.first_name, x.last_name, x.email, ) for x in section.students()])

            apply_list_settings(list_name, {'moderator': [settings.DEFAULT_EMAIL_ADDRESSES['mailman_moderator'], '%s-teachers@%s' % (cls.emailcode(), Site.objects.get_current().domain)]})
            if DEBUG: print "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-.*@%s" % (cls.emailcode(), Site.objects.get_current().domain)})

        if DEBUG: print "Settings applied still..."
        add_list_member(list_name, [cls.parent_program.director_email])
        add_list_member(list_name, [x.email for x in cls.teachers()])
        if 'archive' in settings.DEFAULT_EMAIL_ADDRESSES:
            add_list_member(list_name, settings.DEFAULT_EMAIL_ADDRESSES['archive'])
        if DEBUG: print "Members added"

        self.recipients = ["*****@*****.**" % list_name]
        self.send = True
Example #4
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_member(list_name, [
                    "%s %s <%s>" % (
                        x.first_name,
                        x.last_name,
                        x.email,
                    ) for x in section.students()
                ])

            apply_list_settings(
                list_name, {
                    'moderator': [
                        settings.DEFAULT_EMAIL_ADDRESSES['mailman_moderator'],
                        '%s-teachers@%s' %
                        (cls.emailcode(), Site.objects.get_current().domain)
                    ]
                })
            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)
                })

        add_list_member(list_name, [cls.parent_program.director_email])
        add_list_member(list_name, [x.email for x in 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
Example #5
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.anchor.name
        template_prog["term_friendly"] = tprogram.anchor.friendly_name
        '''

        template_prog["admins"] = ESPUser.objects.filter(
            permission__permission_type="Administer",
            permission__program=tprogram).values_list("id", flat=True)

        # aseering 5/18/2008 -- More aggressively list everyone who was an Admin
        #template_prog["admins"] = [ x.id for x in UserBit.objects.bits_get_users(verb=GetNode("V/Administer"), qsc=tprogram.anchor, user_objs=True) ]

        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_member(students_list_name, [
                        new_prog.director_email,
                        settings.DEFAULT_EMAIL_ADDRESSES['archive']
                    ])
                    add_list_member(teachers_list_name, [
                        new_prog.director_email,
                        settings.DEFAULT_EMAIL_ADDRESSES['archive']
                    ])

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

    #   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
        })
Example #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})
Example #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_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.anchor.name
        template_prog["term_friendly"] = tprogram.anchor.friendly_name
        '''
        template_prog["anchor"] = tprogram.anchor.parent.id

        # aseering 5/18/2008 -- List everyone who was granted V/Administer on the specified program
        template_prog["admins"] = ESPUser.objects.filter(
            userbit__verb=GetNode("V/Administer"),
            userbit__qsc=tprogram.anchor).values_list("id", flat=True)

        # aseering 5/18/2008 -- More aggressively list everyone who was an Admin
        #template_prog["admins"] = [ x.id for x in UserBit.objects.bits_get_users(verb=GetNode("V/Administer"), qsc=tprogram.anchor, user_objs=True) ]

        program_visible_bits = list(
            UserBit.objects.bits_get_users(
                verb=GetNode("V/Flags/Public"), qsc=tprogram.anchor).filter(
                    user__isnull=True).order_by("-startdate"))
        if len(program_visible_bits) > 0:
            newest_bit = program_visible_bits[0]
            oldest_bit = program_visible_bits[-1]

            template_prog["publish_start"] = oldest_bit.startdate
            template_prog["publish_end"] = newest_bit.enddate

        student_reg_bits = list(
            UserBit.objects.bits_get_users(
                verb=GetNode("V/Deadline/Registration/Student"),
                qsc=tprogram.anchor).filter(
                    user__isnull=True).order_by("-startdate"))
        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.startdate
            template_prog["student_reg_end"] = newest_bit.enddate

        teacher_reg_bits = list(
            UserBit.objects.bits_get_users(
                verb=GetNode("V/Deadline/Registration/Teacher"),
                qsc=tprogram.anchor).filter(
                    user__isnull=True).order_by("-startdate"))
        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.startdate
            template_prog["teacher_reg_end"] = newest_bit.enddate

        line_items = LineItemType.objects.filter(
            anchor__name="Required",
            anchor__parent__parent=tprogram.anchor).values(
                "amount", "finaid_amount")

        template_prog["base_cost"] = int(
            -sum([x["amount"] for x in line_items]))
        template_prog["finaid_cost"] = int(
            -sum([x["finaid_amount"] for x in line_items]))

    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():
            # Fix the anchor friendly name right away, otherwise in-memory caches cause (mild) issues later on
            anchor = GetNode(pcf.cleaned_data['anchor'].get_uri() + "/" +
                             pcf.cleaned_data["term"])
            anchor.friendly_name = pcf.cleaned_data['term_friendly']
            anchor.save()

            new_prog = pcf.save(
                commit=False)  # don't save, we need to fix it up:
            new_prog.anchor = anchor
            new_prog.save()
            pcf.save_m2m()

            commit_program(new_prog, context['datatrees'], context['userbits'],
                           context['modules'], context['costs'])

            # 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.anchor.parent.name,
                                               new_prog.anchor.name)
                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_member(students_list_name, [
                        new_prog.director_email,
                        settings.DEFAULT_EMAIL_ADDRESSES['archive']
                    ])
                    add_list_member(teachers_list_name, [
                        new_prog.director_email,
                        settings.DEFAULT_EMAIL_ADDRESSES['archive']
                    ])

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

    #   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)
            datatrees, userbits, 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,
                'datatrees':
                datatrees,
                'userbits':
                userbits,
                'modules':
                modules,
                'costs': (form.cleaned_data['base_cost'],
                          form.cleaned_data['finaid_cost'])
            })
            request.session['context_str'] = context_pickled

            return render_to_response(
                'program/newprogram_review.html', request,
                GetNode('Q/Programs/'), {
                    'prog': temp_prog,
                    'datatrees': datatrees,
                    'userbits': userbits,
                    '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, GetNode('Q/Programs/'), {
            'form': form,
            'programs': Program.objects.all().order_by('-id'),
            'template_prog_id': template_prog_id
        })
Example #8
0
    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