index.py 21 KB
Newer Older
1 2 3
"""
View for Courseware Index
"""
4 5 6

# pylint: disable=attribute-defined-outside-init

7 8 9
import logging
import urllib

10 11 12 13 14 15 16 17 18 19
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.http import Http404
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_control
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.generic import View
20 21
from opaque_keys.edx.keys import CourseKey
from web_fragments.fragment import Fragment
attiyaishaque committed
22

23
from edxmako.shortcuts import render_to_response, render_to_string
24
from lms.djangoapps.courseware.exceptions import CourseAccessRedirect
25
from lms.djangoapps.experiments.utils import get_experiment_user_metadata_context
26
from lms.djangoapps.gating.api import get_entrance_exam_score_ratio, get_entrance_exam_usage_key
27
from lms.djangoapps.grades.new.course_grade_factory import CourseGradeFactory
28
from openedx.core.djangoapps.crawlers.models import CrawlersConfig
29
from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY
30
from openedx.core.djangoapps.monitoring_utils import set_custom_metrics_for_course_key
31
from openedx.core.djangoapps.user_api.preferences.api import get_user_preference
32
from openedx.core.djangoapps.waffle_utils import WaffleSwitchNamespace
33
from openedx.features.course_experience import COURSE_OUTLINE_PAGE_FLAG, default_course_url_name
34
from openedx.features.course_experience.views.course_sock import CourseSockFragmentView
35
from openedx.features.enterprise_support.api import data_sharing_consent_required
36 37
from shoppingcart.models import CourseRegistrationCode
from student.views import is_course_blocked
38
from student.models import CourseEnrollment
39 40 41 42
from util.views import ensure_valid_course_key
from xmodule.modulestore.django import modulestore
from xmodule.x_module import STUDENT_VIEW

43
from ..access import has_access
44
from ..access_utils import in_preview_mode, check_course_open_for_learner
45
from ..courses import get_course_with_access, get_current_child, get_studio_url
46
from ..entrance_exams import (
47 48
    course_has_entrance_exam,
    get_entrance_exam_content,
49
    user_can_skip_entrance_exam,
50
    user_has_passed_entrance_exam
51
)
52 53
from ..masquerade import setup_masquerade
from ..model_data import FieldDataCache
54
from ..module_render import get_module_for_descriptor, toc_for_course
55
from .views import (
56
    CourseTabView,
57
)
58

59
log = logging.getLogger("edx.courseware.views.index")
60 61 62 63 64 65 66 67 68 69 70 71 72

TEMPLATE_IMPORTS = {'urllib': urllib}
CONTENT_DEPTH = 2


class CoursewareIndex(View):
    """
    View class for the Courseware page.
    """
    @method_decorator(login_required)
    @method_decorator(ensure_csrf_cookie)
    @method_decorator(cache_control(no_cache=True, no_store=True, must_revalidate=True))
    @method_decorator(ensure_valid_course_key)
73
    @method_decorator(data_sharing_consent_required)
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    def get(self, request, course_id, chapter=None, section=None, position=None):
        """
        Displays courseware accordion and associated content.  If course, chapter,
        and section are all specified, renders the page, or returns an error if they
        are invalid.

        If section is not specified, displays the accordion opened to the right
        chapter.

        If neither chapter or section are specified, displays the user's most
        recent chapter, or the first chapter if this is the user's first visit.

        Arguments:
            request: HTTP request
            course_id (unicode): course id
            chapter (unicode): chapter url_name
            section (unicode): section url_name
            position (unicode): position in module, eg of <sequential> module
        """
        self.course_key = CourseKey.from_string(course_id)
        self.request = request
        self.original_chapter_url_name = chapter
        self.original_section_url_name = section
        self.chapter_url_name = chapter
        self.section_url_name = section
        self.position = position
        self.chapter, self.section = None, None
101
        self.course = None
attiyaishaque committed
102
        self.url = request.path
103 104

        try:
105
            set_custom_metrics_for_course_key(self.course_key)
106
            self._clean_position()
107
            with modulestore().bulk_operations(self.course_key):
108 109 110 111 112
                self.course = get_course_with_access(
                    request.user, 'load', self.course_key,
                    depth=CONTENT_DEPTH,
                    check_if_enrolled=True,
                )
113 114
                self.is_staff = has_access(request.user, 'staff', self.course)
                self._setup_masquerade_for_effective_user()
115
                return self._get(request)
116 117
        except Exception as exception:  # pylint: disable=broad-except
            return CourseTabView.handle_exceptions(request, self.course, exception)
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133

    def _setup_masquerade_for_effective_user(self):
        """
        Setup the masquerade information to allow the request to
        be processed for the requested effective user.
        """
        self.real_user = self.request.user
        self.masquerade, self.effective_user = setup_masquerade(
            self.request,
            self.course_key,
            self.is_staff,
            reset_masquerade_data=True
        )
        # Set the user in the request to the effective user.
        self.request.user = self.effective_user

134
    def _get(self, request):
135 136 137
        """
        Render the index page.
        """
138
        self._redirect_if_needed_to_pay_for_course()
139
        self._prefetch_and_bind_course(request)
140 141 142 143 144 145 146 147 148 149 150

        if self.course.has_children_at_depth(CONTENT_DEPTH):
            self._reset_section_to_exam_if_required()
            self.chapter = self._find_chapter()
            self.section = self._find_section()

            if self.chapter and self.section:
                self._redirect_if_not_requested_section()
                self._save_positions()
                self._prefetch_and_bind_section()

151
        return render_to_response('courseware/courseware.html', self._create_courseware_context(request))
152 153 154 155 156 157 158 159 160 161 162 163

    def _redirect_if_not_requested_section(self):
        """
        If the resulting section and chapter are different from what was initially
        requested, redirect back to the index page, but with an updated URL that includes
        the correct section and chapter values.  We do this so that our analytics events
        and error logs have the appropriate URLs.
        """
        if (
                self.chapter.url_name != self.original_chapter_url_name or
                (self.original_section_url_name and self.section.url_name != self.original_section_url_name)
        ):
164
            raise CourseAccessRedirect(
165 166 167 168 169 170 171 172 173 174
                reverse(
                    'courseware_section',
                    kwargs={
                        'course_id': unicode(self.course_key),
                        'chapter': self.chapter.url_name,
                        'section': self.section.url_name,
                    },
                )
            )

175
    def _clean_position(self):
176
        """
177
        Verify that the given position is an integer. If it is not positive, set it to 1.
178 179 180
        """
        if self.position is not None:
            try:
181
                self.position = max(int(self.position), 1)
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
            except ValueError:
                raise Http404(u"Position {} is not an integer!".format(self.position))

    def _redirect_if_needed_to_pay_for_course(self):
        """
        Redirect to dashboard if the course is blocked due to non-payment.
        """
        self.real_user = User.objects.prefetch_related("groups").get(id=self.real_user.id)
        redeemed_registration_codes = CourseRegistrationCode.objects.filter(
            course_id=self.course_key,
            registrationcoderedemption__redeemed_by=self.real_user
        )
        if is_course_blocked(self.request, redeemed_registration_codes, self.course_key):
            # registration codes may be generated via Bulk Purchase Scenario
            # we have to check only for the invoice generated registration codes
            # that their invoice is valid or not
            log.warning(
                u'User %s cannot access the course %s because payment has not yet been received',
                self.real_user,
                unicode(self.course_key),
            )
203
            raise CourseAccessRedirect(reverse('dashboard'))
204 205 206 207 208

    def _reset_section_to_exam_if_required(self):
        """
        Check to see if an Entrance Exam is required for the user.
        """
209
        if not user_can_skip_entrance_exam(self.effective_user, self.course):
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
            exam_chapter = get_entrance_exam_content(self.effective_user, self.course)
            if exam_chapter and exam_chapter.get_children():
                exam_section = exam_chapter.get_children()[0]
                if exam_section:
                    self.chapter_url_name = exam_chapter.url_name
                    self.section_url_name = exam_section.url_name

    def _get_language_preference(self):
        """
        Returns the preferred language for the actual user making the request.
        """
        language_preference = get_user_preference(self.real_user, LANGUAGE_KEY)
        if not language_preference:
            language_preference = settings.LANGUAGE_CODE
        return language_preference

    def _is_masquerading_as_student(self):
        """
        Returns whether the current request is masquerading as a student.
        """
        return self.masquerade and self.masquerade.role == 'student'

232 233 234 235 236 237
    def _is_masquerading_as_specific_student(self):
        """
        Returns whether the current request is masqueurading as a specific student.
        """
        return self._is_masquerading_as_student() and self.masquerade.user_name

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    def _find_block(self, parent, url_name, block_type, min_depth=None):
        """
        Finds the block in the parent with the specified url_name.
        If not found, calls get_current_child on the parent.
        """
        child = None
        if url_name:
            child = parent.get_child_by(lambda m: m.location.name == url_name)
            if not child:
                # User may be trying to access a child that isn't live yet
                if not self._is_masquerading_as_student():
                    raise Http404('No {block_type} found with name {url_name}'.format(
                        block_type=block_type,
                        url_name=url_name,
                    ))
            elif min_depth and not child.has_children_at_depth(min_depth - 1):
                child = None
        if not child:
            child = get_current_child(parent, min_depth=min_depth, requested_child=self.request.GET.get("child"))
        return child

    def _find_chapter(self):
        """
        Finds the requested chapter.
        """
        return self._find_block(self.course, self.chapter_url_name, 'chapter', CONTENT_DEPTH - 1)

    def _find_section(self):
        """
        Finds the requested section.
        """
        if self.chapter:
            return self._find_block(self.chapter, self.section_url_name, 'section')

272
    def _prefetch_and_bind_course(self, request):
273 274 275 276 277
        """
        Prefetches all descendant data for the requested section and
        sets up the runtime, which binds the request user to the section.
        """
        self.field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
278 279 280 281 282
            self.course_key,
            self.effective_user,
            self.course,
            depth=CONTENT_DEPTH,
            read_only=CrawlersConfig.is_crawler(request),
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
        )

        self.course = get_module_for_descriptor(
            self.effective_user,
            self.request,
            self.course,
            self.field_data_cache,
            self.course_key,
            course=self.course,
        )

    def _prefetch_and_bind_section(self):
        """
        Prefetches all descendant data for the requested section and
        sets up the runtime, which binds the request user to the section.
        """
        # Pre-fetch all descendant data
300
        self.section = modulestore().get_item(self.section.location, depth=None, lazy=False)
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
        self.field_data_cache.add_descriptor_descendents(self.section, depth=None)

        # Bind section to user
        self.section = get_module_for_descriptor(
            self.effective_user,
            self.request,
            self.section,
            self.field_data_cache,
            self.course_key,
            self.position,
            course=self.course,
        )

    def _save_positions(self):
        """
        Save where we are in the course and chapter.
        """
        save_child_position(self.course, self.chapter_url_name)
        save_child_position(self.chapter, self.section_url_name)

321
    def _create_courseware_context(self, request):
322 323 324 325
        """
        Returns and creates the rendering context for the courseware.
        Also returns the table of contents for the courseware.
        """
326
        course_url_name = default_course_url_name(self.course.id)
327
        course_url = reverse(course_url_name, kwargs={'course_id': unicode(self.course.id)})
328

329 330 331
        courseware_context = {
            'csrf': csrf(self.request)['csrf_token'],
            'course': self.course,
332 333 334
            'course_url': course_url,
            'chapter': self.chapter,
            'section': self.section,
335 336 337 338
            'init': '',
            'fragment': Fragment(),
            'staff_access': self.is_staff,
            'masquerade': self.masquerade,
339 340
            'supports_preview_menu': True,
            'studio_url': get_studio_url(self.course, 'course'),
341 342 343
            'xqa_server': settings.FEATURES.get('XQA_SERVER', "http://your_xqa_server.com"),
            'bookmarks_api_url': reverse('bookmarks'),
            'language_preference': self._get_language_preference(),
344
            'disable_optimizely': not WaffleSwitchNamespace('RET').is_enabled('enable_optimizely_in_courseware'),
345
            'section_title': None,
346
            'sequence_title': None,
347
            'disable_accordion': COURSE_OUTLINE_PAGE_FLAG.is_enabled(self.course.id),
348
        }
349 350 351 352 353 354
        courseware_context.update(
            get_experiment_user_metadata_context(
                self.course,
                self.effective_user,
            )
        )
355 356 357 358 359 360 361 362
        table_of_contents = toc_for_course(
            self.effective_user,
            self.request,
            self.course,
            self.chapter_url_name,
            self.section_url_name,
            self.field_data_cache,
        )
363 364 365 366 367
        courseware_context['accordion'] = render_accordion(
            self.request,
            self.course,
            table_of_contents['chapters'],
        )
368

369 370 371
        courseware_context['course_sock_fragment'] = CourseSockFragmentView().render_to_fragment(
            request, course=self.course)

372
        # entrance exam data
373
        self._add_entrance_exam_to_context(courseware_context)
374 375

        # staff masquerading data
376
        if not check_course_open_for_learner(self.effective_user, self.course):
377 378 379
            # Disable student view button if user is staff and
            # course is not yet visible to students.
            courseware_context['disable_student_access'] = True
380
            courseware_context['supports_preview_menu'] = False
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395

        if self.section:
            # chromeless data
            if self.section.chrome:
                chrome = [s.strip() for s in self.section.chrome.lower().split(",")]
                if 'accordion' not in chrome:
                    courseware_context['disable_accordion'] = True
                if 'tabs' not in chrome:
                    courseware_context['disable_tabs'] = True

            # default tab
            if self.section.default_tab:
                courseware_context['default_tab'] = self.section.default_tab

            # section data
396
            courseware_context['section_title'] = self.section.display_name_with_default
397 398 399 400 401
            section_context = self._create_section_context(
                table_of_contents['previous_of_active_section'],
                table_of_contents['next_of_active_section'],
            )
            courseware_context['fragment'] = self.section.render(STUDENT_VIEW, section_context)
402 403 404
            if self.section.position and self.section.has_children:
                display_items = self.section.get_display_items()
                if display_items:
405 406 407 408
                    try:
                        courseware_context['sequence_title'] = display_items[self.section.position - 1] \
                            .display_name_with_default
                    except IndexError:
409 410 411 412
                        log.exception(
                            "IndexError loading courseware for user %s, course %s, section %s, position %d. Total items: %d. URL: %s",
                            self.real_user.username,
                            self.course.id,
413 414 415
                            self.section.display_name_with_default,
                            self.section.position,
                            len(display_items),
416 417 418
                            self.url,
                        )
                        raise
419 420
        return courseware_context

421 422 423 424 425 426 427 428 429 430 431
    def _add_entrance_exam_to_context(self, courseware_context):
        """
        Adds entrance exam related information to the given context.
        """
        if course_has_entrance_exam(self.course) and getattr(self.chapter, 'is_entrance_exam', False):
            courseware_context['entrance_exam_passed'] = user_has_passed_entrance_exam(self.effective_user, self.course)
            courseware_context['entrance_exam_current_score'] = get_entrance_exam_score_ratio(
                CourseGradeFactory().create(self.effective_user, self.course),
                get_entrance_exam_usage_key(self.course),
            )

432 433 434 435 436 437 438 439 440 441 442
    def _create_section_context(self, previous_of_active_section, next_of_active_section):
        """
        Returns and creates the rendering context for the section.
        """
        def _compute_section_url(section_info, requested_child):
            """
            Returns the section URL for the given section_info with the given child parameter.
            """
            return "{url}?child={requested_child}".format(
                url=reverse(
                    'courseware_section',
443
                    args=[unicode(self.course_key), section_info['chapter_url_name'], section_info['url_name']],
444 445 446 447 448 449 450
                ),
                requested_child=requested_child,
            )

        section_context = {
            'activate_block_id': self.request.GET.get('activate_block_id'),
            'requested_child': self.request.GET.get("child"),
451
            'progress_url': reverse('progress', kwargs={'course_id': unicode(self.course_key)}),
452 453 454 455 456
        }
        if previous_of_active_section:
            section_context['prev_url'] = _compute_section_url(previous_of_active_section, 'last')
        if next_of_active_section:
            section_context['next_url'] = _compute_section_url(next_of_active_section, 'first')
457 458
        # sections can hide data that masquerading staff should see when debugging issues with specific students
        section_context['specific_masquerade'] = self._is_masquerading_as_specific_student()
459 460 461
        return section_context


462
def render_accordion(request, course, table_of_contents):
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
    """
    Returns the HTML that renders the navigation for the given course.
    Expects the table_of_contents to have data on each chapter and section,
    including which ones are active.
    """
    context = dict(
        [
            ('toc', table_of_contents),
            ('course_id', unicode(course.id)),
            ('csrf', csrf(request)['csrf_token']),
            ('due_date_display_format', course.due_date_display_format),
        ] + TEMPLATE_IMPORTS.items()
    )
    return render_to_string('courseware/accordion.html', context)


def save_child_position(seq_module, child_name):
    """
    child_name: url_name of the child
    """
    for position, child in enumerate(seq_module.get_display_items(), start=1):
        if child.location.name == child_name:
            # Only save if position changed
            if position != seq_module.position:
                seq_module.position = position
    # Save this new position to the underlying KeyValueStore
    seq_module.save()


def save_positions_recursively_up(user, request, field_data_cache, xmodule, course=None):
    """
    Recurses up the course tree starting from a leaf
    Saving the position property based on the previous node as it goes
    """
    current_module = xmodule

    while current_module:
        parent_location = modulestore().get_parent_location(current_module.location)
        parent = None
        if parent_location:
            parent_descriptor = modulestore().get_item(parent_location)
            parent = get_module_for_descriptor(
                user,
                request,
                parent_descriptor,
                field_data_cache,
                current_module.location.course_key,
                course=course
            )

        if parent and hasattr(parent, 'position'):
            save_child_position(parent, current_module.location.name)

        current_module = parent