Skip to content
Snippets Groups Projects
models.py 77.3 KiB
Newer Older
        enrollment, created = cls.objects.get_or_create(
            user=user,
            course_id=course_key,
        )
        # If we *did* just create a new enrollment, set some defaults
        if created:
            enrollment.mode = CourseMode.DEFAULT_MODE_SLUG
            enrollment.is_active = False
            enrollment.save()
Julia Hansbrough's avatar
Julia Hansbrough committed

        return enrollment

Awais's avatar
Awais committed
    @classmethod
    def get_enrollment(cls, user, course_key):
        """Returns a CoursewareEnrollment object.

        Args:
            user (User): The user associated with the enrollment.
            course_id (CourseKey): The key of the course associated with the enrollment.

        Returns:
            Course enrollment object or None
        """
        try:
Awais's avatar
Awais committed
                user=user,
                course_id=course_key
            )
        except cls.DoesNotExist:
            return None

    @classmethod
    def is_enrollment_closed(cls, user, course):
        """
        Returns a boolean value regarding whether the user has access to enroll in the course. Returns False if the
        enrollment has been closed.
        """
        # Disable the pylint error here, as per ormsbee. This local import was previously
        # in CourseEnrollment.enroll
        from courseware.access import has_access  # pylint: disable=import-error
        return not has_access(user, 'enroll', course)

    def update_enrollment(self, mode=None, is_active=None, skip_refund=False):
Julia Hansbrough's avatar
Julia Hansbrough committed
        """
        Updates an enrollment for a user in a class.  This includes options
        like changing the mode, toggling is_active True/False, etc.

        Also emits relevant events for analytics purposes.

        This saves immediately.
Julia Hansbrough's avatar
Julia Hansbrough committed
        """
Gabe Mulley's avatar
Gabe Mulley committed
        activation_changed = False
Julia Hansbrough's avatar
Julia Hansbrough committed
        # if is_active is None, then the call to update_enrollment didn't specify
        # any value, so just leave is_active as it is
Julia Hansbrough's avatar
Julia Hansbrough committed
        if self.is_active != is_active and is_active is not None:
            self.is_active = is_active
Gabe Mulley's avatar
Gabe Mulley committed
            activation_changed = True

        mode_changed = False
        # if mode is None, the call to update_enrollment didn't specify a new
Julia Hansbrough's avatar
Julia Hansbrough committed
        # mode, so leave as-is
Julia Hansbrough's avatar
Julia Hansbrough committed
        if self.mode != mode and mode is not None:
            self.mode = mode
Gabe Mulley's avatar
Gabe Mulley committed
            mode_changed = True

        if activation_changed or mode_changed:
Julia Hansbrough's avatar
Julia Hansbrough committed
            self.save()
Julia Hansbrough's avatar
Julia Hansbrough committed
        if activation_changed:
            if self.is_active:
                self.emit_event(EVENT_NAME_ENROLLMENT_ACTIVATED)
                    tags=[u"org:{}".format(self.course_id.org),
                          u"offering:{}".format(self.course_id.offering),
            else:
                UNENROLL_DONE.send(sender=None, course_enrollment=self, skip_refund=skip_refund)
Julia Hansbrough's avatar
Julia Hansbrough committed
                self.emit_event(EVENT_NAME_ENROLLMENT_DEACTIVATED)
                dog_stats_api.increment(
                    "common.student.unenrollment",
                    tags=[u"org:{}".format(self.course_id.org),
                          u"offering:{}".format(self.course_id.offering),
        if mode_changed:
            # Only emit mode change events when the user's enrollment
            # mode has changed from its previous setting
            self.emit_event(EVENT_NAME_ENROLLMENT_MODE_CHANGED)
Gabe Mulley's avatar
Gabe Mulley committed
    def emit_event(self, event_name):
        """
        Emits an event to explicitly track course enrollment and unenrollment.
        """

        try:
            context = contexts.course_context_from_course_id(self.course_id)
            assert isinstance(self.course_id, CourseKey)
Gabe Mulley's avatar
Gabe Mulley committed
            data = {
                'user_id': self.user.id,
                'course_id': self.course_id.to_deprecated_string(),
Gabe Mulley's avatar
Gabe Mulley committed
                'mode': self.mode,
            }

            with tracker.get_tracker().context(event_name, context):
                tracker.emit(event_name, data)
                if hasattr(settings, 'LMS_SEGMENT_KEY') and settings.LMS_SEGMENT_KEY:
                    tracking_context = tracker.get_tracker().resolve_context()
                    analytics.track(self.user_id, event_name, {
                        'category': 'conversion',
                        'label': self.course_id.to_deprecated_string(),
                        'org': self.course_id.org,
                        'course': self.course_id.course,
                        'run': self.course_id.run,
                        'mode': self.mode,
                        'ip': tracking_context.get('ip'),
                        'Google Analytics': {
                            'clientId': tracking_context.get('client_id')
                        }
Gabe Mulley's avatar
Gabe Mulley committed
        except:  # pylint: disable=bare-except
            if event_name and self.course_id:
                log.exception(
                    u'Unable to emit event %s for user %s and course %s',
                    event_name,
                    self.user.username,
    def enroll(cls, user, course_key, mode=None, check_access=False):
        """
        Enroll a user in a course. This saves immediately.

        Returns a CoursewareEnrollment object.

        `user` is a Django User object. If it hasn't been saved yet (no `.id`
               attribute), this method will automatically save it before
               adding an enrollment for it.

Julia Hansbrough's avatar
Julia Hansbrough committed
        `course_key` is our usual course_id string (e.g. "edX/Test101/2013_Fall)

        `mode` is a string specifying what kind of enrollment this is. The
               default is the default course mode, 'audit'. Other options
               include 'professional', 'verified', 'honor',
               'no-id-professional' and 'credit'.
               See CourseMode in common/djangoapps/course_modes/models.py.
Julia Hansbrough's avatar
Julia Hansbrough committed
        `check_access`: if True, we check that an accessible course actually
                exists for the given course_key before we enroll the student.
                The default is set to False to avoid breaking legacy code or
                code with non-standard flows (ex. beta tester invitations), but
                for any standard enrollment flow you probably want this to be True.

Julia Hansbrough's avatar
Julia Hansbrough committed
        Exceptions that can be raised: NonExistentCourseError,
        EnrollmentClosedError, CourseFullError, AlreadyEnrolledError.  All these
        are subclasses of CourseEnrollmentException if you want to catch all of
        them in the same way.

        It is expected that this method is called from a method which has already
        verified the user authentication.

        Also emits relevant events for analytics purposes.
        if mode is None:
            mode = _default_course_mode(unicode(course_key))
        # All the server-side checks for whether a user is allowed to enroll.
        try:
            course = CourseOverview.get_from_id(course_key)
        except CourseOverview.DoesNotExist:
            # This is here to preserve legacy behavior which allowed enrollment in courses
            # announced before the start of content creation.
            if check_access:
                log.warning(u"User %s failed to enroll in non-existent course %s", user.username, unicode(course_key))
                raise NonExistentCourseError
Julia Hansbrough's avatar
Julia Hansbrough committed

Julia Hansbrough's avatar
Julia Hansbrough committed
        if check_access:
            if cls.is_enrollment_closed(user, course):
Julia Hansbrough's avatar
Julia Hansbrough committed
                log.warning(
                    u"User %s failed to enroll in course %s because enrollment is closed",
                    user.username,
                    course_key.to_deprecated_string()
Julia Hansbrough's avatar
Julia Hansbrough committed
                raise EnrollmentClosedError

            if cls.objects.is_course_full(course):
Julia Hansbrough's avatar
Julia Hansbrough committed
                log.warning(
                    u"Course %s has reached its maximum enrollment of %d learners. User %s failed to enroll.",
                    course_key.to_deprecated_string(),
                    course.max_student_enrollments_allowed,
                    user.username,
Julia Hansbrough's avatar
Julia Hansbrough committed
                raise CourseFullError
        if cls.is_enrolled(user, course_key):
                u"User %s attempted to enroll in %s, but they were already enrolled",
                user.username,
                course_key.to_deprecated_string()
Julia Hansbrough's avatar
Julia Hansbrough committed
            if check_access:
                raise AlreadyEnrolledError

        # User is allowed to enroll if they've reached this point.
        enrollment = cls.get_or_create_enrollment(user, course_key)
        enrollment.update_enrollment(is_active=True, mode=mode)
        if badges_enabled():
            from lms.djangoapps.badges.events.course_meta import award_enrollment_badge
            award_enrollment_badge(user)

Julia Hansbrough's avatar
Julia Hansbrough committed
        return enrollment
    def enroll_by_email(cls, email, course_id, mode=None, ignore_errors=True):
        """
        Enroll a user in a course given their email. This saves immediately.

        Note that  enrolling by email is generally done in big batches and the
        error rate is high. For that reason, we supress User lookup errors by
        default.

        Returns a CoursewareEnrollment object. If the User does not exist and
        `ignore_errors` is set to `True`, it will return None.

        `email` Email address of the User to add to enroll in the course.

        `course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall)

        `mode` is a string specifying what kind of enrollment this is. The
               default is the default course mode, 'audit'. Other options
               include 'professional', 'verified', 'honor',
               'no-id-professional' and 'credit'.
               See CourseMode in common/djangoapps/course_modes/models.py.

        `ignore_errors` is a boolean indicating whether we should suppress
                        `User.DoesNotExist` errors (returning None) or let it
                        bubble up.

        It is expected that this method is called from a method which has already
        verified the user authentication and access.
        """
        try:
            user = User.objects.get(email=email)
            return cls.enroll(user, course_id, mode)
        except User.DoesNotExist:
            err_msg = u"Tried to enroll email {} into course {}, but user not found"
            log.error(err_msg.format(email, course_id))
            if ignore_errors:
                return None
            raise

    @classmethod
    def unenroll(cls, user, course_id, skip_refund=False):
        """
        Remove the user from a given course. If the relevant `CourseEnrollment`
        object doesn't exist, we log an error but don't throw an exception.

        `user` is a Django User object. If it hasn't been saved yet (no `.id`
               attribute), this method will automatically save it before
               adding an enrollment for it.

        `course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall)
        `skip_refund` can be set to True to avoid the refund process.
            record = cls.objects.get(user=user, course_id=course_id)
            record.update_enrollment(is_active=False, skip_refund=skip_refund)
            log.error(
                u"Tried to unenroll student %s from %s but they were not enrolled",
                user,
                course_id
            )

    @classmethod
    def unenroll_by_email(cls, email, course_id):
        """
        Unenroll a user from a course given their email. This saves immediately.
        User lookup errors are logged but will not throw an exception.

        `email` Email address of the User to unenroll from the course.

        `course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall)
        """
        try:
            user = User.objects.get(email=email)
            return cls.unenroll(user, course_id)
        except User.DoesNotExist:
            log.error(
                u"Tried to unenroll email %s from course %s, but user not found",
                email,
                course_id
            )
    def is_enrolled(cls, user, course_key):
        """
        Returns True if the user is enrolled in the course (the entry must exist
        and it must have `is_active=True`). Otherwise, returns False.

        `user` is a Django User object. If it hasn't been saved yet (no `.id`
               attribute), this method will automatically save it before
               adding an enrollment for it.

        `course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall)
        """
        if not user.is_authenticated():
            return False
cewing's avatar
cewing committed

            record = cls.objects.get(user=user, course_id=course_key)
            return record.is_active
        except cls.DoesNotExist:
            return False

    @classmethod
    def is_enrolled_by_partial(cls, user, course_id_partial):
        """
        Returns `True` if the user is enrolled in a course that starts with
        `course_id_partial`. Otherwise, returns False.

        Can be used to determine whether a student is enrolled in a course
        whose run name is unknown.

        `user` is a Django User object. If it hasn't been saved yet (no `.id`
               attribute), this method will automatically save it before
               adding an enrollment for it.

        `course_id_partial` (CourseKey) is missing the run component
        assert isinstance(course_id_partial, CourseKey)
        assert not course_id_partial.run  # None or empty string
        course_key = SlashSeparatedCourseKey(course_id_partial.org, course_id_partial.course, '')
        querystring = unicode(course_key.to_deprecated_string())
            return cls.objects.filter(
Julian Arni's avatar
Julian Arni committed
                user=user,
Julian Arni's avatar
Julian Arni committed
                is_active=1
            ).exists()
        except cls.DoesNotExist:
            return False

    @classmethod
    def enrollment_mode_for_user(cls, user, course_id):
        """
        Returns the enrollment mode for the given user for the given course

        `user` is a Django User object
        `course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall)
        Returns (mode, is_active) where mode is the enrollment mode of the student
            and is_active is whether the enrollment is active.
        Returns (None, None) if the courseenrollment record does not exist.
            record = cls.objects.get(user=user, course_id=course_id)
            return (record.mode, record.is_active)
    @classmethod
    def enrollments_for_user(cls, user):
        return cls.objects.filter(user=user, is_active=1)
    def is_paid_course(self):
        """
        Returns True, if course is paid
        """
        paid_course = CourseMode.is_white_label(self.course_id)
        if paid_course or CourseMode.is_professional_slug(self.mode):
    def activate(self):
        """Makes this `CourseEnrollment` record active. Saves immediately."""
Julia Hansbrough's avatar
Julia Hansbrough committed
        self.update_enrollment(is_active=True)

    def deactivate(self):
        """Makes this `CourseEnrollment` record inactive. Saves immediately. An
        inactive record means that the student is not enrolled in this course.
        """
Julia Hansbrough's avatar
Julia Hansbrough committed
        self.update_enrollment(is_active=False)
        """Changes this `CourseEnrollment` record's mode to `mode`.  Saves immediately."""
Julia Hansbrough's avatar
Julia Hansbrough committed
        self.update_enrollment(mode=mode)
ichuang's avatar
ichuang committed

    def refundable(self):
        """
        For paid/verified certificates, students may receive a refund if they have
        a verified certificate and the deadline for refunds has not yet passed.
        """
        # In order to support manual refunds past the deadline, set can_refund on this object.
Sarina Canelake's avatar
Sarina Canelake committed
        # On unenrolling, the "UNENROLL_DONE" signal calls CertificateItem.refund_cert_callback(),
        # which calls this method to determine whether to refund the order.
        # This can't be set directly because refunds currently happen as a side-effect of unenrolling.
        # (side-effects are bad)
        if getattr(self, 'can_refund', None) is not None:
            return True

        # If the student has already been given a certificate they should not be refunded
        if GeneratedCertificate.certificate_for_student(self.user, self.course_id) is not None:
            return False

        # If it is after the refundable cutoff date they should not be refunded.
        refund_cutoff_date = self.refund_cutoff_date()
        if refund_cutoff_date and datetime.now(UTC) > refund_cutoff_date:
            return False
        course_mode = CourseMode.mode_for_course(self.course_id, 'verified')
        if course_mode is None:
            return False
        else:
            return True

    def refund_cutoff_date(self):
        """ Calculate and return the refund window end date. """
        try:
            attribute = self.attributes.get(namespace='order', name='order_number')
        except ObjectDoesNotExist:
            return None

        order_number = attribute.value
        order = ecommerce_api_client(self.user).orders(order_number).get()
        refund_window_start_date = max(
            datetime.strptime(order['date_placed'], ECOMMERCE_DATE_FORMAT),
            self.course_overview.start.replace(tzinfo=None)
        )

        return refund_window_start_date.replace(tzinfo=UTC) + EnrollmentRefundConfiguration.current().refund_window
    @property
    def username(self):
        return self.user.username

    @property
    def course(self):
        # Deprecated. Please use the `course_overview` property instead.
        return self.course_overview
    @property
    def course_overview(self):
        """
        Returns a CourseOverview of the course to which this enrollment refers.
        Returns None if an error occurred while trying to load the course.

        Note:
            If the course is re-published within the lifetime of this
            CourseEnrollment object, then the value of this property will
            become stale.
       """
        if not self._course_overview:
            try:
                self._course_overview = CourseOverview.get_from_id(self.course_id)
            except (CourseOverview.DoesNotExist, IOError):
                self._course_overview = None
        return self._course_overview
    def is_verified_enrollment(self):
        """
        Check the course enrollment mode is verified or not
        """
        return CourseMode.is_verified_slug(self.mode)

    def is_professional_enrollment(self):
        """
        Check the course enrollment mode is professional or not
        """
        return CourseMode.is_professional_slug(self.mode)

    @classmethod
    def is_enrolled_as_verified(cls, user, course_key):
        """
        Check whether the course enrollment is for a verified mode.

        Arguments:
            user (User): The user object.
            course_key (CourseKey): The identifier for the course.

        Returns: bool

        """
        enrollment = cls.get_enrollment(user, course_key)
        return (
            enrollment is not None and
            enrollment.is_active and
            enrollment.is_verified_enrollment()
        )

    @classmethod
    def cache_key_name(cls, user_id, course_key):
        """Return cache key name to be used to cache current configuration.
        Args:
            user_id(int): Id of user.
            course_key(unicode): Unicode of course key

        Returns:
            Unicode cache key
        """
        return cls.COURSE_ENROLLMENT_CACHE_KEY.format(user_id, unicode(course_key))


@receiver(models.signals.post_save, sender=CourseEnrollment)
@receiver(models.signals.post_delete, sender=CourseEnrollment)
def invalidate_enrollment_mode_cache(sender, instance, **kwargs):  # pylint: disable=unused-argument, invalid-name
    """Invalidate the cache of CourseEnrollment model. """

    cache_key = CourseEnrollment.cache_key_name(
        instance.user.id,
        unicode(instance.course_id)
    )
    cache.delete(cache_key)

class ManualEnrollmentAudit(models.Model):
    """
    Table for tracking which enrollments were performed through manual enrollment.
    """
    enrollment = models.ForeignKey(CourseEnrollment, null=True)
    enrolled_by = models.ForeignKey(User, null=True)
    enrolled_email = models.CharField(max_length=255, db_index=True)
    time_stamp = models.DateTimeField(auto_now_add=True, null=True)
    state_transition = models.CharField(max_length=255, choices=TRANSITION_STATES)
    reason = models.TextField(null=True)

    @classmethod
    def create_manual_enrollment_audit(cls, user, email, state_transition, reason, enrollment=None):
        """
        saves the student manual enrollment information
        """
        return cls.objects.create(
            enrolled_by=user,
            enrolled_email=email,
            state_transition=state_transition,
            reason=reason,
            enrollment=enrollment
        )

    @classmethod
    def get_manual_enrollment_by_email(cls, email):
        """
        if matches returns the most recent entry in the table filtered by email else returns None.
        """
        try:
            manual_enrollment = cls.objects.filter(enrolled_email=email).latest('time_stamp')
        except cls.DoesNotExist:
            manual_enrollment = None
        return manual_enrollment

    @classmethod
    def get_manual_enrollment(cls, enrollment):
        """
        if matches returns the most recent entry in the table filtered by enrollment else returns None,
        """
        try:
            manual_enrollment = cls.objects.filter(enrollment=enrollment).latest('time_stamp')
        except cls.DoesNotExist:
            manual_enrollment = None
        return manual_enrollment


class CourseEnrollmentAllowed(models.Model):
    """
    Table of users (specified by email address strings) who are allowed to enroll in a specified course.
    The user may or may not (yet) exist.  Enrollment by users listed in this table is allowed
    even if the enrollment time window is past.
    """
    email = models.CharField(max_length=255, db_index=True)
    course_id = CourseKeyField(max_length=255, db_index=True)
    auto_enroll = models.BooleanField(default=0)

    created = models.DateTimeField(auto_now_add=True, null=True, db_index=True)

    class Meta(object):
        unique_together = (('email', 'course_id'),)
    def __unicode__(self):
        return "[CourseEnrollmentAllowed] %s: %s (%s)" % (self.email, self.course_id, self.created)
    @classmethod
    def may_enroll_and_unenrolled(cls, course_id):
        """
        Return QuerySet of students who are allowed to enroll in a course.

        Result excludes students who have already enrolled in the
        course.

        `course_id` identifies the course for which to compute the QuerySet.
        """
        enrolled = CourseEnrollment.objects.users_enrolled_in(course_id=course_id).values_list('email', flat=True)
        return CourseEnrollmentAllowed.objects.filter(course_id=course_id).exclude(email__in=enrolled)


@total_ordering
class CourseAccessRole(models.Model):
    """
    Maps users to org, courses, and roles. Used by student.roles.CourseRole and OrgRole.
    To establish a user as having a specific role over all courses in the org, create an entry
    without a course_id.
    """

    objects = NoneToEmptyManager()

    user = models.ForeignKey(User)
    # blank org is for global group based roles such as course creator (may be deprecated)
    org = models.CharField(max_length=64, db_index=True, blank=True)
    # blank course_id implies org wide role
    course_id = CourseKeyField(max_length=255, db_index=True, blank=True)
    role = models.CharField(max_length=64, db_index=True)

    class Meta(object):
        unique_together = ('user', 'org', 'course_id', 'role')

    @property
    def _key(self):
        """
        convenience function to make eq overrides easier and clearer. arbitrary decision
        that role is primary, followed by org, course, and then user
        """
        return (self.role, self.org, self.course_id, self.user_id)

    def __eq__(self, other):
        """
        Overriding eq b/c the django impl relies on the primary key which requires fetch. sometimes we
        just want to compare roles w/o doing another fetch.
        """
Sarina Canelake's avatar
Sarina Canelake committed
        return type(self) == type(other) and self._key == other._key  # pylint: disable=protected-access

    def __hash__(self):
        return hash(self._key)

    def __lt__(self, other):
        """
        Lexigraphic sort
        """
Sarina Canelake's avatar
Sarina Canelake committed
        return self._key < other._key  # pylint: disable=protected-access
    def __unicode__(self):
        return "[CourseAccessRole] user: {}   role: {}   org: {}   course: {}".format(self.user.username, self.role, self.org, self.course_id)

#### Helper methods for use from python manage.py shell and other classes.

Calen Pennington's avatar
Calen Pennington committed

def get_user_by_username_or_email(username_or_email):
    """
    Return a User object, looking up by email if username_or_email contains a
    '@', otherwise by username.

    Raises:
        User.DoesNotExist is lookup fails.
    """
    if '@' in username_or_email:
        return User.objects.get(email=username_or_email)
    else:
        return User.objects.get(username=username_or_email)
def get_user(email):
Sarina Canelake's avatar
Sarina Canelake committed
    user = User.objects.get(email=email)
    u_prof = UserProfile.objects.get(user=user)
    return user, u_prof

def user_info(email):
Sarina Canelake's avatar
Sarina Canelake committed
    user, u_prof = get_user(email)
    print "User id", user.id
    print "Username", user.username
    print "E-mail", user.email
    print "Name", u_prof.name
    print "Location", u_prof.location
    print "Language", u_prof.language
    return user, u_prof

def change_email(old_email, new_email):
Sarina Canelake's avatar
Sarina Canelake committed
    user = User.objects.get(email=old_email)
    user.email = new_email
    user.save()
def change_name(email, new_name):
Sarina Canelake's avatar
Sarina Canelake committed
    _user, u_prof = get_user(email)
    u_prof.name = new_name
    u_prof.save()
Piotr Mitros's avatar
Piotr Mitros committed
def user_count():
Piotr Mitros's avatar
Piotr Mitros committed
    print "All users", User.objects.all().count()
    print "Active users", User.objects.filter(is_active=True).count()
Piotr Mitros's avatar
Piotr Mitros committed
    return User.objects.all().count()

Piotr Mitros's avatar
Piotr Mitros committed
def active_user_count():
    return User.objects.filter(is_active=True).count()

Piotr Mitros's avatar
Piotr Mitros committed

Piotr Mitros's avatar
Piotr Mitros committed
def create_group(name, description):
    utg = UserTestGroup()
    utg.name = name
    utg.description = description
    utg.save()

def add_user_to_group(user, group):
    utg = UserTestGroup.objects.get(name=group)
    utg.users.add(User.objects.get(username=user))
Piotr Mitros's avatar
Piotr Mitros committed
    utg.save()
def remove_user_from_group(user, group):
    utg = UserTestGroup.objects.get(name=group)
    utg.users.remove(User.objects.get(username=user))
    utg.save()
Sarina Canelake's avatar
Sarina Canelake committed
DEFAULT_GROUPS = {
    'email_future_courses': 'Receive e-mails about future MITx courses',
    'email_helpers': 'Receive e-mails about how to help with MITx',
    'mitx_unenroll': 'Fully unenrolled -- no further communications',
    '6002x_unenroll': 'Took and dropped 6002x'
}

def add_user_to_default_group(user, group):
    try:
        utg = UserTestGroup.objects.get(name=group)
    except UserTestGroup.DoesNotExist:
        utg = UserTestGroup()
        utg.name = group
Sarina Canelake's avatar
Sarina Canelake committed
        utg.description = DEFAULT_GROUPS[group]
    utg.users.add(User.objects.get(username=user))
Piotr Mitros's avatar
Piotr Mitros committed
    utg.save()
ichuang's avatar
ichuang committed

def create_comments_service_user(user):
    if not settings.FEATURES['ENABLE_DISCUSSION_SERVICE']:
        # Don't try--it won't work, and it will fill the logs with lots of errors
        return
Rocky Duan's avatar
Rocky Duan committed
    try:
        cc_user = cc.User.from_django_user(user)
Sarina Canelake's avatar
Sarina Canelake committed
    except Exception:  # pylint: disable=broad-except
        log = logging.getLogger("edx.discussion")  # pylint: disable=redefined-outer-name
        log.error(
            "Could not create comments service user with id {}".format(user.id),
Sarina Canelake's avatar
Sarina Canelake committed
            exc_info=True
        )

# Define login and logout handlers here in the models file, instead of the views file,
# so that they are more likely to be loaded when a Studio user brings up the Studio admin
# page to login.  These are currently the only signals available, so we need to continue
# identifying and logging failures separately (in views).


@receiver(user_logged_in)
Sarina Canelake's avatar
Sarina Canelake committed
def log_successful_login(sender, request, user, **kwargs):  # pylint: disable=unused-argument
    """Handler to log when logins have occurred successfully."""
    if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
        AUDIT_LOG.info(u"Login success - user.id: {0}".format(user.id))
    else:
        AUDIT_LOG.info(u"Login success - {0} ({1})".format(user.username, user.email))
Sarina Canelake's avatar
Sarina Canelake committed
def log_successful_logout(sender, request, user, **kwargs):  # pylint: disable=unused-argument
    """Handler to log when logouts have occurred successfully."""
    if hasattr(request, 'user'):
        if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
            AUDIT_LOG.info(u"Logout - user.id: {0}".format(request.user.id))  # pylint: disable=logging-format-interpolation
        else:
            AUDIT_LOG.info(u"Logout - {0}".format(request.user))  # pylint: disable=logging-format-interpolation


@receiver(user_logged_in)
@receiver(user_logged_out)
Sarina Canelake's avatar
Sarina Canelake committed
def enforce_single_login(sender, request, user, signal, **kwargs):    # pylint: disable=unused-argument
    """
    Sets the current session id in the user profile,
    to prevent concurrent logins.
    """
    if settings.FEATURES.get('PREVENT_CONCURRENT_LOGINS', False):
        if signal == user_logged_in:
            key = request.session.session_key
        else:
            key = None
        if user:
            user.profile.set_login_session(key)


class DashboardConfiguration(ConfigurationModel):
    """Dashboard Configuration settings.

    Includes configuration options for the dashboard, which impact behavior and rendering for the application.

    """
    recent_enrollment_time_delta = models.PositiveIntegerField(
        default=0,
        help_text="The number of seconds in which a new enrollment is considered 'recent'. "
                  "Used to display notifications."
    )

    @property
    def recent_enrollment_seconds(self):
        return self.recent_enrollment_time_delta


class LinkedInAddToProfileConfiguration(ConfigurationModel):
    """
    LinkedIn Add to Profile Configuration

    This configuration enables the "Add to Profile" LinkedIn
    button on the student dashboard.  The button appears when
    users have a certificate available; when clicked,
    users are sent to the LinkedIn site with a pre-filled
    form allowing them to add the certificate to their
    LinkedIn profile.
        "honor": _(u"{platform_name} Honor Code Certificate for {course_name}"),
        "verified": _(u"{platform_name} Verified Certificate for {course_name}"),
        "professional": _(u"{platform_name} Professional Certificate for {course_name}"),
        "no-id-professional": _(
            u"{platform_name} Professional Certificate for {course_name}"
        ),
    }

    company_identifier = models.TextField(
        help_text=_(
            u"The company identifier for the LinkedIn Add-to-Profile button "
    # Deprecated
    dashboard_tracking_code = models.TextField(default="", blank=True)

    trk_partner_name = models.CharField(
        max_length=10,
        default="",
        blank=True,
        help_text=_(
            u"Short identifier for the LinkedIn partner used in the tracking code.  "
            u"(Example: 'edx')  "
            u"If no value is provided, tracking codes will not be sent to LinkedIn."
        )
    )

    def add_to_profile_url(self, course_key, course_name, cert_mode, cert_url, source="o", target="dashboard"):
        """Construct the URL for the "add to profile" button.
            course_key (CourseKey): The identifier for the course.
            course_name (unicode): The display name of the course.
            cert_mode (str): The course mode of the user's certificate (e.g. "verified", "honor", "professional")
            cert_url (str): The download URL for the certificate.

        Keyword Arguments:
            source (str): Either "o" (for onsite/UI), "e" (for emails), or "m" (for mobile)
            target (str): An identifier for the occurrance of the button.
        company_identifier = microsite.get_value('LINKEDIN_COMPANY_ID', self.company_identifier)
            ('_ed', company_identifier),
            ('pfCertificationName', self._cert_name(course_name, cert_mode).encode('utf-8')),
            ('pfCertificationUrl', cert_url),
            ('source', source)
        ])

        tracking_code = self._tracking_code(course_key, cert_mode, target)
        if tracking_code is not None:
            params['trk'] = tracking_code

        return u'http://www.linkedin.com/profile/add?{params}'.format(
            params=urlencode(params)
        )

    def _cert_name(self, course_name, cert_mode):
        """Name of the certification, for display on LinkedIn. """
        return self.MODE_TO_CERT_NAME.get(
            cert_mode,
            _(u"{platform_name} Certificate for {course_name}")
        ).format(
            platform_name=microsite.get_value('platform_name', settings.PLATFORM_NAME),

    def _tracking_code(self, course_key, cert_mode, target):
        """Create a tracking code for the button.

        Tracking codes are used by LinkedIn to collect
        analytics about certifications users are adding
        to their profiles.

        The tracking code format is:
            &trk=[partner name]-[certificate type]-[date]-[target field]

        In our case, we're sending:
            &trk=edx-{COURSE ID}_{COURSE MODE}-{TARGET}

        If no partner code is configured, then this will
        return None, indicating that tracking codes are disabled.

        Arguments:

            course_key (CourseKey): The identifier for the course.
            cert_mode (str): The enrollment mode for the course.
            target (str): Identifier for where the button is located.

        Returns:
            unicode or None

        """
        return (
            u"{partner}-{course_key}_{cert_mode}-{target}".format(
                partner=self.trk_partner_name,
                course_key=unicode(course_key),
                cert_mode=cert_mode,
                target=target
            )
            if self.trk_partner_name else None
        )


class EntranceExamConfiguration(models.Model):
    """
    Represents a Student's entrance exam specific data for a single Course
    """

    user = models.ForeignKey(User, db_index=True)
    course_id = CourseKeyField(max_length=255, db_index=True)
    created = models.DateTimeField(auto_now_add=True, null=True, db_index=True)
    updated = models.DateTimeField(auto_now=True, db_index=True)

    # if skip_entrance_exam is True, then student can skip entrance exam
    # for the course
    skip_entrance_exam = models.BooleanField(default=True)

    class Meta(object):
        unique_together = (('user', 'course_id'), )

    def __unicode__(self):
        return "[EntranceExamConfiguration] %s: %s (%s) = %s" % (
            self.user, self.course_id, self.created, self.skip_entrance_exam
        )

    @classmethod
    def user_can_skip_entrance_exam(cls, user, course_key):
        """
        Return True if given user can skip entrance exam for given course otherwise False.
        """
        can_skip = False
        if is_entrance_exams_enabled():
            try:
                record = EntranceExamConfiguration.objects.get(user=user, course_id=course_key)
                can_skip = record.skip_entrance_exam
            except EntranceExamConfiguration.DoesNotExist:
                can_skip = False
        return can_skip
class LanguageField(models.CharField):
    """Represents a language from the ISO 639-1 language set."""

    def __init__(self, *args, **kwargs):
        """Creates a LanguageField.

        Accepts all the same kwargs as a CharField, except for max_length and
        choices. help_text defaults to a description of the ISO 639-1 set.
        """
        kwargs.pop('max_length', None)
        kwargs.pop('choices', None)
        help_text = kwargs.pop(
            'help_text',
            _("The ISO 639-1 language code for this language."),
        )
        super(LanguageField, self).__init__(
            max_length=16,
            choices=settings.ALL_LANGUAGES,
            help_text=help_text,
            *args,
            **kwargs
        )