courses.py 15.2 KB
Newer Older
1 2 3 4 5
"""
Functions for accessing and displaying courses within the
courseware.
"""
from datetime import datetime
6
from collections import defaultdict
7 8
from fs.errors import ResourceNotFoundError
import logging
9

10
from path import Path as path
11
import pytz
12
from django.http import Http404
13
from django.conf import settings
14 15

from edxmako.shortcuts import render_to_string
16
from xmodule.modulestore.django import modulestore
Don Mitchell committed
17
from xmodule.modulestore.exceptions import ItemNotFoundError
18
from static_replace import replace_static_urls
19
from xmodule.x_module import STUDENT_VIEW
20

21
from courseware.access import has_access
22 23 24 25 26 27 28
from courseware.date_summary import (
    CourseEndDate,
    CourseStartDate,
    TodaysDate,
    VerificationDeadlineDate,
    VerifiedUpgradeDeadlineDate,
)
29 30
from courseware.model_data import FieldDataCache
from courseware.module_render import get_module
31
from lms.djangoapps.courseware.courseware_access_exception import CoursewareAccessException
32
from student.models import CourseEnrollment
33
import branding
34

35
from opaque_keys.edx.keys import UsageKey
36
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
37
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
38

39

40
log = logging.getLogger(__name__)
41

Calen Pennington committed
42

43 44 45 46
def get_course(course_id, depth=0):
    """
    Given a course id, return the corresponding course descriptor.

Don Mitchell committed
47
    If the course does not exist, raises a ValueError.  This is appropriate
48 49 50 51 52
    for internal use.

    depth: The number of levels of children for the modulestore to cache.
    None means infinite depth.  Default is to fetch no children.
    """
Don Mitchell committed
53 54
    course = modulestore().get_course(course_id, depth=depth)
    if course is None:
55
        raise ValueError(u"Course not found: {0}".format(course_id))
56
    return course
57 58


59
def get_course_by_id(course_key, depth=0):
60
    """
61
    Given a course id, return the corresponding course descriptor.
62

Don Mitchell committed
63
    If such a course does not exist, raises a 404.
64

65
    depth: The number of levels of children for the modulestore to cache. None means infinite depth
66
    """
67 68
    with modulestore().bulk_operations(course_key):
        course = modulestore().get_course(course_key, depth=depth)
Don Mitchell committed
69 70 71
    if course:
        return course
    else:
72
        raise Http404("Course not found: {}.".format(unicode(course_key)))
73

74

75 76 77 78 79 80 81
class UserNotEnrolled(Http404):
    def __init__(self, course_key):
        super(UserNotEnrolled, self).__init__()
        self.course_key = course_key


def get_course_with_access(user, action, course_key, depth=0, check_if_enrolled=False):
82
    """
83
    Given a course_key, look up the corresponding course descriptor,
84 85
    check that the user has the access to perform the specified action
    on the course, and return the descriptor.
86

87
    Raises a 404 if the course_key is invalid, or the user doesn't have access.
88 89

    depth: The number of levels of children for the modulestore to cache. None means infinite depth
90 91 92

    check_if_enrolled: If true, additionally verifies that the user is either enrolled in the course
      or has staff access.
93
    """
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    course = get_course_by_id(course_key, depth)
    check_course_access(course, user, action, check_if_enrolled)
    return course


def get_course_overview_with_access(user, action, course_key, check_if_enrolled=False):
    """
    Given a course_key, look up the corresponding course overview,
    check that the user has the access to perform the specified action
    on the course, and return the course overview.

    Raises a 404 if the course_key is invalid, or the user doesn't have access.

    check_if_enrolled: If true, additionally verifies that the user is either enrolled in the course
      or has staff access.
    """
    try:
        course_overview = CourseOverview.get_from_id(course_key)
    except CourseOverview.DoesNotExist:
        raise Http404("Course not found.")
    check_course_access(course_overview, user, action, check_if_enrolled)
    return course_overview


def check_course_access(course, user, action, check_if_enrolled=False):
    """
    Check that the user has the access to perform the specified action
    on the course (CourseDescriptor|CourseOverview).

    check_if_enrolled: If true, additionally verifies that the user is either
    enrolled in the course or has staff access.
    """
    access_response = has_access(user, action, course, course.id)
127

128
    if not access_response:
129 130
        # Deliberately return a non-specific error message to avoid
        # leaking info about access control settings
131
        raise CoursewareAccessException(access_response)
132

133
    if check_if_enrolled:
134 135 136 137 138
        # Verify that the user is either enrolled in the course or a staff
        # member.  If user is not enrolled, raise UserNotEnrolled exception
        # that will be caught by middleware.
        if not ((user.id and CourseEnrollment.is_enrolled(user, course.id)) or has_access(user, 'staff', course)):
            raise UserNotEnrolled(course.id)
139 140


Don Mitchell committed
141
def find_file(filesystem, dirs, filename):
142 143 144
    """
    Looks for a filename in a list of dirs on a filesystem, in the specified order.

Don Mitchell committed
145
    filesystem: an OSFS filesystem
146 147 148 149 150
    dirs: a list of path objects
    filename: a string

    Returns d / filename if found in dir d, else raises ResourceNotFoundError.
    """
Don Mitchell committed
151 152 153
    for directory in dirs:
        filepath = path(directory) / filename
        if filesystem.exists(filepath):
154
            return filepath
155
    raise ResourceNotFoundError(u"Could not find {0}".format(filename))
156

157

158
def get_course_about_section(request, course, section_key):
159
    """
Victor Shnayder committed
160 161 162
    This returns the snippet of html to be rendered on the course about page,
    given the key for the section.

163 164 165 166 167 168 169 170 171 172 173 174
    Valid keys:
    - overview
    - short_description
    - description
    - key_dates (includes start, end, exams, etc)
    - video
    - course_staff_short
    - course_staff_extended
    - requirements
    - syllabus
    - textbook
    - faq
175
    - effort
176
    - more_info
177
    - ocw_links
178 179
    """

Victor Shnayder committed
180 181 182
    # Many of these are stored as html files instead of some semantic
    # markup. This can change without effecting this interface when we find a
    # good format for defining so many snippets of text/html.
183

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
    html_sections = {
        'short_description',
        'description',
        'key_dates',
        'video',
        'course_staff_short',
        'course_staff_extended',
        'requirements',
        'syllabus',
        'textbook',
        'faq',
        'more_info',
        'overview',
        'effort',
        'end_date',
        'prerequisites',
        'ocw_links'
    }

    if section_key in html_sections:
204
        try:
Don Mitchell committed
205
            loc = course.location.replace(category='about', name=section_key)
206 207

            # Use an empty cache
Calen Pennington committed
208
            field_data_cache = FieldDataCache([], course.id, request.user)
209 210 211 212
            about_module = get_module(
                request.user,
                request,
                loc,
Calen Pennington committed
213
                field_data_cache,
214
                log_if_not_found=False,
215
                wrap_xmodule_display=False,
216 217
                static_asset_path=course.static_asset_path,
                course=course
218
            )
219 220 221

            html = ''

222
            if about_module is not None:
223
                try:
224
                    html = about_module.render(STUDENT_VIEW).content
225 226
                except Exception:  # pylint: disable=broad-except
                    html = render_to_string('courseware/error-message.html', None)
227
                    log.exception(
228 229 230
                        u"Error rendering course=%s, section_key=%s",
                        course, section_key
                    )
231
            return html
232 233

        except ItemNotFoundError:
234
            log.warning(
235 236
                u"Missing about section %s in course %s",
                section_key, course.location.to_deprecated_string()
237
            )
238 239 240 241
            return None

    raise KeyError("Invalid about key " + str(section_key))

242

243
def get_course_info_section_module(request, user, course, section_key):
244
    """
245
    This returns the course info module for a given section_key.
Victor Shnayder committed
246

247 248 249 250 251 252
    Valid keys:
    - handouts
    - guest_handouts
    - updates
    - guest_updates
    """
253
    usage_key = course.id.make_usage_key('course_info', section_key)
254 255

    # Use an empty cache
256
    field_data_cache = FieldDataCache([], course.id, user)
257 258

    return get_module(
259
        user,
260
        request,
261
        usage_key,
Calen Pennington committed
262
        field_data_cache,
263
        log_if_not_found=False,
264
        wrap_xmodule_display=False,
265 266
        static_asset_path=course.static_asset_path,
        course=course
267
    )
268

269

270
def get_course_info_section(request, user, course, section_key):
271 272 273
    """
    This returns the snippet of html to be rendered on the course info page,
    given the key for the section.
274

275 276 277 278 279 280
    Valid keys:
    - handouts
    - guest_handouts
    - updates
    - guest_updates
    """
281
    info_module = get_course_info_section_module(request, user, course, section_key)
282 283

    html = ''
284
    if info_module is not None:
285
        try:
286
            html = info_module.render(STUDENT_VIEW).content
287 288
        except Exception:  # pylint: disable=broad-except
            html = render_to_string('courseware/error-message.html', None)
289
            log.exception(
290 291
                u"Error rendering course_id=%s, section_key=%s",
                unicode(course.id), section_key
292
            )
293

294
    return html
295

296

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
def get_course_date_summary(course, user):
    """
    Return the snippet of HTML to be included on the course info page
    in the 'Date Summary' section.
    """
    blocks = _get_course_date_summary_blocks(course, user)
    return '\n'.join(
        b.render() for b in blocks
    )


def _get_course_date_summary_blocks(course, user):
    """
    Return the list of blocks to display on the course info page,
    sorted by date.
    """
    block_classes = (
        CourseEndDate,
        CourseStartDate,
        TodaysDate,
        VerificationDeadlineDate,
        VerifiedUpgradeDeadlineDate,
    )

    blocks = (cls(course, user) for cls in block_classes)
322 323 324 325 326 327 328 329 330 331

    def block_key_fn(block):
        """
        If the block's date is None, return the maximum datetime in order
        to force it to the end of the list of displayed blocks.
        """
        if block.date is None:
            return datetime.max.replace(tzinfo=pytz.UTC)
        return block.date
    return sorted((b for b in blocks if b.is_enabled), key=block_key_fn)
332 333


334 335
# TODO: Fix this such that these are pulled in as extra course-specific tabs.
#       arjun will address this by the end of October if no one does so prior to
336
#       then.
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
def get_course_syllabus_section(course, section_key):
    """
    This returns the snippet of html to be rendered on the syllabus page,
    given the key for the section.

    Valid keys:
    - syllabus
    - guest_syllabus
    """

    # Many of these are stored as html files instead of some semantic
    # markup. This can change without effecting this interface when we find a
    # good format for defining so many snippets of text/html.

    if section_key in ['syllabus', 'guest_syllabus']:
        try:
Don Mitchell committed
353
            filesys = course.system.resources_fs
354 355
            # first look for a run-specific version
            dirs = [path("syllabus") / course.url_name, path("syllabus")]
Don Mitchell committed
356 357
            filepath = find_file(filesys, dirs, section_key + ".html")
            with filesys.open(filepath) as html_file:
358
                return replace_static_urls(
Don Mitchell committed
359
                    html_file.read().decode('utf-8'),
360
                    getattr(course, 'data_dir', None),
361
                    course_id=course.id,
Calen Pennington committed
362
                    static_asset_path=course.static_asset_path,
363
                )
364
        except ResourceNotFoundError:
365
            log.exception(
366 367
                u"Missing syllabus section %s in course %s",
                section_key, course.location.to_deprecated_string()
368
            )
369 370 371 372
            return "! Syllabus missing !"

    raise KeyError("Invalid about key " + str(section_key))

373

374
def get_courses(user, org=None, filter_=None):
375 376 377 378
    """
    Returns a list of courses available, sorted by course.number and optionally
    filtered by org code (case-insensitive).
    """
379
    courses = branding.get_visible_courses(org=org, filter_=filter_)
380

381
    permission_name = configuration_helpers.get_value(
382 383 384 385
        'COURSE_CATALOG_VISIBILITY_PERMISSION',
        settings.COURSE_CATALOG_VISIBILITY_PERMISSION
    )

386 387
    courses = [c for c in courses if has_access(user, permission_name, c)]

388 389 390
    return courses


391 392 393 394
def get_permission_for_course_about():
    """
    Returns the CourseOverview object for the course after checking for access.
    """
395
    return configuration_helpers.get_value(
396 397 398 399 400
        'COURSE_ABOUT_VISIBILITY_PERMISSION',
        settings.COURSE_ABOUT_VISIBILITY_PERMISSION
    )


401 402 403 404 405 406 407 408 409 410
def sort_by_announcement(courses):
    """
    Sorts a list of courses by their announcement date. If the date is
    not available, sort them by their start date.
    """

    # Sort courses by how far are they from they start day
    key = lambda course: course.sorting_score
    courses = sorted(courses, key=key)

411
    return courses
412

413

414 415 416 417
def sort_by_start_date(courses):
    """
    Returns a list of courses sorted by their start date, latest first.
    """
418 419 420 421 422
    courses = sorted(
        courses,
        key=lambda course: (course.has_ended(), course.start is None, course.start),
        reverse=False
    )
423 424 425 426

    return courses


427
def get_cms_course_link(course, page='course'):
428
    """
429 430
    Returns a link to course_index for editing the course in cms,
    assuming that the course is actually cms-backed.
431
    """
432 433 434
    # This is fragile, but unfortunately the problem is that within the LMS we
    # can't use the reverse calls from the CMS
    return u"//{}/{}/{}".format(settings.CMS_BASE, page, unicode(course.id))
435 436 437 438 439 440 441


def get_cms_block_link(block, page):
    """
    Returns a link to block_index for editing the course in cms,
    assuming that the block is actually cms-backed.
    """
442 443 444
    # This is fragile, but unfortunately the problem is that within the LMS we
    # can't use the reverse calls from the CMS
    return u"//{}/{}/{}".format(settings.CMS_BASE, page, block.location)
445 446


447
def get_studio_url(course, page):
448 449
    """
    Get the Studio URL of the page that is passed in.
450 451 452

    Args:
        course (CourseDescriptor)
453 454
    """
    studio_link = None
455
    if course.course_edit_method == "Studio":
456
        studio_link = get_cms_course_link(course, page)
457
    return studio_link
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483


def get_problems_in_section(section):
    """
    This returns a dict having problems in a section.
    Returning dict has problem location as keys and problem
    descriptor as values.
    """

    problem_descriptors = defaultdict()
    if not isinstance(section, UsageKey):
        section_key = UsageKey.from_string(section)
    else:
        section_key = section
    # it will be a Mongo performance boost, if you pass in a depth=3 argument here
    # as it will optimize round trips to the database to fetch all children for the current node
    section_descriptor = modulestore().get_item(section_key, depth=3)

    # iterate over section, sub-section, vertical
    for subsection in section_descriptor.get_children():
        for vertical in subsection.get_children():
            for component in vertical.get_children():
                if component.location.category == 'problem' and getattr(component, 'has_score', False):
                    problem_descriptors[unicode(component.location)] = component

    return problem_descriptors