-
-
-
diff --git a/common/djangoapps/student/views.py b/common/djangoapps/student/views.py
index cbb12e44cc..a70349bec3 100644
--- a/common/djangoapps/student/views.py
+++ b/common/djangoapps/student/views.py
@@ -82,6 +82,8 @@ def index(request, extra_context={}, user=None):
domain=domain)
context = {'universities': universities, 'entries': entries}
context.update(extra_context)
+ if request.REQUEST.get('next', False):
+ context['show_login_immediately'] = True
return render_to_response('index.html', context)
def course_from_id(course_id):
diff --git a/common/djangoapps/xmodule_modifiers.py b/common/djangoapps/xmodule_modifiers.py
index 80514cf8d4..7ea6778af6 100644
--- a/common/djangoapps/xmodule_modifiers.py
+++ b/common/djangoapps/xmodule_modifiers.py
@@ -35,7 +35,7 @@ def wrap_xmodule(get_html, module, template):
return _get_html
-def replace_course_urls(get_html, course_id, module):
+def replace_course_urls(get_html, course_id):
"""
Updates the supplied module with a new get_html function that wraps
the old get_html function and substitutes urls of the form /course/...
@@ -46,7 +46,7 @@ def replace_course_urls(get_html, course_id, module):
return replace_urls(get_html(), staticfiles_prefix='/courses/'+course_id, replace_prefix='/course/')
return _get_html
-def replace_static_urls(get_html, prefix, module):
+def replace_static_urls(get_html, prefix):
"""
Updates the supplied module with a new get_html function that wraps
the old get_html function and substitutes urls of the form /static/...
diff --git a/common/lib/capa/capa/responsetypes.py b/common/lib/capa/capa/responsetypes.py
index 5b89b78867..0909deea3a 100644
--- a/common/lib/capa/capa/responsetypes.py
+++ b/common/lib/capa/capa/responsetypes.py
@@ -1627,6 +1627,10 @@ class ImageResponse(LoncapaResponse):
for aid in self.answer_ids: # loop through IDs of fields in our stanza
given = student_answers[aid] # this should be a string of the form '[x,y]'
+ if not given: # No answer to parse. Mark as incorrect and move on
+ correct_map.set(aid, 'incorrect')
+ continue
+
# parse expected answer
# TODO: Compile regexp on file load
m = re.match('[\(\[]([0-9]+),([0-9]+)[\)\]]-[\(\[]([0-9]+),([0-9]+)[\)\]]', expectedset[aid].strip().replace(' ', ''))
diff --git a/common/lib/xmodule/xmodule/capa_module.py b/common/lib/xmodule/xmodule/capa_module.py
index a891474581..0d810af87a 100644
--- a/common/lib/xmodule/xmodule/capa_module.py
+++ b/common/lib/xmodule/xmodule/capa_module.py
@@ -179,6 +179,8 @@ class CapaModule(XModule):
return "per_student"
elif rerandomize == "never":
return "never"
+ elif rerandomize == "onreset":
+ return "onreset"
else:
raise Exception("Invalid rerandomize attribute " + rerandomize)
@@ -307,7 +309,7 @@ class CapaModule(XModule):
save_button = False
# Only show the reset button if pressing it will show different values
- if self.rerandomize != 'always':
+ if self.rerandomize not in ["always", "onreset"]:
reset_button = False
# User hasn't submitted an answer yet -- we don't want resets
@@ -617,7 +619,7 @@ class CapaModule(XModule):
return "Refresh the page and make an attempt before resetting."
self.lcp.do_reset()
- if self.rerandomize == "always":
+ if self.rerandomize in ["always", "onreset"]:
# reset random number generator seed (note the self.lcp.get_state()
# in next line)
self.lcp.seed = None
diff --git a/common/lib/xmodule/xmodule/course_module.py b/common/lib/xmodule/xmodule/course_module.py
index 7aa904205d..71c0d761ef 100644
--- a/common/lib/xmodule/xmodule/course_module.py
+++ b/common/lib/xmodule/xmodule/course_module.py
@@ -1,9 +1,9 @@
from fs.errors import ResourceNotFoundError
-import time
import logging
-import requests
from lxml import etree
from path import path # NOTE (THK): Only used for detecting presence of syllabus
+import requests
+import time
from xmodule.util.decorators import lazyproperty
from xmodule.graders import load_grading_policy
@@ -21,10 +21,15 @@ class CourseDescriptor(SequenceDescriptor):
self.title = title
self.book_url = book_url
self.table_of_contents = self._get_toc_from_s3()
-
- @classmethod
- def from_xml_object(cls, xml_object):
- return cls(xml_object.get('title'), xml_object.get('book_url'))
+ self.start_page = int(self.table_of_contents[0].attrib['page'])
+
+ # The last page should be the last element in the table of contents,
+ # but it may be nested. So recurse all the way down the last element
+ last_el = self.table_of_contents[-1]
+ while last_el.getchildren():
+ last_el = last_el[-1]
+
+ self.end_page = int(last_el.attrib['page'])
@property
def table_of_contents(self):
@@ -57,10 +62,18 @@ class CourseDescriptor(SequenceDescriptor):
return table_of_contents
-
def __init__(self, system, definition=None, **kwargs):
super(CourseDescriptor, self).__init__(system, definition, **kwargs)
- self.textbooks = self.definition['data']['textbooks']
+
+ self.textbooks = []
+ for title, book_url in self.definition['data']['textbooks']:
+ try:
+ self.textbooks.append(self.Textbook(title, book_url))
+ except:
+ # If we can't get to S3 (e.g. on a train with no internet), don't break
+ # the rest of the courseware.
+ log.exception("Couldn't load textbook ({0}, {1})".format(title, book_url))
+ continue
self.wiki_slug = self.definition['data']['wiki_slug'] or self.location.course
@@ -82,7 +95,6 @@ class CourseDescriptor(SequenceDescriptor):
# disable the syllabus content for courses that do not provide a syllabus
self.syllabus_present = self.system.resources_fs.exists(path('syllabus'))
-
def set_grading_policy(self, policy_str):
"""Parse the policy specified in policy_str, and save it"""
try:
@@ -94,19 +106,11 @@ class CourseDescriptor(SequenceDescriptor):
# the error log.
self._grading_policy = {}
-
@classmethod
def definition_from_xml(cls, xml_object, system):
textbooks = []
for textbook in xml_object.findall("textbook"):
- try:
- txt = cls.Textbook.from_xml_object(textbook)
- except:
- # If we can't get to S3 (e.g. on a train with no internet), don't break
- # the rest of the courseware.
- log.exception("Couldn't load textbook")
- continue
- textbooks.append(txt)
+ textbooks.append((textbook.get('title'), textbook.get('book_url')))
xml_object.remove(textbook)
#Load the wiki tag if it exists
@@ -116,7 +120,7 @@ class CourseDescriptor(SequenceDescriptor):
wiki_slug = wiki_tag.attrib.get("slug", default=None)
xml_object.remove(wiki_tag)
- definition = super(CourseDescriptor, cls).definition_from_xml(xml_object, system)
+ definition = super(CourseDescriptor, cls).definition_from_xml(xml_object, system)
definition.setdefault('data', {})['textbooks'] = textbooks
definition['data']['wiki_slug'] = wiki_slug
@@ -134,6 +138,13 @@ class CourseDescriptor(SequenceDescriptor):
def grade_cutoffs(self):
return self._grading_policy['GRADE_CUTOFFS']
+ @property
+ def tabs(self):
+ """
+ Return the tabs config, as a python object, or None if not specified.
+ """
+ return self.metadata.get('tabs')
+
@property
def show_calculator(self):
return self.metadata.get("show_calculator", None) == "Yes"
diff --git a/common/lib/xmodule/xmodule/css/capa/display.scss b/common/lib/xmodule/xmodule/css/capa/display.scss
index d7ffa198af..ce0d2d9bf7 100644
--- a/common/lib/xmodule/xmodule/css/capa/display.scss
+++ b/common/lib/xmodule/xmodule/css/capa/display.scss
@@ -53,6 +53,18 @@ section.problem {
float: left;
border-left: 1px solid #ddd;
padding-left: 20px;
+ margin: 20px 0;
+ }
+
+ input[type="radio"],
+ input[type="checkbox"] {
+ float: left;
+ margin: 4px 8px 0 0;
+ }
+
+ text {
+ display: block;
+ margin-left: 25px;
}
}
diff --git a/lms/static/js/jquery.sequence.js b/common/lib/xmodule/xmodule/js/src/sequence/display/jquery.sequence.js
similarity index 100%
rename from lms/static/js/jquery.sequence.js
rename to common/lib/xmodule/xmodule/js/src/sequence/display/jquery.sequence.js
diff --git a/common/lib/xmodule/xmodule/modulestore/mongo.py b/common/lib/xmodule/xmodule/modulestore/mongo.py
index 7aa05e474f..33901947a6 100644
--- a/common/lib/xmodule/xmodule/modulestore/mongo.py
+++ b/common/lib/xmodule/xmodule/modulestore/mongo.py
@@ -316,3 +316,9 @@ class MongoModuleStore(ModuleStoreBase):
{'_id': True})
return [i['_id'] for i in items]
+ def get_errored_courses(self):
+ """
+ This function doesn't make sense for the mongo modulestore, as courses
+ are loaded on demand, rather than up front
+ """
+ return {}
diff --git a/common/lib/xmodule/xmodule/modulestore/xml.py b/common/lib/xmodule/xmodule/modulestore/xml.py
index 82b0abd8ab..874c7d3d7f 100644
--- a/common/lib/xmodule/xmodule/modulestore/xml.py
+++ b/common/lib/xmodule/xmodule/modulestore/xml.py
@@ -414,7 +414,6 @@ class XMLModuleStore(ModuleStoreBase):
policy_str = self.read_grading_policy(paths, tracker)
course_descriptor.set_grading_policy(policy_str)
-
log.debug('========> Done with course import from {0}'.format(course_dir))
return course_descriptor
diff --git a/common/lib/xmodule/xmodule/seq_module.py b/common/lib/xmodule/xmodule/seq_module.py
index b05ea36e50..841936cf17 100644
--- a/common/lib/xmodule/xmodule/seq_module.py
+++ b/common/lib/xmodule/xmodule/seq_module.py
@@ -21,7 +21,8 @@ class SequenceModule(XModule):
''' Layout module which lays out content in a temporal sequence
'''
js = {'coffee': [resource_string(__name__,
- 'js/src/sequence/display.coffee')]}
+ 'js/src/sequence/display.coffee')],
+ 'js': [resource_string(__name__, 'js/src/sequence/display/jquery.sequence.js')]}
css = {'scss': [resource_string(__name__, 'css/sequence/display.scss')]}
js_module_name = "Sequence"
diff --git a/create-dev-env.sh b/create-dev-env.sh
index d28a5891d9..e7ffadf5f5 100755
--- a/create-dev-env.sh
+++ b/create-dev-env.sh
@@ -105,7 +105,7 @@ NUMPY_VER="1.6.2"
SCIPY_VER="0.10.1"
BREW_FILE="$BASE/mitx/brew-formulas.txt"
LOG="/var/tmp/install-$(date +%Y%m%d-%H%M%S).log"
-APT_PKGS="curl git python-virtualenv build-essential python-dev gfortran liblapack-dev libfreetype6-dev libpng12-dev libxml2-dev libxslt-dev yui-compressor coffeescript graphviz libgraphviz-dev"
+APT_PKGS="pkg-config curl git python-virtualenv build-essential python-dev gfortran liblapack-dev libfreetype6-dev libpng12-dev libxml2-dev libxslt-dev yui-compressor coffeescript graphviz graphviz-dev"
if [[ $EUID -eq 0 ]]; then
error "This script should not be run using sudo or as the root user"
diff --git a/doc/xml-format.md b/doc/xml-format.md
index 29c60fea99..9d07f432c9 100644
--- a/doc/xml-format.md
+++ b/doc/xml-format.md
@@ -219,6 +219,13 @@ Values are dictionaries of the form {"metadata-key" : "metadata-value"}.
* The order in which things appear does not matter, though it may be helpful to organize the file in the same order as things appear in the content.
* NOTE: json is picky about commas. If you have trailing commas before closing braces, it will complain and refuse to parse the file. This can be irritating at first.
+Supported fields at the course level:
+
+* "start" -- specify the start date for the course. Format-by-example: "2012-09-05T12:00".
+* "enrollment_start", "enrollment_end" -- when can students enroll? (if not specified, can enroll anytime). Same format as "start".
+* "tabs" -- have custom tabs in the courseware. See below for details on config.
+* TODO: there are others
+
### Grading policy file contents
TODO: This needs to be improved, but for now here's a sketch of how grading works:
@@ -274,6 +281,7 @@ __Inherited:__
* `showanswer` - When to show answer. For 'attempted', will show answer after first attempt. Values: never, attempted, answered, closed. Default: closed. Optional.
* `graded` - Whether this section will count towards the students grade. "true" or "false". Defaults to "false".
* `rerandomise` - Randomize question on each attempt. Values: 'always' (students see a different version of the problem after each attempt to solve it)
+ 'onreset' (randomize question when reset button is pressed by the student)
'never' (all students see the same version of the problem)
'per_student' (individual students see the same version of the problem each time the look at it, but that version is different from what other students see)
Default: 'always'. Optional.
@@ -340,7 +348,43 @@ If you look at some older xml, you may see some tags or metadata attributes that
# Static links
-if your content links (e.g. in an html file) to `"static/blah/ponies.jpg"`, we will look for this in `YOUR_COURSE_DIR/blah/ponies.jpg`. Note that this is not looking in a `static/` subfolder in your course dir. This may (should?) change at some point. Links that include `/course` will be rewritten to the root of your course in the courseware (e.g. `courses/{org}/{course}/{url_name}/` in the current url structure). This is useful for linking to the course wiki, for example.
+If your content links (e.g. in an html file) to `"static/blah/ponies.jpg"`, we will look for this...
+
+* If your course dir has a `static/` subdirectory, we will look in `YOUR_COURSE_DIR/static/blah/ponies.jpg`. This is the prefered organization, as it does not expose anything except what's in `static/` to the world.
+* If your course dir does not have a `static/` subdirectory, we will look in `YOUR_COURSE_DIR/blah/ponies.jpg`. This is the old organization, and requires that the web server allow access to everything in the couse dir. To switch to the new organization, move all your static content into a new `static/` dir (e.g. if you currently have things in `images/`, `css/`, and `special/`, create a dir called `static/`, and move `images/, css/, and special/` there).
+
+Links that include `/course` will be rewritten to the root of your course in the courseware (e.g. `courses/{org}/{course}/{url_name}/` in the current url structure). This is useful for linking to the course wiki, for example.
+
+# Tabs
+
+If you want to customize the courseware tabs displayed for your course, specify a "tabs" list in the course-level policy. e.g.:
+
+ "tabs" : [
+ {"type": "courseware"}, # no name--always "Courseware" for consistency between courses
+ {"type": "course_info", "name": "Course Info"},
+ {"type": "external_link", "name": "My Discussion", "link": "http://www.mydiscussion.org/blah"},
+ {"type": "progress", "name": "Progress"},
+ {"type": "wiki", "name": "Wonderwiki"},
+ {"type": "static_tab", "url_slug": "news", "name": "Exciting news"},
+ {"type": "textbooks"} # generates one tab per textbook, taking names from the textbook titles
+ ]
+
+
+* If you specify any tabs, you must specify all tabs. They will appear in the order given.
+* The first two tabs must have types `"courseware"` and `"course_info"`, in that order. Otherwise, we'll refuse to load the course.
+* for static tabs, the url_slug will be the url that points to the tab. It can not be one of the existing courseware url types (even if those aren't used in your course). The static content will come from `tabs/{course_url_name}/{url_slug}.html`, or `tabs/{url_slug}.html` if that doesn't exist.
+
+* An Instructor tab will be automatically added at the end for course staff users.
+
+## Supported tab types:
+
+* "courseware". No other parameters.
+* "course_info". Parameter "name".
+* "wiki". Parameter "name".
+* "discussion". Parameter "name".
+* "external_link". Parameters "name", "link".
+* "textbooks". No parameters--generates tab names from book titles.
+* "progress". Parameter "name".
# Tips for content developers
diff --git a/lms/djangoapps/courseware/module_render.py b/lms/djangoapps/courseware/module_render.py
index b033660c17..a65d73e4bc 100644
--- a/lms/djangoapps/courseware/module_render.py
+++ b/lms/djangoapps/courseware/module_render.py
@@ -254,12 +254,11 @@ def _get_module(user, request, location, student_module_cache, course_id, positi
module.get_html = replace_static_urls(
wrap_xmodule(module.get_html, module, 'xmodule_display.html'),
- module.metadata['data_dir'], module
- )
+ module.metadata['data_dir'])
# Allow URLs of the form '/course/' refer to the root of multicourse directory
# hierarchy of this course
- module.get_html = replace_course_urls(module.get_html, course_id, module)
+ module.get_html = replace_course_urls(module.get_html, course_id)
if settings.MITX_FEATURES.get('DISPLAY_HISTOGRAMS_TO_STAFF'):
if has_access(user, module, 'staff'):
diff --git a/lms/djangoapps/courseware/tabs.py b/lms/djangoapps/courseware/tabs.py
new file mode 100644
index 0000000000..8ec856e5b3
--- /dev/null
+++ b/lms/djangoapps/courseware/tabs.py
@@ -0,0 +1,274 @@
+"""
+Tabs configuration. By the time the tab is being rendered, it's just a name,
+link, and css class (CourseTab tuple). Tabs are specified in course policy.
+Each tab has a type, and possibly some type-specific parameters.
+
+To add a new tab type, add a TabImpl to the VALID_TAB_TYPES dict below--it will
+contain a validation function that checks whether config for the tab type is
+valid, and a generator function that takes the config, user, and course, and
+actually generates the CourseTab.
+"""
+
+from collections import namedtuple
+import logging
+
+from django.conf import settings
+from django.core.urlresolvers import reverse
+
+from courseware.access import has_access
+from static_replace import replace_urls
+
+log = logging.getLogger(__name__)
+
+class InvalidTabsException(Exception):
+ """
+ A complaint about invalid tabs.
+ """
+ pass
+
+CourseTab = namedtuple('CourseTab', 'name link is_active')
+
+# encapsulate implementation for a tab:
+# - a validation function: takes the config dict and raises
+# InvalidTabsException if required fields are missing or otherwise
+# wrong. (e.g. "is there a 'name' field?). Validators can assume
+# that the type field is valid.
+#
+# - a function that takes a config, a user, and a course, and active_page and
+# return a list of CourseTabs. (e.g. "return a CourseTab with specified
+# name, link to courseware, and is_active=True/False"). The function can
+# assume that it is only called with configs of the appropriate type that
+# have passed the corresponding validator.
+TabImpl = namedtuple('TabImpl', 'validator generator')
+
+
+##### Generators for various tabs.
+
+def _courseware(tab, user, course, active_page):
+ link = reverse('courseware', args=[course.id])
+ return [CourseTab('Courseware', link, active_page == "courseware")]
+
+def _course_info(tab, user, course, active_page):
+ link = reverse('info', args=[course.id])
+ return [CourseTab(tab['name'], link, active_page == "info")]
+
+def _progress(tab, user, course, active_page):
+ if user.is_authenticated():
+ link = reverse('progress', args=[course.id])
+ return [CourseTab(tab['name'], link, active_page == "progress")]
+ return []
+
+def _wiki(tab, user, course, active_page):
+ if settings.WIKI_ENABLED:
+ link = reverse('course_wiki', args=[course.id])
+ return [CourseTab(tab['name'], link, active_page == 'wiki')]
+ return []
+
+def _discussion(tab, user, course, active_page):
+ """
+ This tab format only supports the new Berkeley discussion forums.
+ """
+ if settings.MITX_FEATURES.get('ENABLE_DISCUSSION_SERVICE'):
+ link = reverse('django_comment_client.forum.views.forum_form_discussion',
+ args=[course.id])
+ return [CourseTab(tab['name'], link, active_page=='discussion')]
+ return []
+
+def _external_link(tab, user, course, active_page):
+ # external links are never active
+ return [CourseTab(tab['name'], tab['link'], False)]
+
+def _static_tab(tab, user, course, active_page):
+ link = reverse('static_tab', args=[course.id, tab['url_slug']])
+ active_str = 'static_tab_{0}'.format(tab['url_slug'])
+ return [CourseTab(tab['name'], link, active_page==active_str)]
+
+
+def _textbooks(tab, user, course, active_page):
+ """
+ Generates one tab per textbook. Only displays if user is authenticated.
+ """
+ if user.is_authenticated() and settings.MITX_FEATURES.get('ENABLE_TEXTBOOK'):
+ # since there can be more than one textbook, active_page is e.g. "book/0".
+ return [CourseTab(textbook.title, reverse('book', args=[course.id, index]),
+ active_page=="textbook/{0}".format(index))
+ for index, textbook in enumerate(course.textbooks)]
+ return []
+
+#### Validators
+
+
+def key_checker(expected_keys):
+ """
+ Returns a function that checks that specified keys are present in a dict
+ """
+ def check(d):
+ for k in expected_keys:
+ if k not in d:
+ raise InvalidTabsException("Key {0} not present in {1}"
+ .format(k, d))
+ return check
+
+
+need_name = key_checker(['name'])
+
+def null_validator(d):
+ """
+ Don't check anything--use for tabs that don't need any params. (e.g. textbook)
+ """
+ pass
+
+##### The main tab config dict.
+
+# type -> TabImpl
+VALID_TAB_TYPES = {
+ 'courseware': TabImpl(null_validator, _courseware),
+ 'course_info': TabImpl(need_name, _course_info),
+ 'wiki': TabImpl(need_name, _wiki),
+ 'discussion': TabImpl(need_name, _discussion),
+ 'external_link': TabImpl(key_checker(['name', 'link']), _external_link),
+ 'textbooks': TabImpl(null_validator, _textbooks),
+ 'progress': TabImpl(need_name, _progress),
+ 'static_tab': TabImpl(key_checker(['name', 'url_slug']), _static_tab),
+ }
+
+
+### External interface below this.
+
+def validate_tabs(course):
+ """
+ Check that the tabs set for the specified course is valid. If it
+ isn't, raise InvalidTabsException with the complaint.
+
+ Specific rules checked:
+ - if no tabs specified, that's fine
+ - if tabs specified, first two must have type 'courseware' and 'course_info', in that order.
+ - All the tabs must have a type in VALID_TAB_TYPES.
+
+ """
+ tabs = course.tabs
+ if tabs is None:
+ return
+
+ if len(tabs) < 2:
+ raise InvalidTabsException("Expected at least two tabs. tabs: '{0}'".format(tabs))
+ if tabs[0]['type'] != 'courseware':
+ raise InvalidTabsException(
+ "Expected first tab to have type 'courseware'. tabs: '{0}'".format(tabs))
+ if tabs[1]['type'] != 'course_info':
+ raise InvalidTabsException(
+ "Expected second tab to have type 'course_info'. tabs: '{0}'".format(tabs))
+ for t in tabs:
+ if t['type'] not in VALID_TAB_TYPES:
+ raise InvalidTabsException("Unknown tab type {0}. Known types: {1}"
+ .format(t['type'], VALID_TAB_TYPES))
+ # the type-specific validator checks the rest of the tab config
+ VALID_TAB_TYPES[t['type']].validator(t)
+
+ # Possible other checks: make sure tabs that should only appear once (e.g. courseware)
+ # are actually unique (otherwise, will break active tag code)
+
+
+def get_course_tabs(user, course, active_page):
+ """
+ Return the tabs to show a particular user, as a list of CourseTab items.
+ """
+ if not course.tabs:
+ return get_default_tabs(user, course, active_page)
+
+ # TODO (vshnayder): There needs to be a place to call this right after course
+ # load, but not from inside xmodule, since that doesn't (and probably
+ # shouldn't) know about the details of what tabs are supported, etc.
+ validate_tabs(course)
+
+ tabs = []
+ for tab in course.tabs:
+ # expect handlers to return lists--handles things that are turned off
+ # via feature flags, and things like 'textbook' which might generate
+ # multiple tabs.
+ gen = VALID_TAB_TYPES[tab['type']].generator
+ tabs.extend(gen(tab, user, course, active_page))
+
+ # Instructor tab is special--automatically added if user is staff for the course
+ if has_access(user, course, 'staff'):
+ tabs.append(CourseTab('Instructor',
+ reverse('instructor_dashboard', args=[course.id]),
+ active_page == 'instructor'))
+ return tabs
+
+
+def get_default_tabs(user, course, active_page):
+
+ # When calling the various _tab methods, can omit the 'type':'blah' from the
+ # first arg, since that's only used for dispatch
+ tabs = []
+ tabs.extend(_courseware({''}, user, course, active_page))
+ tabs.extend(_course_info({'name': 'Course Info'}, user, course, active_page))
+
+ if hasattr(course, 'syllabus_present') and course.syllabus_present:
+ link = reverse('syllabus', args=[course.id])
+ tabs.append(CourseTab('Syllabus', link, active_page=='syllabus'))
+
+ tabs.extend(_textbooks({}, user, course, active_page))
+
+ ## If they have a discussion link specified, use that even if we feature
+ ## flag discussions off. Disabling that is mostly a server safety feature
+ ## at this point, and we don't need to worry about external sites.
+ if course.discussion_link:
+ tabs.append(CourseTab('Discussion', course.discussion_link, active_page == 'discussion'))
+ elif settings.MITX_FEATURES.get('ENABLE_DISCUSSION_SERVICE'):
+ link = reverse('django_comment_client.forum.views.forum_form_discussion',
+ args=[course.id])
+ tabs.append(CourseTab('Discussion', link, active_page == 'discussion'))
+ elif settings.MITX_FEATURES.get('ENABLE_DISCUSSION'):
+ ## This is Askbot, which we should be retiring soon...
+ tabs.append(CourseTab('Discussion', reverse('questions'), active_page == 'discussion'))
+
+ tabs.extend(_wiki({'name': 'Wiki', 'type': 'wiki'}, user, course, active_page))
+
+ if user.is_authenticated() and not course.hide_progress_tab:
+ tabs.extend(_progress({'name': 'Progress'}, user, course, active_page))
+
+ if has_access(user, course, 'staff'):
+ link = reverse('instructor_dashboard', args=[course.id])
+ tabs.append(CourseTab('Instructor', link, active_page=='instructor'))
+
+ return tabs
+
+def get_static_tab_by_slug(course, tab_slug):
+ """
+ Look for a tab with type 'static_tab' and the specified 'tab_slug'. Returns
+ the tab (a config dict), or None if not found.
+ """
+ if course.tabs is None:
+ return None
+ for tab in course.tabs:
+ # The validation code checks that these exist.
+ if tab['type'] == 'static_tab' and tab['url_slug'] == tab_slug:
+ return tab
+
+ return None
+
+
+def get_static_tab_contents(course, tab):
+ """
+ Given a course and a static tab config dict, load the tab contents,
+ returning None if not found.
+
+ Looks in tabs/{course_url_name}/{tab_slug}.html first, then tabs/{tab_slug}.html.
+ """
+ slug = tab['url_slug']
+ paths = ['tabs/{0}/{1}.html'.format(course.url_name, slug),
+ 'tabs/{0}.html'.format(slug)]
+ fs = course.system.resources_fs
+ for p in paths:
+ if fs.exists(p):
+ try:
+ with fs.open(p) as tabfile:
+ # TODO: redundant with module_render.py. Want to be helper methods in static_replace or something.
+ contents = replace_urls(tabfile.read(), course.metadata['data_dir'])
+ return replace_urls(contents, staticfiles_prefix='/courses/'+course.id, replace_prefix='/course/')
+ except (ResourceNotFoundError) as err:
+ log.exception("Couldn't load tab contents from '{0}': {1}".format(p, err))
+ return None
+ return None
diff --git a/lms/djangoapps/courseware/views.py b/lms/djangoapps/courseware/views.py
index c474da8d8b..269977e458 100644
--- a/lms/djangoapps/courseware/views.py
+++ b/lms/djangoapps/courseware/views.py
@@ -22,6 +22,7 @@ from django.views.decorators.cache import cache_control
from courseware import grades
from courseware.access import has_access
from courseware.courses import (get_course_with_access, get_courses_by_university)
+import courseware.tabs as tabs
from models import StudentModuleCache
from module_render import toc_for_course, get_module, get_instance_module
from student.models import UserProfile
@@ -343,6 +344,30 @@ def course_info(request, course_id):
return render_to_response('courseware/info.html', {'course': course,
'staff_access': staff_access,})
+@ensure_csrf_cookie
+def static_tab(request, course_id, tab_slug):
+ """
+ Display the courses tab with the given name.
+
+ Assumes the course_id is in a valid format.
+ """
+ course = get_course_with_access(request.user, course_id, 'load')
+
+ tab = tabs.get_static_tab_by_slug(course, tab_slug)
+ if tab is None:
+ raise Http404
+
+ contents = tabs.get_static_tab_contents(course, tab)
+ if contents is None:
+ raise Http404
+
+ staff_access = has_access(request.user, course, 'staff')
+ return render_to_response('courseware/static_tab.html',
+ {'course': course,
+ 'tab': tab,
+ 'tab_contents': contents,
+ 'staff_access': staff_access,})
+
# TODO arjun: remove when custom tabs in place, see courseware/syllabus.py
@ensure_csrf_cookie
def syllabus(request, course_id):
@@ -357,6 +382,7 @@ def syllabus(request, course_id):
return render_to_response('courseware/syllabus.html', {'course': course,
'staff_access': staff_access,})
+
def registered_for_course(course, user):
'''Return CourseEnrollment if user is registered for course, else False'''
if user is None:
@@ -404,6 +430,9 @@ def university_profile(request, org_id):
context = dict(courses=courses, org_id=org_id)
template_file = "university_profile/{0}.html".format(org_id).lower()
+ if request.REQUEST.get('next', False):
+ context['show_login_immediately'] = True
+
return render_to_response(template_file, context)
def render_notifications(request, course, notifications):
diff --git a/lms/djangoapps/django_comment_client/forum/views.py b/lms/djangoapps/django_comment_client/forum/views.py
index a883ab92e0..35e7fd6618 100644
--- a/lms/djangoapps/django_comment_client/forum/views.py
+++ b/lms/djangoapps/django_comment_client/forum/views.py
@@ -43,6 +43,7 @@ def get_threads(request, course_id, discussion_id=None, per_page=THREADS_PER_PAG
'tags': '',
'commentable_id': discussion_id,
'course_id': course_id,
+ 'user_id': request.user.id,
}
if not request.GET.get('sort_key'):
@@ -81,6 +82,7 @@ def inline_discussion(request, course_id, discussion_id):
# TODO (vshnayder): since none of this code seems to be aware of the fact that
# sometimes things go wrong, I suspect that the js client is also not
# checking for errors on request. Check and fix as needed.
+ log.error("Error loading inline discussion threads.")
raise Http404
annotated_content_info = utils.get_metadata_for_threads(course_id, threads, request.user, user_info)
@@ -111,6 +113,7 @@ def forum_form_discussion(request, course_id):
unsafethreads, query_params = get_threads(request, course_id) # This might process a search query
threads = [utils.safe_content(thread) for thread in unsafethreads]
except (cc.utils.CommentClientError, cc.utils.CommentClientUnknownError) as err:
+ log.error("Error loading forum discussion threads: %s" % str(err))
raise Http404
user_info = cc.User.from_django_user(request.user).to_dict()
@@ -159,14 +162,18 @@ def forum_form_discussion(request, course_id):
@login_required
def single_thread(request, course_id, discussion_id, thread_id):
- if request.is_ajax():
- course = get_course_with_access(request.user, course_id, 'load')
- user_info = cc.User.from_django_user(request.user).to_dict()
+ course = get_course_with_access(request.user, course_id, 'load')
+ cc_user = cc.User.from_django_user(request.user)
+ user_info = cc_user.to_dict()
+
+ try:
+ thread = cc.Thread.find(thread_id).retrieve(recursive=True, user_id=request.user.id)
+ except (cc.utils.CommentClientError, cc.utils.CommentClientUnknownError) as err:
+ log.error("Error loading single thread.")
+ raise Http404
+
+ if request.is_ajax():
- try:
- thread = cc.Thread.find(thread_id).retrieve(recursive=True)
- except (cc.utils.CommentClientError, cc.utils.CommentClientUnknownError) as err:
- raise Http404
courseware_context = get_courseware_context(thread, course)
annotated_content_info = utils.get_annotated_content_infos(course_id, thread, request.user, user_info=user_info)
@@ -183,13 +190,13 @@ def single_thread(request, course_id, discussion_id, thread_id):
})
else:
- course = get_course_with_access(request.user, course_id, 'load')
category_map = utils.get_discussion_category_map(course)
+
try:
threads, query_params = get_threads(request, course_id)
- thread = cc.Thread.find(thread_id).retrieve(recursive=True)
threads.append(thread.to_dict())
except (cc.utils.CommentClientError, cc.utils.CommentClientUnknownError) as err:
+ log.error("Error loading single thread.")
raise Http404
course = get_course_with_access(request.user, course_id, 'load')
@@ -211,8 +218,7 @@ def single_thread(request, course_id, discussion_id, thread_id):
# course_id,
#)
- user_info = cc.User.from_django_user(request.user).to_dict()
-
+
annotated_content_info = utils.get_metadata_for_threads(course_id, threads, request.user, user_info)
context = {
diff --git a/lms/djangoapps/django_comment_client/utils.py b/lms/djangoapps/django_comment_client/utils.py
index 1dcb5522f7..1a77bf1434 100644
--- a/lms/djangoapps/django_comment_client/utils.py
+++ b/lms/djangoapps/django_comment_client/utils.py
@@ -189,7 +189,7 @@ def initialize_discussion_info(course):
"sort_key": entry["sort_key"],
"start_date": entry["start_date"]}
- default_topics = {'General': course.location.html_id()}
+ default_topics = {'General': {'id' :course.location.html_id()}}
discussion_topics = course.metadata.get('discussion_topics', default_topics)
for topic, entry in discussion_topics.items():
category_map['entries'][topic] = {"id": entry["id"],
@@ -351,7 +351,8 @@ def safe_content(content):
'endorsed', 'parent_id', 'thread_id', 'votes', 'closed', 'created_at',
'updated_at', 'depth', 'type', 'commentable_id', 'comments_count',
'at_position_list', 'children', 'highlighted_title', 'highlighted_body',
- 'courseware_title', 'courseware_url', 'tags'
+ 'courseware_title', 'courseware_url', 'tags', 'unread_comments_count',
+ 'read',
]
if (content.get('anonymous') is False) and (content.get('anonymous_to_peers') is False):
diff --git a/lms/djangoapps/instructor/views.py b/lms/djangoapps/instructor/views.py
index d812791c3d..312a46142a 100644
--- a/lms/djangoapps/instructor/views.py
+++ b/lms/djangoapps/instructor/views.py
@@ -85,7 +85,8 @@ def instructor_dashboard(request, course_id):
writer = csv.writer(response, dialect='excel', quotechar='"', quoting=csv.QUOTE_ALL)
writer.writerow(datatable['header'])
for datarow in datatable['data']:
- writer.writerow(datarow)
+ encoded_row = [unicode(s).encode('utf-8') for s in datarow]
+ writer.writerow(encoded_row)
return response
def get_staff_group(course):
@@ -250,7 +251,7 @@ def get_student_grade_summary_data(request, course, course_id, get_grades=True,
If get_raw_scores=True, then instead of grade summaries, the raw grades for all graded modules are returned.
'''
- enrolled_students = User.objects.filter(courseenrollment__course_id=course_id).order_by('username')
+ enrolled_students = User.objects.filter(courseenrollment__course_id=course_id).prefetch_related("groups").order_by('username')
header = ['ID', 'Username', 'Full Name', 'edX email', 'External email']
if get_grades:
diff --git a/lms/djangoapps/staticbook/views.py b/lms/djangoapps/staticbook/views.py
index d68117dd8a..fabb8b861c 100644
--- a/lms/djangoapps/staticbook/views.py
+++ b/lms/djangoapps/staticbook/views.py
@@ -7,16 +7,23 @@ from courseware.courses import get_course_with_access
from lxml import etree
@login_required
-def index(request, course_id, book_index, page=0):
+def index(request, course_id, book_index, page=None):
course = get_course_with_access(request.user, course_id, 'load')
staff_access = has_access(request.user, course, 'staff')
- textbook = course.textbooks[int(book_index)]
+ book_index = int(book_index)
+ textbook = course.textbooks[book_index]
table_of_contents = textbook.table_of_contents
+ if page is None:
+ page = textbook.start_page
+
return render_to_response('staticbook.html',
- {'page': int(page), 'course': course, 'book_url': textbook.book_url,
+ {'book_index': book_index, 'page': int(page),
+ 'course': course, 'book_url': textbook.book_url,
'table_of_contents': table_of_contents,
+ 'start_page' : textbook.start_page,
+ 'end_page' : textbook.end_page,
'staff_access': staff_access})
def index_shifted(request, course_id, page):
diff --git a/lms/envs/cms/__init__.py b/lms/envs/cms/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/lms/envs/with_cms.py b/lms/envs/cms/aws.py
similarity index 100%
rename from lms/envs/with_cms.py
rename to lms/envs/cms/aws.py
diff --git a/lms/envs/cms/dev.py b/lms/envs/cms/dev.py
new file mode 100644
index 0000000000..6e4697cccb
--- /dev/null
+++ b/lms/envs/cms/dev.py
@@ -0,0 +1,19 @@
+"""
+Settings for the LMS that runs alongside the CMS on AWS
+"""
+
+from ..dev import *
+
+MODULESTORE = {
+ 'default': {
+ 'ENGINE': 'xmodule.modulestore.mongo.MongoModuleStore',
+ 'OPTIONS': {
+ 'default_class': 'xmodule.raw_module.RawDescriptor',
+ 'host': 'localhost',
+ 'db': 'xmodule',
+ 'collection': 'modulestore',
+ 'fs_root': DATA_DIR,
+ 'render_template': 'mitxmako.shortcuts.render_to_string',
+ }
+ }
+}
diff --git a/lms/envs/common.py b/lms/envs/common.py
index 8e91565784..4681f5fd9a 100644
--- a/lms/envs/common.py
+++ b/lms/envs/common.py
@@ -550,6 +550,8 @@ PIPELINE_JS = {
}
}
+PIPELINE_DISABLE_WRAPPER = True
+
# Compile all coffee files in course data directories if they are out of date.
# TODO: Remove this once we move data into Mongo. This is only temporary while
# course data directories are still in use.
diff --git a/lms/lib/comment_client/thread.py b/lms/lib/comment_client/thread.py
index bda032bbdf..424250033e 100644
--- a/lms/lib/comment_client/thread.py
+++ b/lms/lib/comment_client/thread.py
@@ -8,8 +8,9 @@ class Thread(models.Model):
accessible_fields = [
'id', 'title', 'body', 'anonymous', 'anonymous_to_peers', 'course_id',
'closed', 'tags', 'votes', 'commentable_id', 'username', 'user_id',
- 'created_at', 'updated_at', 'comments_count', 'at_position_list',
- 'children', 'type', 'highlighted_title', 'highlighted_body', 'endorsed'
+ 'created_at', 'updated_at', 'comments_count', 'unread_comments_count',
+ 'at_position_list', 'children', 'type', 'highlighted_title',
+ 'highlighted_body', 'endorsed', 'read'
]
updatable_fields = [
@@ -59,7 +60,21 @@ class Thread(models.Model):
else:
return super(Thread, cls).url(action, params)
+ # TODO: This is currently overriding Model._retrieve only to add parameters
+ # for the request. Model._retrieve should be modified to handle this such
+ # that subclasses don't need to override for this.
def _retrieve(self, *args, **kwargs):
url = self.url(action='get', params=self.attributes)
- response = perform_request('get', url, {'recursive': kwargs.get('recursive')})
+
+ request_params = {
+ 'recursive': kwargs.get('recursive'),
+ 'user_id': kwargs.get('user_id'),
+ 'mark_as_read': kwargs.get('mark_as_read', True),
+ }
+
+ # user_id may be none, in which case it shouldn't be part of the
+ # request.
+ request_params = strip_none(request_params)
+
+ response = perform_request('get', url, request_params)
self.update_attributes(**response)
diff --git a/lms/static/coffee/src/discussion/discussion_router.coffee b/lms/static/coffee/src/discussion/discussion_router.coffee
index a5219a68b9..50c14b20de 100644
--- a/lms/static/coffee/src/discussion/discussion_router.coffee
+++ b/lms/static/coffee/src/discussion/discussion_router.coffee
@@ -27,6 +27,8 @@ if Backbone?
showThread: (forum_name, thread_id) ->
@thread = @discussion.get(thread_id)
+ @thread.set("unread_comments_count", 0)
+ @thread.set("read", true)
@setActiveThread()
if(@main)
@main.cleanup()
diff --git a/lms/static/coffee/src/discussion/views/discussion_thread_list_view.coffee b/lms/static/coffee/src/discussion/views/discussion_thread_list_view.coffee
index 9239620754..529efa2620 100644
--- a/lms/static/coffee/src/discussion/views/discussion_thread_list_view.coffee
+++ b/lms/static/coffee/src/discussion/views/discussion_thread_list_view.coffee
@@ -140,6 +140,8 @@ if Backbone?
content.addClass("followed")
if thread.get('endorsed')
content.addClass("resolved")
+ if thread.get('read')
+ content.addClass("read")
@highlight(content)
diff --git a/lms/static/sass/_discussion.scss b/lms/static/sass/_discussion.scss
index 79c853f42d..8d1257d440 100644
--- a/lms/static/sass/_discussion.scss
+++ b/lms/static/sass/_discussion.scss
@@ -1018,6 +1018,7 @@ body.discussion {
text-shadow: 0 -1px 0 rgba(0, 0, 0, .3);
box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 1px rgba(0, 0, 0, .2) inset;
}
+
}
}
@@ -1052,14 +1053,17 @@ body.discussion {
}
a {
- position: relative;
display: block;
- height: 36px;
+ position: relative;
+ float: left;
+ clear: both;
+ width: 100%;
padding: 0 10px 0 18px;
margin-bottom: 1px;
margin-right: -1px;
@include linear-gradient(top, rgba(255, 255, 255, .7), rgba(255, 255, 255, 0));
background-color: #fff;
+ @include clearfix;
&:hover {
@include linear-gradient(top, rgba(255, 255, 255, .7), rgba(255, 255, 255, 0));
@@ -1096,15 +1100,23 @@ body.discussion {
}
.title {
+ display: block;
+ float: left;
+ width: 70%;
+ margin: 8px 0 10px;
font-size: 13px;
font-weight: 700;
- line-height: 34px;
+ line-height: 1.4;
color: #333;
}
- &.read .title {
- font-weight: 400;
- color: #737373;
+ &.read {
+ background: #f2f2f2;
+
+ .title {
+ font-weight: 400;
+ color: #737373;
+ }
}
&.resolved:before {
@@ -1121,7 +1133,7 @@ body.discussion {
content: '';
position: absolute;
top: 0;
- right: 1px;
+ right: 0;
width: 10px;
height: 12px;
background: url(../images/following-flag.png) no-repeat;
@@ -1164,22 +1176,13 @@ body.discussion {
}
}
- .title {
- display: block;
- float: left;
- width: 70%;
- white-space: nowrap;
- text-overflow: ellipsis;
- overflow: hidden;
- }
-
.votes-count,
.comments-count {
display: block;
float: right;
width: 32px;
height: 16px;
- margin-top: 9px;
+ margin-top: 8px;
border-radius: 2px;
@include linear-gradient(top, #d4d4d4, #dfdfdf);
font-size: 11px;
@@ -1206,12 +1209,13 @@ body.discussion {
background-position: 0 -5px;
}
- &.new {
- @include linear-gradient(top, #84d7fe, #99e0fe);
+ &.unread {
+ @include linear-gradient(top, #84d7fe, #60a8d6);
color: #333;
&:after {
color: #99e0fe;
+ background-position: 0 0px;
}
}
}
@@ -1320,6 +1324,7 @@ body.discussion {
position: relative;
z-index: 100;
margin-top: 5px;
+ margin-left: 40px;
}
.post-tools {
@@ -1475,17 +1480,31 @@ body.discussion {
}
}
+ blockquote {
+ background: #f6f6f6;
+ border-radius: 3px;
+ padding: 5px 10px;
+ font-size: 14px;
+ }
+
.comments {
list-style: none;
margin-top: 20px;
padding: 0;
border-top: 1px solid #ddd;
- li {
+ > li {
background: #f6f6f6;
border-bottom: 1px solid #ddd;
}
+ blockquote {
+ background: #e6e6e6;
+ border-radius: 3px;
+ padding: 5px 10px;
+ font-size: 14px;
+ }
+
.comment-form {
background: #eee;
@include clearfix;
@@ -1509,7 +1528,6 @@ body.discussion {
.discussion-errors {
margin: 0px;
}
-
}
.response-body {
diff --git a/lms/templates/courseware/course_navigation.html b/lms/templates/courseware/course_navigation.html
index ffa8b0cadd..5ae69908fb 100644
--- a/lms/templates/courseware/course_navigation.html
+++ b/lms/templates/courseware/course_navigation.html
@@ -6,54 +6,21 @@ if active_page == None and active_page_context is not UNDEFINED:
# If active_page is not passed in as an argument, it may be in the context as active_page_context
active_page = active_page_context
-def url_class(url):
- if url == active_page:
+def url_class(is_active):
+ if is_active:
return "active"
return ""
%>
-<%! from django.core.urlresolvers import reverse %>
-<%! from courseware.access import has_access %>
+<%! from courseware.tabs import get_course_tabs %>