Example #1
0
    def get_status(self, user_id, course_id, related_assessment_location):
        """Get verification attempt status against a user for a given
        'checkpoint' and 'course_id'.

        Args:
            user_id (str): User Id string
            course_id (str): A string of course id
            related_assessment_location (str): Location of Reverification XBlock

        Returns: str or None
        """
        user = User.objects.get(id=user_id)
        course_key = CourseKey.from_string(course_id)

        if not CourseEnrollment.is_enrolled_as_verified(user, course_key):
            return self.NON_VERIFIED_TRACK
        elif SkippedReverification.check_user_skipped_reverification_exists(
                user_id, course_key):
            return self.SKIPPED_STATUS

        try:
            checkpoint_status = VerificationStatus.objects.filter(
                user_id=user_id,
                checkpoint__course_id=course_key,
                checkpoint__checkpoint_location=related_assessment_location
            ).latest()
            return checkpoint_status.status
        except ObjectDoesNotExist:
            return None
Example #2
0
    def get_verification_context(self, request, course):
        course_key = CourseKey.from_string(unicode(course.id))

        # Establish whether the course has a verified mode
        available_modes = CourseMode.modes_for_course_dict(unicode(course.id))
        has_verified_mode = CourseMode.has_verified_mode(available_modes)

        # Establish whether the user is already enrolled
        is_already_verified = CourseEnrollment.is_enrolled_as_verified(request.user, course_key)

        # Establish whether the verification deadline has already passed
        verification_deadline = VerifiedUpgradeDeadlineDate(course, request.user)
        deadline_has_passed = verification_deadline.deadline_has_passed()

        # If this proves its worth, we can internationalize and display for more than English speakers.
        show_course_sock = (
            has_verified_mode and not is_already_verified and
            not deadline_has_passed and get_language() == 'en'
        )

        # Get information about the upgrade
        course_price = get_cosmetic_verified_display_price(course)
        upgrade_url = EcommerceService().upgrade_url(request.user, course_key)

        context = {
            'show_course_sock': show_course_sock,
            'course_price': course_price,
            'course_id': course.id,
            'upgrade_url': upgrade_url,
        }

        return context
Example #3
0
    def get_verification_context(self, request, course):
        course_key = CourseKey.from_string(unicode(course.id))

        # Establish whether the course has a verified mode
        available_modes = CourseMode.modes_for_course_dict(unicode(course.id))
        has_verified_mode = CourseMode.has_verified_mode(available_modes)

        # Establish whether the user is already enrolled
        is_already_verified = CourseEnrollment.is_enrolled_as_verified(
            request.user, course_key)

        # Establish whether the verification deadline has already passed
        verification_deadline = VerifiedUpgradeDeadlineDate(
            course, request.user)
        deadline_has_passed = verification_deadline.deadline_has_passed()

        show_course_sock = has_verified_mode and not is_already_verified and not deadline_has_passed

        # Get the price of the course and format correctly
        course_price = get_cosmetic_verified_display_price(course)

        context = {
            'show_course_sock': show_course_sock,
            'course_price': course_price,
            'course_id': course.id
        }

        return context
Example #4
0
    def get_status(self, user_id, course_id, related_assessment_location):
        """Get verification attempt status against a user for a given
        'checkpoint' and 'course_id'.

        Args:
            user_id (str): User Id string
            course_id (str): A string of course id
            related_assessment_location (str): Location of Reverification XBlock

        Returns: str or None
        """
        user = User.objects.get(id=user_id)
        course_key = CourseKey.from_string(course_id)

        if not CourseEnrollment.is_enrolled_as_verified(user, course_key):
            return self.NON_VERIFIED_TRACK
        elif SkippedReverification.check_user_skipped_reverification_exists(user_id, course_key):
            return self.SKIPPED_STATUS

        try:
            checkpoint_status = VerificationStatus.objects.filter(
                user_id=user_id,
                checkpoint__course_id=course_key,
                checkpoint__checkpoint_location=related_assessment_location
            ).latest()
            return checkpoint_status.status
        except ObjectDoesNotExist:
            return None
    def get_verification_context(self, request, course):
        course_key = CourseKey.from_string(unicode(course.id))

        # Establish whether the course has a verified mode
        available_modes = CourseMode.modes_for_course_dict(unicode(course.id))
        has_verified_mode = CourseMode.has_verified_mode(available_modes)

        # Establish whether the user is already enrolled
        is_already_verified = CourseEnrollment.is_enrolled_as_verified(request.user.id, course_key)

        # Establish whether the verification deadline has already passed
        verification_deadline = VerifiedUpgradeDeadlineDate(course, request.user)
        deadline_has_passed = verification_deadline.deadline_has_passed()

        show_course_sock = has_verified_mode and not is_already_verified and not deadline_has_passed

        # Get the price of the course and format correctly
        course_price = get_cosmetic_verified_display_price(course)

        context = {
            'show_course_sock': show_course_sock,
            'course_price': course_price,
            'course_id': course.id
        }

        return context
Example #6
0
def _should_show_course_goal_message(request, course, user_access):
    """
    Returns true if the current learner should be shown a course goal message.
    """
    course_key = course.id

    # Don't show a message if course goals has not been enabled
    if not ENABLE_COURSE_GOALS.is_enabled(course_key) or not settings.FEATURES.get('ENABLE_COURSE_GOALS'):
        return False

    # Don't show a message if the user is not enrolled
    if not user_access['is_enrolled']:
        return False

    # Don't show a message if the learner has already specified a goal
    if get_course_goal(auth.get_user(request), course_key):
        return False

    # Don't show a message if the course does not have a verified mode
    if not CourseMode.has_verified_mode(CourseMode.modes_for_course_dict(unicode(course_key))):
        return False

    # Don't show a message if the learner has already verified
    if CourseEnrollment.is_enrolled_as_verified(request.user, course_key):
        return False

    return True
Example #7
0
    def get_verification_context(self, request, course):
        course_key = CourseKey.from_string(unicode(course.id))

        # Establish whether the course has a verified mode
        available_modes = CourseMode.modes_for_course_dict(unicode(course.id))
        has_verified_mode = CourseMode.has_verified_mode(available_modes)

        # Establish whether the user is already enrolled
        is_already_verified = CourseEnrollment.is_enrolled_as_verified(
            request.user, course_key)

        # Establish whether the verification deadline has already passed
        verification_deadline = VerifiedUpgradeDeadlineDate(
            course, request.user)
        deadline_has_passed = verification_deadline.deadline_has_passed()

        # If this proves its worth, we can internationalize and display for more than English speakers.
        show_course_sock = (has_verified_mode and not is_already_verified
                            and not deadline_has_passed
                            and get_language() == 'en')

        # Get information about the upgrade
        course_price = get_cosmetic_verified_display_price(course)
        upgrade_url = EcommerceService().upgrade_url(request.user, course_key)

        context = {
            'show_course_sock': show_course_sock,
            'course_price': course_price,
            'course_id': course.id,
            'upgrade_url': upgrade_url,
        }

        return context
    def render_to_fragment(self, request, course_id, user_access, **kwargs):
        """
        Renders a course message fragment for the specified course.
        """
        course_key = CourseKey.from_string(course_id)
        course = get_course_with_access(request.user, 'load', course_key)

        # Get time until the start date, if already started, or no start date, value will be zero or negative
        now = datetime.now(UTC)
        already_started = course.start and now > course.start
        days_until_start_string = "started" if already_started else format_timedelta(
            course.start - now, locale=to_locale(get_language())
        )
        course_start_data = {
            'course_start_date': format_date(course.start, locale=to_locale(get_language())),
            'already_started': already_started,
            'days_until_start_string': days_until_start_string
        }

        # Register the course home messages to be loaded on the page
        _register_course_home_messages(request, course, user_access, course_start_data)

        # Register course date alerts
        for course_date_block in get_course_date_blocks(course, request.user, request):
            course_date_block.register_alerts(request, course)

        # Register a course goal message, if appropriate
        # Only show the set course goal message for enrolled, unverified
        # users that have not yet set a goal in a course that allows for
        # verified statuses.
        user_goal = get_course_goal(auth.get_user(request), course_key)
        is_already_verified = CourseEnrollment.is_enrolled_as_verified(request.user, course_key)
        if has_course_goal_permission(request, course_id, user_access) and not is_already_verified and not user_goal:
            _register_course_goal_message(request, course)

        # Grab the relevant messages
        course_home_messages = list(CourseHomeMessages.user_messages(request))

        # Pass in the url used to set a course goal
        goal_api_url = get_goal_api_url(request)

        # Grab the logo
        image_src = 'course_experience/images/home_message_author.png'

        context = {
            'course_home_messages': course_home_messages,
            'goal_api_url': goal_api_url,
            'image_src': image_src,
            'course_id': course_id,
            'username': request.user.username,
        }

        html = render_to_string('course_experience/course-messages-fragment.html', context)
        return Fragment(html)
    def render_to_fragment(self, request, course_id, user_access, **kwargs):
        """
        Renders a course message fragment for the specified course.
        """
        course_key = CourseKey.from_string(course_id)
        course = get_course_with_access(request.user, 'load', course_key)

        # Get time until the start date, if already started, or no start date, value will be zero or negative
        now = datetime.now(UTC)
        already_started = course.start and now > course.start
        days_until_start_string = "started" if already_started else format_timedelta(
            course.start - now, locale=to_locale(get_language())
        )
        course_start_data = {
            'course_start_date': format_date(course.start, locale=to_locale(get_language())),
            'already_started': already_started,
            'days_until_start_string': days_until_start_string
        }

        # Register the course home messages to be loaded on the page
        _register_course_home_messages(request, course, user_access, course_start_data)

        # Register course date alerts
        for course_date_block in get_course_date_blocks(course, request.user):
            course_date_block.register_alerts(request, course)

        # Register a course goal message, if appropriate
        # Only show the set course goal message for enrolled, unverified
        # users that have not yet set a goal in a course that allows for
        # verified statuses.
        user_goal = get_course_goal(auth.get_user(request), course_key)
        is_already_verified = CourseEnrollment.is_enrolled_as_verified(request.user, course_key)
        if has_course_goal_permission(request, course_id, user_access) and not is_already_verified and not user_goal:
            _register_course_goal_message(request, course)

        # Grab the relevant messages
        course_home_messages = list(CourseHomeMessages.user_messages(request))

        # Pass in the url used to set a course goal
        goal_api_url = get_goal_api_url(request)

        # Grab the logo
        image_src = 'course_experience/images/home_message_author.png'

        context = {
            'course_home_messages': course_home_messages,
            'goal_api_url': goal_api_url,
            'image_src': image_src,
            'course_id': course_id,
            'username': request.user.username,
        }

        html = render_to_string('course_experience/course-messages-fragment.html', context)
        return Fragment(html)
def _get_user_statuses(user, course_key, checkpoint):
    """
    Retrieve all the information we need to determine the user's group.

    This will retrieve the information as a multi-get from the cache.

    Args:
        user (User): User object
        course_key (CourseKey): Identifier for the course.
        checkpoint (unicode): Location of the checkpoint in the course (serialized usage key)

    Returns:
        tuple of booleans of the form (is_verified, has_skipped, has_completed)

    """
    enrollment_cache_key = CourseEnrollment.cache_key_name(user.id, unicode(course_key))
    has_skipped_cache_key = SkippedReverification.cache_key_name(user.id, unicode(course_key))
    verification_status_cache_key = VerificationStatus.cache_key_name(user.id, unicode(course_key))

    # Try a multi-get from the cache
    cache_values = cache.get_many([
        enrollment_cache_key,
        has_skipped_cache_key,
        verification_status_cache_key
    ])

    # Retrieve whether the user is enrolled in a verified mode.
    is_verified = cache_values.get(enrollment_cache_key)
    if is_verified is None:
        is_verified = CourseEnrollment.is_enrolled_as_verified(user, course_key)
        cache.set(enrollment_cache_key, is_verified)

    # Retrieve whether the user has skipped any checkpoints in this course
    has_skipped = cache_values.get(has_skipped_cache_key)
    if has_skipped is None:
        has_skipped = SkippedReverification.check_user_skipped_reverification_exists(user, course_key)
        cache.set(has_skipped_cache_key, has_skipped)

    # Retrieve the user's verification status for each checkpoint in the course.
    verification_statuses = cache_values.get(verification_status_cache_key)
    if verification_statuses is None:
        verification_statuses = VerificationStatus.get_all_checkpoints(user.id, course_key)
        cache.set(verification_status_cache_key, verification_statuses)

    # Check whether the user has completed this checkpoint
    # "Completion" here means *any* submission, regardless of its status
    # since we want to show the user the content if they've submitted
    # photos.
    checkpoint = verification_statuses.get(checkpoint)
    has_completed_check = bool(checkpoint)

    return (is_verified, has_skipped, has_completed_check)
Example #11
0
    def get(self, request, course_id):
        """
        Displays the user's Learner Analytics for the specified course.

        Arguments:
            request: HTTP request
            course_id (unicode): course id
        """
        course_key = CourseKey.from_string(course_id)
        if not ENABLE_DASHBOARD_TAB.is_enabled(course_key):
            raise Http404

        course = get_course_with_access(request.user,
                                        'load',
                                        course_key,
                                        check_if_enrolled=True)
        course_url_name = default_course_url_name(course.id)
        course_url = reverse(course_url_name,
                             kwargs={'course_id': unicode(course.id)})

        is_verified = CourseEnrollment.is_enrolled_as_verified(
            request.user, course_key)
        has_access = is_verified or request.user.is_staff

        enrollment = CourseEnrollment.get_enrollment(request.user, course_key)

        upgrade_price = None
        upgrade_url = None

        if enrollment and enrollment.upgrade_deadline:
            upgrade_url = EcommerceService().upgrade_url(
                request.user, course_key)
            upgrade_price = get_cosmetic_verified_display_price(course)

        context = {
            'upgrade_price': upgrade_price,
            'upgrade_link': upgrade_url,
            'course': course,
            'course_url': course_url,
            'disable_courseware_js': True,
            'uses_pattern_library': True,
            'is_self_paced': course.self_paced,
            'is_verified': is_verified,
            'has_access': has_access,
        }

        if (has_access):
            grading_policy = course.grading_policy

            (raw_grade_data, answered_percent,
             percent_grade) = self.get_grade_data(
                 request.user, course_key, grading_policy['GRADE_CUTOFFS'])
            raw_schedule_data = self.get_assignments_with_due_date(
                request, course_key)

            grade_data, schedule_data = self.sort_grade_and_schedule_data(
                raw_grade_data, raw_schedule_data)

            # TODO: LEARNER-3854: Fix hacked defaults with real error handling if implementing Learner Analytics.
            try:
                weekly_active_users = self.get_weekly_course_activity_count(
                    course_key)
                week_streak = self.consecutive_weeks_of_course_activity_for_user(
                    request.user.username, course_key)
            except Exception as e:
                logging.exception(e)
                weekly_active_users = 134
                week_streak = 1

            context.update({
                'grading_policy':
                grading_policy,
                'assignment_grades':
                grade_data,
                'answered_percent':
                answered_percent,
                'assignment_schedule':
                schedule_data,
                'assignment_schedule_raw':
                raw_schedule_data,
                'profile_image_urls':
                get_profile_image_urls_for_user(request.user, request),
                'discussion_info':
                self.get_discussion_data(request, course_key),
                'passing_grade':
                math.ceil(100 * course.lowest_passing_grade),
                'percent_grade':
                math.ceil(100 * percent_grade),
                'weekly_active_users':
                weekly_active_users,
                'week_streak':
                week_streak,
            })

        return render_to_response('learner_analytics/dashboard.html', context)
Example #12
0
    def get(self, request, course_id):
        """
        Displays the user's Learner Analytics for the specified course.

        Arguments:
            request: HTTP request
            course_id (unicode): course id
        """
        course_key = CourseKey.from_string(course_id)
        if not ENABLE_DASHBOARD_TAB.is_enabled(course_key):
            raise Http404

        course = get_course_with_access(request.user, 'load', course_key, check_if_enrolled=True)
        course_url_name = default_course_url_name(course.id)
        course_url = reverse(course_url_name, kwargs={'course_id': unicode(course.id)})

        is_verified = CourseEnrollment.is_enrolled_as_verified(request.user, course_key)
        has_access = is_verified or request.user.is_staff

        enrollment = CourseEnrollment.get_enrollment(request.user, course_key)

        upgrade_price = None
        upgrade_url = None

        if enrollment and enrollment.upgrade_deadline:
            upgrade_url = EcommerceService().upgrade_url(request.user, course_key)
            upgrade_price = get_cosmetic_verified_display_price(course)

        context = {
            'upgrade_price': upgrade_price,
            'upgrade_link': upgrade_url,
            'course': course,
            'course_url': course_url,
            'disable_courseware_js': True,
            'uses_pattern_library': True,
            'is_self_paced': course.self_paced,
            'is_verified': is_verified,
            'has_access': has_access,
        }

        if (has_access):
            grading_policy = course.grading_policy

            (raw_grade_data, answered_percent, percent_grade) = self.get_grade_data(request.user, course_key, grading_policy['GRADE_CUTOFFS'])
            raw_schedule_data = self.get_assignments_with_due_date(request, course_key)

            grade_data, schedule_data = self.sort_grade_and_schedule_data(raw_grade_data, raw_schedule_data)

            # TODO: LEARNER-3854: Fix hacked defaults with real error handling if implementing Learner Analytics.
            try:
                weekly_active_users = self.get_weekly_course_activity_count(course_key)
                week_streak = self.consecutive_weeks_of_course_activity_for_user(
                    request.user.username, course_key
                )
            except Exception as e:
                logging.exception(e)
                weekly_active_users = 134
                week_streak = 1

            context.update({
                'grading_policy': grading_policy,
                'assignment_grades': grade_data,
                'answered_percent': answered_percent,
                'assignment_schedule': schedule_data,
                'assignment_schedule_raw': raw_schedule_data,
                'profile_image_urls': get_profile_image_urls_for_user(request.user, request),
                'discussion_info': self.get_discussion_data(request, course_key),
                'passing_grade': math.ceil(100 * course.lowest_passing_grade),
                'percent_grade': math.ceil(100 * percent_grade),
                'weekly_active_users': weekly_active_users,
                'week_streak': week_streak,
            })

        return render_to_response('learner_analytics/dashboard.html', context)
Example #13
0
def is_certificate_valid(certificate):
    """
    Returns True if the student has a valid, verified certificate for this course, False otherwise.
    """
    return CourseEnrollment.is_enrolled_as_verified(certificate.user, certificate.course_id) and certificate.is_valid()
Example #14
0
    def get(self, request, *args, **kwargs):
        course_key_string = kwargs.get('course_key_string')
        course_key = CourseKey.from_string(course_key_string)
        course_usage_key = modulestore().make_course_usage_key(course_key)

        if not course_home_mfe_outline_tab_is_active(course_key):
            raise Http404

        # Enable NR tracing for this view based on course
        monitoring_utils.set_custom_attribute('course_id', course_key_string)
        monitoring_utils.set_custom_attribute('user_id', request.user.id)
        monitoring_utils.set_custom_attribute('is_staff',
                                              request.user.is_staff)

        course = get_course_with_access(request.user,
                                        'load',
                                        course_key,
                                        check_if_enrolled=False)

        _masquerade, request.user = setup_masquerade(
            request,
            course_key,
            staff_access=has_access(request.user, 'staff', course_key),
            reset_masquerade_data=True,
        )

        course_overview = CourseOverview.get_from_id(course_key)
        enrollment = CourseEnrollment.get_enrollment(request.user, course_key)
        allow_anonymous = COURSE_ENABLE_UNENROLLED_ACCESS_FLAG.is_enabled(
            course_key)
        allow_public = allow_anonymous and course.course_visibility == COURSE_VISIBILITY_PUBLIC
        allow_public_outline = allow_anonymous and course.course_visibility == COURSE_VISIBILITY_PUBLIC_OUTLINE
        is_enrolled = enrollment and enrollment.is_active
        is_staff = bool(has_access(request.user, 'staff', course_key))
        show_enrolled = is_enrolled or is_staff

        show_handouts = show_enrolled or allow_public
        handouts_html = get_course_info_section(
            request, request.user, course, 'handouts') if show_handouts else ''

        # TODO: TNL-7185 Legacy: Refactor to return the offer & expired data and format the message in the MFE
        offer_html = show_enrolled and generate_offer_html(
            request.user, course_overview)
        course_expired_html = show_enrolled and generate_course_expired_message(
            request.user, course_overview)

        welcome_message_html = None
        if show_enrolled:
            if LATEST_UPDATE_FLAG.is_enabled(course_key):
                welcome_message_html = LatestUpdateFragmentView(
                ).latest_update_html(request, course)
            elif get_course_tag(request.user, course_key,
                                PREFERENCE_KEY) != 'False':
                welcome_message_html = WelcomeMessageFragmentView(
                ).welcome_message_html(request, course)

        enroll_alert = {
            'can_enroll': True,
            'extra_text': None,
        }
        if not show_enrolled:
            if CourseMode.is_masters_only(course_key):
                enroll_alert['can_enroll'] = False
                enroll_alert['extra_text'] = _(
                    'Please contact your degree administrator or '
                    'edX Support if you have questions.')
            elif course.invitation_only:
                enroll_alert['can_enroll'] = False

        course_tools = CourseToolsPluginManager.get_enabled_course_tools(
            request, course_key)
        date_blocks = get_course_date_blocks(course,
                                             request.user,
                                             request,
                                             num_assignments=1)

        # User locale settings
        user_timezone_locale = user_timezone_locale_prefs(request)
        user_timezone = user_timezone_locale['user_timezone']

        dates_tab_link = request.build_absolute_uri(
            reverse('dates', args=[course.id]))
        if course_home_mfe_dates_tab_is_active(course.id):
            dates_tab_link = get_microfrontend_url(course_key=course.id,
                                                   view_name='dates')

        course_blocks = None
        if show_enrolled or allow_public or allow_public_outline:
            outline_user = request.user if show_enrolled else None
            course_blocks = get_course_outline_block_tree(
                request, course_key_string, outline_user)

        resume_course = {
            'has_visited_course': False,
            'url': None,
        }
        if show_enrolled:
            try:
                resume_block = get_key_to_last_completed_block(
                    request.user, course.id)
                resume_course['has_visited_course'] = True
            except UnavailableCompletionData:
                resume_block = course_usage_key
            resume_path = reverse('jump_to',
                                  kwargs={
                                      'course_id': course_key_string,
                                      'location': str(resume_block)
                                  })
            resume_course['url'] = request.build_absolute_uri(resume_path)

        dates_widget = {
            'course_date_blocks': [
                block for block in date_blocks
                if not isinstance(block, TodaysDate)
            ],
            'dates_tab_link':
            dates_tab_link,
            'user_timezone':
            user_timezone,
        }

        # Only show the set course goal message for enrolled, unverified
        # users in a course that allows for verified statuses.
        is_already_verified = CourseEnrollment.is_enrolled_as_verified(
            request.user, course_key)
        if (not is_already_verified and has_course_goal_permission(
                request, course_key_string, {'is_enrolled': is_enrolled})):
            course_goals = {
                'goal_options':
                valid_course_goals_ordered(include_unsure=True),
                'selected_goal': None
            }

            selected_goal = get_course_goal(request.user, course_key)
            if selected_goal:
                course_goals['selected_goal'] = {
                    'key': selected_goal.goal_key,
                    'text': get_course_goal_text(selected_goal.goal_key),
                }
        else:
            course_goals = {'goal_options': [], 'selected_goal': None}

        data = {
            'course_blocks': course_blocks,
            'course_expired_html': course_expired_html or None,
            'course_goals': course_goals,
            'course_tools': course_tools,
            'dates_widget': dates_widget,
            'enroll_alert': enroll_alert,
            'handouts_html': handouts_html or None,
            'has_ended': course.has_ended(),
            'offer_html': offer_html or None,
            'resume_course': resume_course,
            'welcome_message_html': welcome_message_html or None,
        }
        context = self.get_serializer_context()
        context['course_key'] = course_key
        context['enable_links'] = show_enrolled or allow_public
        serializer = self.get_serializer_class()(data, context=context)

        return Response(serializer.data)
Example #15
0
    def get(self, request, course_id):
        """
        Displays the user's Learner Analytics for the specified course.

        Arguments:
            request: HTTP request
            course_id (unicode): course id
        """
        course_key = CourseKey.from_string(course_id)
        if not ENABLE_DASHBOARD_TAB.is_enabled(course_key):
            raise Http404

        course = get_course_with_access(request.user,
                                        'load',
                                        course_key,
                                        check_if_enrolled=True)
        course_url_name = default_course_url_name(course.id)
        course_url = reverse(course_url_name,
                             kwargs={'course_id': unicode(course.id)})

        grading_policy = course.grading_policy

        (grade_data, answered_percent) = self.get_grade_data(
            request.user, course_key, grading_policy['GRADE_CUTOFFS'])
        schedule_data = self.get_assignments_with_due_date(request, course_key)
        (grade_data, schedule_data) = self.sort_grade_and_schedule_data(
            grade_data, schedule_data)

        context = {
            'course':
            course,
            'course_url':
            course_url,
            'disable_courseware_js':
            True,
            'uses_pattern_library':
            True,
            'is_self_paced':
            course.self_paced,
            'is_verified':
            CourseEnrollment.is_enrolled_as_verified(request.user, course_key),
            'grading_policy':
            grading_policy,
            'assignment_grades':
            grade_data,
            'answered_percent':
            answered_percent,
            'assignment_schedule':
            schedule_data,
            'profile_image_urls':
            get_profile_image_urls_for_user(request.user, request),
            'discussion_info':
            self.get_discussion_data(request, course_key),
            'weekly_active_users':
            self.get_weekly_course_activity_count(course_key),
            'week_streak':
            self.consecutive_weeks_of_course_activity_for_user(
                request.user.username, course_key)
        }

        return render_to_response('learner_analytics/dashboard.html', context)
def is_certificate_valid(certificate):
    """
    Returns True if the student has a valid, verified certificate for this course, False otherwise.
    """
    return CourseEnrollment.is_enrolled_as_verified(
        certificate.user, certificate.course_id) and certificate.is_valid()
def _register_course_home_messages(request, course_id, user_access,
                                   course_start_data):
    """
    Register messages to be shown in the course home content page.
    """
    course_key = CourseKey.from_string(course_id)
    course = get_course_with_access(request.user, 'load', course_key)
    if user_access['is_anonymous']:
        CourseHomeMessages.register_info_message(
            request,
            Text(
                _(" {sign_in_link} or {register_link} and then enroll in this course."
                  )
            ).format(
                sign_in_link=HTML(
                    "<a href='/login?next={current_url}'>{sign_in_label}</a>").
                format(
                    sign_in_label=_("Sign in"),
                    current_url=urlquote_plus(request.path),
                ),
                register_link=HTML(
                    "<a href='/register?next={current_url}'>{register_label}</a>"
                ).format(
                    register_label=_("register"),
                    current_url=urlquote_plus(request.path),
                )),
            title=Text(
                _('You must be enrolled in the course to see course content.')
            ))
    if not user_access['is_anonymous'] and not user_access[
            'is_staff'] and not user_access['is_enrolled']:
        CourseHomeMessages.register_info_message(
            request,
            Text(
                _("{open_enroll_link} Enroll now{close_enroll_link} to access the full course."
                  )).format(open_enroll_link='', close_enroll_link=''),
            title=Text(_('Welcome to {course_display_name}')).format(
                course_display_name=course.display_name))
    if user_access['is_enrolled'] and not course_start_data['already_started']:
        CourseHomeMessages.register_info_message(
            request,
            Text(_("Don't forget to add a calendar reminder!")),
            title=Text(
                _("Course starts in {days_until_start_string} on {course_start_date}."
                  )
            ).format(days_until_start_string=course_start_data[
                'days_until_start_string'],
                     course_start_date=course_start_data['course_start_date']))

    # Only show the set course goal message for enrolled, unverified
    # users that have not yet set a goal in a course that allows for
    # verified statuses.
    has_verified_mode = CourseMode.has_verified_mode(
        CourseMode.modes_for_course_dict(unicode(course.id)))
    is_already_verified = CourseEnrollment.is_enrolled_as_verified(
        request.user, course_key)
    user_goal = get_course_goal(
        auth.get_user(request),
        course_key) if not request.user.is_anonymous() else None
    if user_access['is_enrolled'] and has_verified_mode and not is_already_verified and not user_goal \
            and ENABLE_COURSE_GOALS.is_enabled(course_key) and settings.FEATURES.get('ENABLE_COURSE_GOALS'):
        goal_choices_html = Text(
            _('To start, set a course goal by selecting the option below that best describes '
              'your learning plan. {goal_options_container}')).format(
                  goal_options_container=HTML(
                      '<div class="row goal-options-container">'))

        # Add the dismissible option for users that are unsure of their goal
        goal_choices_html += Text('{initial_tag}{choice}{closing_tag}').format(
            initial_tag=HTML(
                '<div tabindex="0" aria-label="{aria_label_choice}" class="goal-option dismissible" '
                'data-choice="{goal_key}">').format(
                    goal_key=GOAL_KEY_CHOICES.unsure,
                    aria_label_choice=Text(_("Set goal to: {choice}")).format(
                        choice=GOAL_KEY_CHOICES[GOAL_KEY_CHOICES.unsure]),
                ),
            choice=Text(_('{choice}')).format(
                choice=GOAL_KEY_CHOICES[GOAL_KEY_CHOICES.unsure], ),
            closing_tag=HTML('</div>'),
        )

        # Add the option to set a goal to earn a certificate,
        # complete the course or explore the course
        goal_options = [
            GOAL_KEY_CHOICES.certify, GOAL_KEY_CHOICES.complete,
            GOAL_KEY_CHOICES.explore
        ]
        for goal_key in goal_options:
            goal_text = GOAL_KEY_CHOICES[goal_key]
            goal_choices_html += HTML(
                '{initial_tag}{goal_text}{closing_tag}'
            ).format(initial_tag=HTML(
                '<div tabindex="0" aria-label="{aria_label_choice}" class="goal-option {col_sel} btn" '
                'data-choice="{goal_key}">').format(
                    goal_key=goal_key,
                    aria_label_choice=Text(
                        _("Set goal to: {goal_text}")).format(
                            goal_text=Text(_(goal_text))),
                    col_sel='col-' +
                    str(int(math.floor(12 / len(goal_options))))),
                     goal_text=goal_text,
                     closing_tag=HTML('</div>'))

        CourseHomeMessages.register_info_message(
            request,
            HTML('{goal_choices_html}{closing_tag}').format(
                goal_choices_html=goal_choices_html,
                closing_tag=HTML('</div>')),
            title=Text(_('Welcome to {course_display_name}')).format(
                course_display_name=course.display_name))