enrollment.py 19.4 KB
Newer Older
1 2 3 4 5 6
"""
Enrollment operations for use by instructor APIs.

Does not include any access control, be sure to check access before calling.
"""

7
import crum
8
import json
9
import logging
10
from django.contrib.auth.models import User
11 12 13
from django.conf import settings
from django.core.urlresolvers import reverse
from django.core.mail import send_mail
14
from django.utils.translation import override as override_language
15

16
from course_modes.models import CourseMode
17
from courseware.models import StudentModule
18 19
from courseware.model_data import FieldDataCache
from courseware.module_render import get_module_for_descriptor
David Baumgold committed
20
from edxmako.shortcuts import render_to_string
Sanford Student committed
21 22
from lms.djangoapps.grades.scores import weighted_score
from lms.djangoapps.grades.signals.signals import SCORE_CHANGED
23 24
from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
25
from openedx.core.djangoapps.user_api.models import UserPreference
26 27
from submissions import api as sub_api  # installed from the edx-submissions repository
from student.models import CourseEnrollment, CourseEnrollmentAllowed, anonymous_id_for_user
28 29 30 31 32
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.exceptions import ItemNotFoundError


log = logging.getLogger(__name__)
33

34

35 36 37 38
class EmailEnrollmentState(object):
    """ Store the complete enrollment state of an email in a class """
    def __init__(self, course_id, email):
        exists_user = User.objects.filter(email=email).exists()
39 40
        if exists_user:
            user = User.objects.get(email=email)
41 42 43
            mode, is_active = CourseEnrollment.enrollment_mode_for_user(user, course_id)
            # is_active is `None` if the user is not enrolled in the course
            exists_ce = is_active is not None and is_active
44
            full_name = user.profile.name
45
        else:
46
            mode = None
47
            exists_ce = False
48
            full_name = None
49
        ceas = CourseEnrollmentAllowed.objects.filter(course_id=course_id, email=email).all()
50
        exists_allowed = ceas.exists()
51 52 53 54 55 56
        state_auto_enroll = exists_allowed and ceas[0].auto_enroll

        self.user = exists_user
        self.enrollment = exists_ce
        self.allowed = exists_allowed
        self.auto_enroll = bool(state_auto_enroll)
57
        self.full_name = full_name
58
        self.mode = mode
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85

    def __repr__(self):
        return "{}(user={}, enrollment={}, allowed={}, auto_enroll={})".format(
            self.__class__.__name__,
            self.user,
            self.enrollment,
            self.allowed,
            self.auto_enroll,
        )

    def to_dict(self):
        """
        example: {
            'user': False,
            'enrollment': False,
            'allowed': True,
            'auto_enroll': True,
        }
        """
        return {
            'user': self.user,
            'enrollment': self.enrollment,
            'allowed': self.allowed,
            'auto_enroll': self.auto_enroll,
        }


86 87 88 89 90
def get_user_email_language(user):
    """
    Return the language most appropriate for writing emails to user. Returns
    None if the preference has not been set, or if the user does not exist.
    """
91 92 93
    # Calling UserPreference directly instead of get_user_preference because the user requesting the
    # information is not "user" and also may not have is_staff access.
    return UserPreference.get_value(user, LANGUAGE_KEY)
94 95 96


def enroll_email(course_id, student_email, auto_enroll=False, email_students=False, email_params=None, language=None):
97
    """
98
    Enroll a student by email.
99

100 101 102 103
    `student_email` is student's emails e.g. "foo@bar.com"
    `auto_enroll` determines what is put in CourseEnrollmentAllowed.auto_enroll
        if auto_enroll is set, then when the email registers, they will be
        enrolled in the course automatically.
104 105
    `email_students` determines if student should be notified of action by email.
    `email_params` parameters used while parsing email templates (a `dict`).
106
    `language` is the language used to render the email.
107

108 109
    returns two EmailEnrollmentState's
        representing state before and after the action.
110
    """
111
    previous_state = EmailEnrollmentState(course_id, student_email)
112
    enrollment_obj = None
113
    if previous_state.user:
114 115
        # if the student is currently unenrolled, don't enroll them in their
        # previous mode
116 117 118 119 120 121 122 123

        # for now, White Labels use 'shoppingcart' which is based on the
        # "honor" course_mode. Given the change to use "audit" as the default
        # course_mode in Open edX, we need to be backwards compatible with
        # how White Labels approach enrollment modes.
        if CourseMode.is_white_label(course_id):
            course_mode = CourseMode.DEFAULT_SHOPPINGCART_MODE_SLUG
        else:
124
            course_mode = None
125

126 127 128
        if previous_state.enrollment:
            course_mode = previous_state.mode

129
        enrollment_obj = CourseEnrollment.enroll_by_email(student_email, course_id, course_mode)
130 131 132 133
        if email_students:
            email_params['message'] = 'enrolled_enroll'
            email_params['email_address'] = student_email
            email_params['full_name'] = previous_state.full_name
134
            send_mail_to_student(student_email, email_params, language=language)
135 136 137 138
    else:
        cea, _ = CourseEnrollmentAllowed.objects.get_or_create(course_id=course_id, email=student_email)
        cea.auto_enroll = auto_enroll
        cea.save()
139 140 141
        if email_students:
            email_params['message'] = 'allowed_enroll'
            email_params['email_address'] = student_email
142
            send_mail_to_student(student_email, email_params, language=language)
143

144 145
    after_state = EmailEnrollmentState(course_id, student_email)

146
    return previous_state, after_state, enrollment_obj
147 148


149
def unenroll_email(course_id, student_email, email_students=False, email_params=None, language=None):
150
    """
151
    Unenroll a student by email.
152

153
    `student_email` is student's emails e.g. "foo@bar.com"
154 155
    `email_students` determines if student should be notified of action by email.
    `email_params` parameters used while parsing email templates (a `dict`).
156
    `language` is the language used to render the email.
157

158 159
    returns two EmailEnrollmentState's
        representing state before and after the action.
160
    """
161 162
    previous_state = EmailEnrollmentState(course_id, student_email)
    if previous_state.enrollment:
163
        CourseEnrollment.unenroll_by_email(student_email, course_id)
164 165 166 167
        if email_students:
            email_params['message'] = 'enrolled_unenroll'
            email_params['email_address'] = student_email
            email_params['full_name'] = previous_state.full_name
168
            send_mail_to_student(student_email, email_params, language=language)
169 170 171

    if previous_state.allowed:
        CourseEnrollmentAllowed.objects.get(course_id=course_id, email=student_email).delete()
172 173 174 175
        if email_students:
            email_params['message'] = 'allowed_unenroll'
            email_params['email_address'] = student_email
            # Since no User object exists for this student there is no "full_name" available.
176
            send_mail_to_student(student_email, email_params, language=language)
177 178

    after_state = EmailEnrollmentState(course_id, student_email)
179

180
    return previous_state, after_state
181 182


183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
def send_beta_role_email(action, user, email_params):
    """
    Send an email to a user added or removed as a beta tester.

    `action` is one of 'add' or 'remove'
    `user` is the User affected
    `email_params` parameters used while parsing email templates (a `dict`).
    """
    if action == 'add':
        email_params['message'] = 'add_beta_tester'
        email_params['email_address'] = user.email
        email_params['full_name'] = user.profile.name

    elif action == 'remove':
        email_params['message'] = 'remove_beta_tester'
        email_params['email_address'] = user.email
        email_params['full_name'] = user.profile.name

    else:
        raise ValueError("Unexpected action received '{}' - expected 'add' or 'remove'".format(action))

204
    send_mail_to_student(user.email, email_params, language=get_user_email_language(user))
205 206


207
def reset_student_attempts(course_id, student, module_state_key, requesting_user, delete_module=False):
208 209 210 211 212 213
    """
    Reset student attempts for a problem. Optionally deletes all student state for the specified problem.

    In the previous instructor dashboard it was possible to modify/delete
    modules that were not problems. That has been disabled for safety.

214 215 216 217
    `student` is a User
    `problem_to_reset` is the name of a problem e.g. 'L2Node1'.
    To build the module_state_key 'problem/' and course information will be appended to `problem_to_reset`.

218 219 220 221 222
    Raises:
        ValueError: `problem_state` is invalid JSON.
        StudentModule.DoesNotExist: could not load the student module.
        submissions.SubmissionError: unexpected error occurred while resetting the score in the submissions API.

223
    """
224 225 226
    user_id = anonymous_id_for_user(student, course_id)
    requesting_user_id = anonymous_id_for_user(requesting_user, course_id)
    submission_cleared = False
227 228 229 230 231 232
    try:
        # A block may have children. Clear state on children first.
        block = modulestore().get_item(module_state_key)
        if block.has_children:
            for child in block.children:
                try:
233
                    reset_student_attempts(course_id, student, child, requesting_user, delete_module=delete_module)
234 235 236
                except StudentModule.DoesNotExist:
                    # If a particular child doesn't have any state, no big deal, as long as the parent does.
                    pass
237 238 239 240 241 242 243 244 245 246 247 248
        if delete_module:
            # Some blocks (openassessment) use StudentModule data as a key for internal submission data.
            # Inform these blocks of the reset and allow them to handle their data.
            clear_student_state = getattr(block, "clear_student_state", None)
            if callable(clear_student_state):
                clear_student_state(
                    user_id=user_id,
                    course_id=unicode(course_id),
                    item_id=unicode(module_state_key),
                    requesting_user_id=requesting_user_id
                )
                submission_cleared = True
249
    except ItemNotFoundError:
250
        block = None
251 252
        log.warning("Could not find %s in modulestore when attempting to reset attempts.", module_state_key)

253 254 255 256 257 258
    # Reset the student's score in the submissions API, if xblock.clear_student_state has not done so already.
    # We need to do this before retrieving the `StudentModule` model, because a score may exist with no student module.

    # TODO: Should the LMS know about sub_api and call this reset, or should it generically call it on all of its
    # xblock services as well?  See JIRA ARCH-26.
    if delete_module and not submission_cleared:
259
        sub_api.reset_score(
260
            user_id,
261 262
            course_id.to_deprecated_string(),
            module_state_key.to_deprecated_string(),
263 264 265 266 267
        )

    module_to_reset = StudentModule.objects.get(
        student_id=student.id,
        course_id=course_id,
268
        module_state_key=module_state_key
269
    )
270 271 272

    if delete_module:
        module_to_reset.delete()
273
        _fire_score_changed_for_block(course_id, student, block, module_state_key)
274 275 276 277 278
    else:
        _reset_module_attempts(module_to_reset)


def _reset_module_attempts(studentmodule):
279 280 281 282 283
    """
    Reset the number of attempts on a studentmodule.

    Throws ValueError if `problem_state` is invalid JSON.
    """
284 285 286 287 288 289 290 291
    # load the state json
    problem_state = json.loads(studentmodule.state)
    # old_number_of_attempts = problem_state["attempts"]
    problem_state["attempts"] = 0

    # save
    studentmodule.state = json.dumps(problem_state)
    studentmodule.save()
292 293


294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
def _fire_score_changed_for_block(course_id, student, block, module_state_key):
    """
    Fires a SCORE_CHANGED event for the given module. The earned points are
    always zero. We must retrieve the possible points from the XModule, as
    noted below.
    """
    if block and block.has_score:
        cache = FieldDataCache.cache_for_descriptor_descendents(
            course_id=course_id,
            user=student,
            descriptor=block,
            depth=0
        )
        # For implementation reasons, we need to pull the max_score from the XModule,
        # even though the data is not user-specific.  Here we bind the data to the
        # current user.
        request = crum.get_current_request()
        module = get_module_for_descriptor(
            user=student,
            request=request,
            descriptor=block,
            field_data_cache=cache,
            course_key=course_id
        )
318 319 320 321 322
        max_score = module.max_score()
        if max_score is None:
            return
        else:
            points_earned, points_possible = weighted_score(0, max_score, getattr(module, 'weight', None))
323 324 325 326 327 328
    else:
        points_earned, points_possible = 0, 0
    SCORE_CHANGED.send(
        sender=None,
        points_possible=points_possible,
        points_earned=points_earned,
329
        user_id=student.id,
Sanford Student committed
330 331
        course_id=unicode(course_id),
        usage_id=unicode(module_state_key)
332 333 334
    )


335
def get_email_params(course, auto_enroll, secure=True, course_key=None, display_name=None):
336 337 338 339 340 341 342
    """
    Generate parameters used when parsing email templates.

    `auto_enroll` is a flag for auto enrolling non-registered students: (a `boolean`)
    Returns a dict of parameters
    """

343
    protocol = 'https' if secure else 'http'
344
    course_key = course_key or course.id.to_deprecated_string()
345
    display_name = display_name or course.display_name_with_default_escaped
346

347
    stripped_site_name = configuration_helpers.get_value(
348 349 350
        'SITE_NAME',
        settings.SITE_NAME
    )
351
    # TODO: Use request.build_absolute_uri rather than '{proto}://{site}{path}'.format
352
    # and check with the Services team that this works well with microsites
353 354 355
    registration_url = u'{proto}://{site}{path}'.format(
        proto=protocol,
        site=stripped_site_name,
356
        path=reverse('register_user')
357
    )
358 359 360
    course_url = u'{proto}://{site}{path}'.format(
        proto=protocol,
        site=stripped_site_name,
361
        path=reverse('course_root', kwargs={'course_id': course_key})
362 363 364 365 366
    )

    # We can't get the url to the course's About page if the marketing site is enabled.
    course_about_url = None
    if not settings.FEATURES.get('ENABLE_MKTG_SITE', False):
367 368 369
        course_about_url = u'{proto}://{site}{path}'.format(
            proto=protocol,
            site=stripped_site_name,
370
            path=reverse('about_course', kwargs={'course_id': course_key})
371 372
        )

373 374 375 376 377 378 379
    is_shib_course = uses_shib(course)

    # Composition of email
    email_params = {
        'site_name': stripped_site_name,
        'registration_url': registration_url,
        'course': course,
380
        'display_name': display_name,
381
        'auto_enroll': auto_enroll,
382 383
        'course_url': course_url,
        'course_about_url': course_about_url,
384 385 386 387 388
        'is_shib_course': is_shib_course,
    }
    return email_params


389
def send_mail_to_student(student, param_dict, language=None):
390 391 392 393 394 395 396 397
    """
    Construct the email using templates and then send it.
    `student` is the student's email address (a `str`),

    `param_dict` is a `dict` with keys
    [
        `site_name`: name given to edX instance (a `str`)
        `registration_url`: url for registration (a `str`)
398
        `display_name` : display name of a course (a `str`)
399 400 401 402 403 404 405 406 407
        `course_id`: id of course (a `str`)
        `auto_enroll`: user input option (a `str`)
        `course_url`: url of course (a `str`)
        `email_address`: email of student (a `str`)
        `full_name`: student full name (a `str`)
        `message`: type of email to send and template to use (a `str`)
        `is_shib_course`: (a `boolean`)
    ]

408 409 410 411
    `language` is the language used to render the email. If None the language
    of the currently-logged in user (that is, the user sending the email) will
    be used.

412 413 414
    Returns a boolean indicating whether the email was sent successfully.
    """

415
    # add some helpers and microconfig subsitutions
416 417
    if 'display_name' in param_dict:
        param_dict['course_name'] = param_dict['display_name']
418

419
    param_dict['site_name'] = configuration_helpers.get_value(
420 421 422 423 424 425 426
        'SITE_NAME',
        param_dict['site_name']
    )

    subject = None
    message = None

427 428
    # see if there is an activation email template definition available as configuration,
    # if so, then render that
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
    message_type = param_dict['message']

    email_template_dict = {
        'allowed_enroll': (
            'emails/enroll_email_allowedsubject.txt',
            'emails/enroll_email_allowedmessage.txt'
        ),
        'enrolled_enroll': (
            'emails/enroll_email_enrolledsubject.txt',
            'emails/enroll_email_enrolledmessage.txt'
        ),
        'allowed_unenroll': (
            'emails/unenroll_email_subject.txt',
            'emails/unenroll_email_allowedmessage.txt'
        ),
        'enrolled_unenroll': (
            'emails/unenroll_email_subject.txt',
            'emails/unenroll_email_enrolledmessage.txt'
447 448 449 450 451 452 453 454 455
        ),
        'add_beta_tester': (
            'emails/add_beta_tester_email_subject.txt',
            'emails/add_beta_tester_email_message.txt'
        ),
        'remove_beta_tester': (
            'emails/remove_beta_tester_email_subject.txt',
            'emails/remove_beta_tester_email_message.txt'
        ),
asadiqbal08 committed
456 457 458 459
        'account_creation_and_enrollment': (
            'emails/enroll_email_enrolledsubject.txt',
            'emails/account_creation_and_enroll_emailMessage.txt'
        ),
460
    }
461

462
    subject_template, message_template = email_template_dict.get(message_type, (None, None))
463
    if subject_template is not None and message_template is not None:
464 465 466
        subject, message = render_message_to_string(
            subject_template, message_template, param_dict, language=language
        )
467

468
    if subject and message:
469 470 471 472 473
        # Remove leading and trailing whitespace from body
        message = message.strip()

        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
474
        from_address = configuration_helpers.get_value(
475 476 477 478 479
            'email_from_address',
            settings.DEFAULT_FROM_EMAIL
        )

        send_mail(subject, message, from_address, [student], fail_silently=False)
480 481


482 483 484 485 486 487 488 489 490
def render_message_to_string(subject_template, message_template, param_dict, language=None):
    """
    Render a mail subject and message templates using the parameters from
    param_dict and the given language. If language is None, the platform
    default language is used.

    Returns two strings that correspond to the rendered, translated email
    subject and message.
    """
491
    language = language or settings.LANGUAGE_CODE
492 493 494 495 496 497 498 499 500 501 502 503 504
    with override_language(language):
        return get_subject_and_message(subject_template, message_template, param_dict)


def get_subject_and_message(subject_template, message_template, param_dict):
    """
    Return the rendered subject and message with the appropriate parameters.
    """
    subject = render_to_string(subject_template, param_dict)
    message = render_to_string(message_template, param_dict)
    return subject, message


505 506 507 508 509 510
def uses_shib(course):
    """
    Used to return whether course has Shibboleth as the enrollment domain

    Returns a boolean indicating if Shibboleth authentication is set for this course.
    """
511
    return course.enrollment_domain and course.enrollment_domain.startswith(settings.SHIBBOLETH_DOMAIN_PREFIX)