Commit 72dee8ba by Lyla Fischer

merge with master

parents a0201f37 98f19470
import hashlib import hashlib
import json
import logging import logging
import os import os
import re import re
...@@ -14,7 +13,7 @@ try: # This lets us do __name__ == ='__main__' ...@@ -14,7 +13,7 @@ try: # This lets us do __name__ == ='__main__'
from student.models import UserProfile from student.models import UserProfile
from student.models import UserTestGroup from student.models import UserTestGroup
from mitxmako.shortcuts import render_to_response, render_to_string from mitxmako.shortcuts import render_to_string
from util.cache import cache from util.cache import cache
except: except:
settings = None settings = None
...@@ -97,20 +96,9 @@ def item(l, default="", process=lambda x:x): ...@@ -97,20 +96,9 @@ def item(l, default="", process=lambda x:x):
def id_tag(course): def id_tag(course):
''' Tag all course elements with unique IDs ''' ''' Tag all course elements with unique IDs '''
old_ids = {'video':'youtube',
'problem':'filename',
'sequential':'id',
'html':'filename',
'vertical':'id',
'tab':'id',
'schematic':'id',
'book' : 'id'}
import courseware.modules import courseware.modules
default_ids = courseware.modules.get_default_ids() default_ids = courseware.modules.get_default_ids()
#print default_ids, old_ids
#print default_ids == old_ids
# Tag elements with unique IDs # Tag elements with unique IDs
elements = course.xpath("|".join(['//'+c for c in default_ids])) elements = course.xpath("|".join(['//'+c for c in default_ids]))
for elem in elements: for elem in elements:
...@@ -153,6 +141,9 @@ def propogate_downward_tag(element, attribute_name, parent_attribute = None): ...@@ -153,6 +141,9 @@ def propogate_downward_tag(element, attribute_name, parent_attribute = None):
return return
def user_groups(user): def user_groups(user):
if not user.is_authenticated():
return []
# TODO: Rewrite in Django # TODO: Rewrite in Django
key = 'user_group_names_{user.id}'.format(user=user) key = 'user_group_names_{user.id}'.format(user=user)
cache_expiration = 60 * 60 # one hour cache_expiration = 60 * 60 # one hour
...@@ -183,11 +174,12 @@ def course_xml_process(tree): ...@@ -183,11 +174,12 @@ def course_xml_process(tree):
def course_file(user): def course_file(user):
''' Given a user, return course.xml''' ''' Given a user, return course.xml'''
#import logging
#log = logging.getLogger("tracking")
#log.info( "DEBUG: cf:"+str(user) )
filename = UserProfile.objects.get(user=user).courseware # user.profile_cache.courseware if user.is_authenticated():
filename = UserProfile.objects.get(user=user).courseware # user.profile_cache.courseware
else:
filename = 'guest_course.xml'
groups = user_groups(user) groups = user_groups(user)
options = {'dev_content':settings.DEV_CONTENT, options = {'dev_content':settings.DEV_CONTENT,
'groups' : groups} 'groups' : groups}
......
import StringIO
import json
import logging import logging
import os
import sys
import sys
import urllib
import uuid
from lxml import etree from lxml import etree
from django.conf import settings
from django.contrib.auth.models import User
from django.core.context_processors import csrf
from django.db import connection
from django.http import Http404 from django.http import Http404
from django.http import HttpResponse from django.http import HttpResponse
from django.shortcuts import redirect from django.shortcuts import redirect
...@@ -21,15 +10,13 @@ from django.template import Context, loader ...@@ -21,15 +10,13 @@ from django.template import Context, loader
from fs.osfs import OSFS from fs.osfs import OSFS
from mitxmako.shortcuts import render_to_response, render_to_string from django.conf import settings
from mitxmako.shortcuts import render_to_string
from models import StudentModule from models import StudentModule
from student.models import UserProfile
import track.views import track.views
import courseware.content_parser as content_parser
import courseware.modules import courseware.modules
log = logging.getLogger("mitx.courseware") log = logging.getLogger("mitx.courseware")
...@@ -62,60 +49,11 @@ def make_track_function(request): ...@@ -62,60 +49,11 @@ def make_track_function(request):
def f(event_type, event): def f(event_type, event):
return track.views.server_track(request, event_type, event, page='x_module') return track.views.server_track(request, event_type, event, page='x_module')
return f return f
def modx_dispatch(request, module=None, dispatch=None, id=None):
''' Generic view for extensions. '''
if not request.user.is_authenticated():
return redirect('/')
# Grab the student information for the module from the database
s = StudentModule.objects.filter(student=request.user,
module_id=id)
#s = StudentModule.get_with_caching(request.user, id)
if len(s) == 0 or s is None:
log.debug("Couldnt find module for user and id " + str(module) + " " + str(request.user) + " "+ str(id))
raise Http404
s = s[0]
oldgrade = s.grade
oldstate = s.state
dispatch=dispatch.split('?')[0]
ajax_url = '/modx/'+module+'/'+id+'/'
# Grab the XML corresponding to the request from course.xml
xml = content_parser.module_xml(request.user, module, 'id', id)
# Create the module
system = I4xSystem(track_function = make_track_function(request),
render_function = None,
ajax_url = ajax_url,
filestore = None
)
instance=courseware.modules.get_module_class(module)(system,
xml,
id,
state=oldstate)
# Let the module handle the AJAX
post_data=""
if request.raw_post_data:
post_data = json.loads(request.raw_post_data)
ajax_return=instance.handle_ajax(dispatch, post_data)
# Save the state back to the database
s.state=instance.get_state()
if instance.get_score():
s.grade=instance.get_score()['score']
if s.grade != oldgrade or s.state != oldstate:
s.save()
# Return whatever the module wanted to return to the client/caller
return HttpResponse(ajax_return)
def grade_histogram(module_id): def grade_histogram(module_id):
''' Print out a histogram of grades on a given problem. ''' Print out a histogram of grades on a given problem.
Part of staff member debug info. Part of staff member debug info.
''' '''
from django.db import connection, transaction from django.db import connection
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("select courseware_studentmodule.grade,COUNT(courseware_studentmodule.student_id) from courseware_studentmodule where courseware_studentmodule.module_id=%s group by courseware_studentmodule.grade", [module_id]) cursor.execute("select courseware_studentmodule.grade,COUNT(courseware_studentmodule.student_id) from courseware_studentmodule where courseware_studentmodule.module_id=%s group by courseware_studentmodule.grade", [module_id])
...@@ -145,7 +83,7 @@ def render_x_module(user, request, xml_module, module_object_preload): ...@@ -145,7 +83,7 @@ def render_x_module(user, request, xml_module, module_object_preload):
state = smod.state state = smod.state
# Create a new instance # Create a new instance
ajax_url = '/modx/'+module_type+'/'+module_id+'/' ajax_url = settings.MITX_ROOT_URL + '/modx/'+module_type+'/'+module_id+'/'
system = I4xSystem(track_function = make_track_function(request), system = I4xSystem(track_function = make_track_function(request),
render_function = lambda x: render_module(user, request, x, module_object_preload), render_function = lambda x: render_module(user, request, x, module_object_preload),
ajax_url = ajax_url, ajax_url = ajax_url,
...@@ -156,8 +94,9 @@ def render_x_module(user, request, xml_module, module_object_preload): ...@@ -156,8 +94,9 @@ def render_x_module(user, request, xml_module, module_object_preload):
module_id, module_id,
state=state) state=state)
# If instance wasn't already in the database, create it # If instance wasn't already in the database, and this
if not smod: # isn't a guest user, create it
if not smod and user.is_authenticated():
smod=StudentModule(student=user, smod=StudentModule(student=user,
module_type = module_type, module_type = module_type,
module_id=module_id, module_id=module_id,
...@@ -168,6 +107,8 @@ def render_x_module(user, request, xml_module, module_object_preload): ...@@ -168,6 +107,8 @@ def render_x_module(user, request, xml_module, module_object_preload):
content = instance.get_html() content = instance.get_html()
init_js = instance.get_init_js() init_js = instance.get_init_js()
destory_js = instance.get_destroy_js() destory_js = instance.get_destroy_js()
# special extra information about each problem, only for users who are staff
if user.is_staff: if user.is_staff:
histogram = grade_histogram(module_id) histogram = grade_histogram(module_id)
render_histogram = len(histogram) > 0 render_histogram = len(histogram) > 0
......
...@@ -93,6 +93,10 @@ class Module(XModule): ...@@ -93,6 +93,10 @@ class Module(XModule):
check_button = False check_button = False
save_button = False save_button = False
# Only show the reset button if pressing it will show different values
if self.rerandomize != 'always':
reset_button = False
# User hasn't submitted an answer yet -- we don't want resets # User hasn't submitted an answer yet -- we don't want resets
if not self.lcp.done: if not self.lcp.done:
reset_button = False reset_button = False
...@@ -237,7 +241,8 @@ class Module(XModule): ...@@ -237,7 +241,8 @@ class Module(XModule):
return True return True
if self.show_answer == 'closed' and not self.closed(): if self.show_answer == 'closed' and not self.closed():
return False return False
print "aa", self.show_answer if self.show_answer == 'always':
return True
raise self.system.exception404 #TODO: Not 404 raise self.system.exception404 #TODO: Not 404
def get_answer(self, get): def get_answer(self, get):
...@@ -297,21 +302,19 @@ class Module(XModule): ...@@ -297,21 +302,19 @@ class Module(XModule):
self.attempts = self.attempts + 1 self.attempts = self.attempts + 1
self.lcp.done=True self.lcp.done=True
success = 'correct' success = 'correct'
for i in correct_map: for i in correct_map:
if correct_map[i]!='correct': if correct_map[i]!='correct':
success = 'incorrect' success = 'incorrect'
js=json.dumps({'correct_map' : correct_map,
'success' : success})
event_info['correct_map']=correct_map event_info['correct_map']=correct_map
event_info['success']=success event_info['success']=success
self.tracker('save_problem_check', event_info) self.tracker('save_problem_check', event_info)
return js return json.dumps({'success': success,
'contents': self.get_problem_html(encapsulate=False)})
def save_problem(self, get): def save_problem(self, get):
event_info = dict() event_info = dict()
...@@ -368,9 +371,7 @@ class Module(XModule): ...@@ -368,9 +371,7 @@ class Module(XModule):
self.lcp.context=dict() self.lcp.context=dict()
self.lcp.questions=dict() # Detailed info about questions in problem instance. TODO: Should be by id and not lid. self.lcp.questions=dict() # Detailed info about questions in problem instance. TODO: Should be by id and not lid.
self.lcp.seed=None self.lcp.seed=None
self.lcp=LoncapaProblem(self.filestore.open(self.filename), self.item_id, self.lcp.get_state())
filename="problems/"+self.filename+".xml"
self.lcp=LoncapaProblem(self.filestore.open(filename), self.item_id, self.lcp.get_state())
event_info['new_state']=self.lcp.get_state() event_info['new_state']=self.lcp.get_state()
self.tracker('reset_problem', event_info) self.tracker('reset_problem', event_info)
......
import json
import logging import logging
import os
import random
import sys
import StringIO
import urllib import urllib
import uuid
from django.conf import settings from django.conf import settings
from django.core.context_processors import csrf from django.core.context_processors import csrf
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.http import HttpResponse, Http404 from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponse
from django.shortcuts import redirect from django.shortcuts import redirect
from django.template import Context, loader
from mitxmako.shortcuts import render_to_response, render_to_string from mitxmako.shortcuts import render_to_response, render_to_string
#from django.views.decorators.csrf import ensure_csrf_cookie #from django.views.decorators.csrf import ensure_csrf_cookie
from django.db import connection
from django.views.decorators.cache import cache_control from django.views.decorators.cache import cache_control
from lxml import etree from lxml import etree
from module_render import render_module, modx_dispatch from module_render import render_module, make_track_function, I4xSystem
from models import StudentModule from models import StudentModule
from student.models import UserProfile from student.models import UserProfile
import courseware.content_parser as content_parser import courseware.content_parser as content_parser
import courseware.modules.capa_module import courseware.modules
import courseware.grades as grades import courseware.grades as grades
...@@ -50,12 +43,11 @@ def gradebook(request): ...@@ -50,12 +43,11 @@ def gradebook(request):
return render_to_response('gradebook.html',{'students':student_info}) return render_to_response('gradebook.html',{'students':student_info})
@login_required
@cache_control(no_cache=True, no_store=True, must_revalidate=True) @cache_control(no_cache=True, no_store=True, must_revalidate=True)
def profile(request, student_id = None): def profile(request, student_id = None):
''' User profile. Show username, location, etc, as well as grades . ''' User profile. Show username, location, etc, as well as grades .
We need to allow the user to change some of these settings .''' We need to allow the user to change some of these settings .'''
if not request.user.is_authenticated():
return redirect('/')
if student_id == None: if student_id == None:
student = request.user student = request.user
...@@ -103,7 +95,7 @@ def render_section(request, section): ...@@ -103,7 +95,7 @@ def render_section(request, section):
''' TODO: Consolidate with index ''' TODO: Consolidate with index
''' '''
user = request.user user = request.user
if not settings.COURSEWARE_ENABLED or not user.is_authenticated(): if not settings.COURSEWARE_ENABLED:
return redirect('/') return redirect('/')
# try: # try:
...@@ -115,8 +107,11 @@ def render_section(request, section): ...@@ -115,8 +107,11 @@ def render_section(request, section):
module_ids = dom.xpath("//@id") module_ids = dom.xpath("//@id")
module_object_preload = list(StudentModule.objects.filter(student=user, if user.is_authenticated():
module_id__in=module_ids)) module_object_preload = list(StudentModule.objects.filter(student=user,
module_id__in=module_ids))
else:
module_object_preload = []
module=render_module(user, request, dom, module_object_preload) module=render_module(user, request, dom, module_object_preload)
...@@ -137,7 +132,7 @@ def index(request, course="6.002 Spring 2012", chapter="Using the System", secti ...@@ -137,7 +132,7 @@ def index(request, course="6.002 Spring 2012", chapter="Using the System", secti
''' Displays courseware accordion, and any associated content. ''' Displays courseware accordion, and any associated content.
''' '''
user = request.user user = request.user
if not settings.COURSEWARE_ENABLED or not user.is_authenticated(): if not settings.COURSEWARE_ENABLED:
return redirect('/') return redirect('/')
# Fixes URLs -- we don't get funny encoding characters from spaces # Fixes URLs -- we don't get funny encoding characters from spaces
...@@ -169,8 +164,11 @@ def index(request, course="6.002 Spring 2012", chapter="Using the System", secti ...@@ -169,8 +164,11 @@ def index(request, course="6.002 Spring 2012", chapter="Using the System", secti
module_ids = dom.xpath("//course[@name=$course]/chapter[@name=$chapter]//section[@name=$section]//@id", module_ids = dom.xpath("//course[@name=$course]/chapter[@name=$chapter]//section[@name=$section]//@id",
course=course, chapter=chapter, section=section) course=course, chapter=chapter, section=section)
module_object_preload = list(StudentModule.objects.filter(student=user, if user.is_authenticated():
module_id__in=module_ids)) module_object_preload = list(StudentModule.objects.filter(student=user,
module_id__in=module_ids))
else:
module_object_preload = []
module=render_module(user, request, module, module_object_preload) module=render_module(user, request, module, module_object_preload)
...@@ -185,3 +183,49 @@ def index(request, course="6.002 Spring 2012", chapter="Using the System", secti ...@@ -185,3 +183,49 @@ def index(request, course="6.002 Spring 2012", chapter="Using the System", secti
result = render_to_response('courseware.html', context) result = render_to_response('courseware.html', context)
return result return result
def modx_dispatch(request, module=None, dispatch=None, id=None):
''' Generic view for extensions. '''
if not request.user.is_authenticated():
return redirect('/')
# Grab the student information for the module from the database
s = StudentModule.objects.filter(student=request.user,
module_id=id)
#s = StudentModule.get_with_caching(request.user, id)
if len(s) == 0 or s is None:
log.debug("Couldnt find module for user and id " + str(module) + " " + str(request.user) + " "+ str(id))
raise Http404
s = s[0]
oldgrade = s.grade
oldstate = s.state
dispatch=dispatch.split('?')[0]
ajax_url = settings.MITX_ROOT_URL + '/modx/'+module+'/'+id+'/'
# Grab the XML corresponding to the request from course.xml
xml = content_parser.module_xml(request.user, module, 'id', id)
# Create the module
system = I4xSystem(track_function = make_track_function(request),
render_function = None,
ajax_url = ajax_url,
filestore = None
)
instance=courseware.modules.get_module_class(module)(system,
xml,
id,
state=oldstate)
# Let the module handle the AJAX
ajax_return=instance.handle_ajax(dispatch, request.POST)
# Save the state back to the database
s.state=instance.get_state()
if instance.get_score():
s.grade=instance.get_score()['score']
if s.grade != oldgrade or s.state != oldstate:
s.save()
# Return whatever the module wanted to return to the client/caller
return HttpResponse(ajax_return)
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import types from django.conf import settings as settings
from django.conf import settings
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
from django.core.context_processors import csrf from django.core.context_processors import csrf
from django.core.urlresolvers import get_callable
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from django.db.models import Q from django.db.models import Q
from django.http import Http404, HttpResponse, HttpResponseRedirect, HttpResponseServerError, HttpResponseForbidden, HttpResponseNotAllowed from django.http import HttpResponse, HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.template import Context
from django.template import RequestContext, Context, loader
from django.utils import simplejson from django.utils import simplejson
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from mitxmako.shortcuts import render_to_response, render_to_string from mitxmako.shortcuts import render_to_response
from mako.lookup import TemplateLookup
from mako.template import Template
import mitxmako.middleware
from models import * # TODO: Clean up from models import Revision, Article, CreateArticleForm, RevisionFormWithTitle, RevisionForm
from settings import * import wiki_settings
def view(request, wiki_url): def view(request, wiki_url):
if not request.user.is_authenticated():
return redirect('/')
(article, path, err) = fetch_from_url(request, wiki_url) (article, path, err) = fetch_from_url(request, wiki_url)
if err: if err:
return err return err
...@@ -45,9 +31,6 @@ def view(request, wiki_url): ...@@ -45,9 +31,6 @@ def view(request, wiki_url):
return render_to_response('simplewiki_view.html', d) return render_to_response('simplewiki_view.html', d)
def view_revision(request, revision_number, wiki_url, revision=None): def view_revision(request, revision_number, wiki_url, revision=None):
if not request.user.is_authenticated():
return redirect('/')
(article, path, err) = fetch_from_url(request, wiki_url) (article, path, err) = fetch_from_url(request, wiki_url)
if err: if err:
return err return err
...@@ -76,8 +59,6 @@ def view_revision(request, revision_number, wiki_url, revision=None): ...@@ -76,8 +59,6 @@ def view_revision(request, revision_number, wiki_url, revision=None):
def root_redirect(request): def root_redirect(request):
if not request.user.is_authenticated():
return redirect('/')
try: try:
root = Article.get_root() root = Article.get_root()
except: except:
...@@ -87,8 +68,6 @@ def root_redirect(request): ...@@ -87,8 +68,6 @@ def root_redirect(request):
return HttpResponseRedirect(reverse('wiki_view', args=(root.get_url()))) return HttpResponseRedirect(reverse('wiki_view', args=(root.get_url())))
def create(request, wiki_url): def create(request, wiki_url):
if not request.user.is_authenticated():
return redirect('/')
url_path = get_url_path(wiki_url) url_path = get_url_path(wiki_url)
...@@ -161,9 +140,6 @@ def create(request, wiki_url): ...@@ -161,9 +140,6 @@ def create(request, wiki_url):
return render_to_response('simplewiki_edit.html', d) return render_to_response('simplewiki_edit.html', d)
def edit(request, wiki_url): def edit(request, wiki_url):
if not request.user.is_authenticated():
return redirect('/')
(article, path, err) = fetch_from_url(request, wiki_url) (article, path, err) = fetch_from_url(request, wiki_url)
if err: if err:
return err return err
...@@ -173,7 +149,7 @@ def edit(request, wiki_url): ...@@ -173,7 +149,7 @@ def edit(request, wiki_url):
if perm_err: if perm_err:
return perm_err return perm_err
if WIKI_ALLOW_TITLE_EDIT: if wiki_settings.WIKI_ALLOW_TITLE_EDIT:
EditForm = RevisionFormWithTitle EditForm = RevisionFormWithTitle
else: else:
EditForm = RevisionForm EditForm = RevisionForm
...@@ -195,7 +171,7 @@ def edit(request, wiki_url): ...@@ -195,7 +171,7 @@ def edit(request, wiki_url):
if not request.user.is_anonymous(): if not request.user.is_anonymous():
new_revision.revision_user = request.user new_revision.revision_user = request.user
new_revision.save() new_revision.save()
if WIKI_ALLOW_TITLE_EDIT: if wiki_settings.WIKI_ALLOW_TITLE_EDIT:
new_revision.article.title = f.cleaned_data['title'] new_revision.article.title = f.cleaned_data['title']
new_revision.article.save() new_revision.article.save()
return HttpResponseRedirect(reverse('wiki_view', args=(article.get_url(),))) return HttpResponseRedirect(reverse('wiki_view', args=(article.get_url(),)))
...@@ -215,9 +191,6 @@ def edit(request, wiki_url): ...@@ -215,9 +191,6 @@ def edit(request, wiki_url):
return render_to_response('simplewiki_edit.html', d) return render_to_response('simplewiki_edit.html', d)
def history(request, wiki_url, page=1): def history(request, wiki_url, page=1):
if not request.user.is_authenticated():
return redirect('/')
(article, path, err) = fetch_from_url(request, wiki_url) (article, path, err) = fetch_from_url(request, wiki_url)
if err: if err:
return err return err
...@@ -302,9 +275,6 @@ def history(request, wiki_url, page=1): ...@@ -302,9 +275,6 @@ def history(request, wiki_url, page=1):
def revision_feed(request, page=1): def revision_feed(request, page=1):
if not request.user.is_superuser:
return redirect('/')
page_size = 10 page_size = 10
try: try:
...@@ -332,8 +302,6 @@ def revision_feed(request, page=1): ...@@ -332,8 +302,6 @@ def revision_feed(request, page=1):
return render_to_response('simplewiki_revision_feed.html', d) return render_to_response('simplewiki_revision_feed.html', d)
def search_articles(request): def search_articles(request):
if not request.user.is_authenticated():
return redirect('/')
# blampe: We should check for the presence of other popular django search # blampe: We should check for the presence of other popular django search
# apps and use those if possible. Only fall back on this as a last resort. # apps and use those if possible. Only fall back on this as a last resort.
# Adding some context to results (eg where matches were) would also be nice. # Adding some context to results (eg where matches were) would also be nice.
...@@ -380,9 +348,6 @@ def search_articles(request): ...@@ -380,9 +348,6 @@ def search_articles(request):
def search_add_related(request, wiki_url): def search_add_related(request, wiki_url):
if not request.user.is_authenticated():
return redirect('/')
(article, path, err) = fetch_from_url(request, wiki_url) (article, path, err) = fetch_from_url(request, wiki_url)
if err: if err:
return err return err
...@@ -435,9 +400,6 @@ def add_related(request, wiki_url): ...@@ -435,9 +400,6 @@ def add_related(request, wiki_url):
return HttpResponseRedirect(reverse('wiki_view', args=(article.get_url(),))) return HttpResponseRedirect(reverse('wiki_view', args=(article.get_url(),)))
def remove_related(request, wiki_url, related_id): def remove_related(request, wiki_url, related_id):
if not request.user.is_authenticated():
return redirect('/')
(article, path, err) = fetch_from_url(request, wiki_url) (article, path, err) = fetch_from_url(request, wiki_url)
if err: if err:
return err return err
...@@ -457,8 +419,6 @@ def remove_related(request, wiki_url, related_id): ...@@ -457,8 +419,6 @@ def remove_related(request, wiki_url, related_id):
return HttpResponseRedirect(reverse('wiki_view', args=(article.get_url(),))) return HttpResponseRedirect(reverse('wiki_view', args=(article.get_url(),)))
def random_article(request): def random_article(request):
if not request.user.is_authenticated():
return redirect('/')
from random import randint from random import randint
num_arts = Article.objects.count() num_arts = Article.objects.count()
article = Article.objects.all()[randint(0, num_arts-1)] article = Article.objects.all()[randint(0, num_arts-1)]
...@@ -470,8 +430,6 @@ def encode_err(request, url): ...@@ -470,8 +430,6 @@ def encode_err(request, url):
return render_to_response('simplewiki_error.html', d) return render_to_response('simplewiki_error.html', d)
def not_found(request, wiki_url): def not_found(request, wiki_url):
if not request.user.is_authenticated():
return redirect('/')
"""Generate a NOT FOUND message for some URL""" """Generate a NOT FOUND message for some URL"""
d = {'wiki_err_notfound': True, d = {'wiki_err_notfound': True,
'wiki_url': wiki_url} 'wiki_url': wiki_url}
...@@ -543,17 +501,22 @@ def check_permissions(request, article, check_read=False, check_write=False, che ...@@ -543,17 +501,22 @@ def check_permissions(request, article, check_read=False, check_write=False, che
# LOGIN PROTECTION # # LOGIN PROTECTION #
#################### ####################
if WIKI_REQUIRE_LOGIN_VIEW: if wiki_settings.WIKI_REQUIRE_LOGIN_VIEW:
view = login_required(view) view = login_required(view)
history = login_required(history) history = login_required(history)
# search_related = login_required(search_related) search_articles = login_required(search_articles)
# wiki_encode_err = login_required(wiki_encode_err) root_redirect = login_required(root_redirect)
revision_feed = login_required(revision_feed)
if WIKI_REQUIRE_LOGIN_EDIT: random_article = login_required(random_article)
search_add_related = login_required(search_add_related)
not_found = login_required(not_found)
view_revision = login_required(view_revision)
if wiki_settings.WIKI_REQUIRE_LOGIN_EDIT:
create = login_required(create) create = login_required(create)
edit = login_required(edit) edit = login_required(edit)
add_related = login_required(add_related) add_related = login_required(add_related)
remove_related = login_required(remove_related) remove_related = login_required(remove_related)
if WIKI_CONTEXT_PREPROCESSORS: if wiki_settings.WIKI_CONTEXT_PREPROCESSORS:
settings.TEMPLATE_CONTEXT_PROCESSORS = settings.TEMPLATE_CONTEXT_PROCESSORS + WIKI_CONTEXT_PREPROCESSORS settings.TEMPLATE_CONTEXT_PROCESSORS += wiki_settings.WIKI_CONTEXT_PREPROCESSORS
# Create your views here. from django.contrib.auth.decorators import login_required
import os from mitxmako.shortcuts import render_to_response
from django.conf import settings
from django.http import Http404
from django.shortcuts import redirect
from mitxmako.shortcuts import render_to_response, render_to_string
@login_required
def index(request, page=0): def index(request, page=0):
if not request.user.is_authenticated():
return redirect('/')
return render_to_response('staticbook.html',{'page':int(page)}) return render_to_response('staticbook.html',{'page':int(page)})
def index_shifted(request, page): def index_shifted(request, page):
......
...@@ -10,6 +10,7 @@ from django.conf import settings ...@@ -10,6 +10,7 @@ from django.conf import settings
from django.contrib.auth import logout, authenticate, login from django.contrib.auth import logout, authenticate, login
from django.contrib.auth.forms import PasswordResetForm from django.contrib.auth.forms import PasswordResetForm
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.core.context_processors import csrf from django.core.context_processors import csrf
from django.core.mail import send_mail from django.core.mail import send_mail
from django.core.validators import validate_email, validate_slug, ValidationError from django.core.validators import validate_email, validate_slug, ValidationError
...@@ -17,7 +18,6 @@ from django.db import IntegrityError ...@@ -17,7 +18,6 @@ from django.db import IntegrityError
from django.http import HttpResponse, Http404 from django.http import HttpResponse, Http404
from django.shortcuts import redirect from django.shortcuts import redirect
from mitxmako.shortcuts import render_to_response, render_to_string from mitxmako.shortcuts import render_to_response, render_to_string
from mako import exceptions
from django_future.csrf import ensure_csrf_cookie from django_future.csrf import ensure_csrf_cookie
...@@ -93,12 +93,11 @@ def logout_user(request): ...@@ -93,12 +93,11 @@ def logout_user(request):
logout(request) logout(request)
return redirect('/') return redirect('/')
@login_required
@ensure_csrf_cookie @ensure_csrf_cookie
def change_setting(request): def change_setting(request):
''' JSON call to change a profile setting: Right now, location and language ''' JSON call to change a profile setting: Right now, location and language
''' '''
if not request.user.is_authenticated():
return redirect('/')
up = UserProfile.objects.get(user=request.user) #request.user.profile_cache up = UserProfile.objects.get(user=request.user) #request.user.profile_cache
if 'location' in request.POST: if 'location' in request.POST:
up.location=request.POST['location'] up.location=request.POST['location']
......
...@@ -179,8 +179,8 @@ CELERY_ALWAYS_EAGER = True ...@@ -179,8 +179,8 @@ CELERY_ALWAYS_EAGER = True
djcelery.setup_loader() djcelery.setup_loader()
################################# SIMPLEWIKI ################################### ################################# SIMPLEWIKI ###################################
WIKI_REQUIRE_LOGIN_EDIT = True SIMPLE_WIKI_REQUIRE_LOGIN_EDIT = True
WIKI_REQUIRE_LOGIN_VIEW = True SIMPLE_WIKI_REQUIRE_LOGIN_VIEW = False
################################# Middleware ################################### ################################# Middleware ###################################
# List of finder classes that know how to find static files in # List of finder classes that know how to find static files in
......
...@@ -27,6 +27,7 @@ def render_to_string(template_name, dictionary, context=None, namespace='main'): ...@@ -27,6 +27,7 @@ def render_to_string(template_name, dictionary, context=None, namespace='main'):
# collapse context_instance to a single dictionary for mako # collapse context_instance to a single dictionary for mako
context_dictionary = {} context_dictionary = {}
context_instance['settings'] = settings context_instance['settings'] = settings
context_instance['MITX_ROOT_URL'] = settings.MITX_ROOT_URL
for d in mitxmako.middleware.requestcontext: for d in mitxmako.middleware.requestcontext:
context_dictionary.update(d) context_dictionary.update(d)
for d in context_instance: for d in context_instance:
......
...@@ -60,7 +60,4 @@ def send_feedback(request): ...@@ -60,7 +60,4 @@ def send_feedback(request):
def info(request): def info(request):
''' Info page (link from main header) ''' ''' Info page (link from main header) '''
if not request.user.is_authenticated():
return redirect('/')
return render_to_response("info.html", {}) return render_to_response("info.html", {})
...@@ -57,6 +57,10 @@ task :package do ...@@ -57,6 +57,10 @@ task :package do
args = ["fakeroot", "fpm", "-s", "dir", "-t", "deb", args = ["fakeroot", "fpm", "-s", "dir", "-t", "deb",
"--after-install=#{postinstall.path}", "--after-install=#{postinstall.path}",
"--prefix=#{INSTALL_DIR_PATH}", "--prefix=#{INSTALL_DIR_PATH}",
"--exclude=build",
"--exclude=rakefile",
"--exclude=.git",
"--exclude=**/*.pyc",
"-C", "#{REPO_ROOT}", "-C", "#{REPO_ROOT}",
"--provides=#{PACKAGE_NAME}", "--provides=#{PACKAGE_NAME}",
"--name=#{NORMALIZED_DEPLOY_NAME}", "--name=#{NORMALIZED_DEPLOY_NAME}",
......
...@@ -5,6 +5,14 @@ import tempfile ...@@ -5,6 +5,14 @@ import tempfile
import djcelery import djcelery
MITX_ROOT_URL = ''
COURSE_NAME = "6.002_Spring_2012"
COURSE_NUMBER = "6.002x"
COURSE_TITLE = "Circuits and Electronics"
ROOT_URLCONF = 'urls'
# from settings2.askbotsettings import LIVESETTINGS_OPTIONS # from settings2.askbotsettings import LIVESETTINGS_OPTIONS
DEFAULT_GROUPS = [] DEFAULT_GROUPS = []
...@@ -38,8 +46,8 @@ DEFAULT_FEEDBACK_EMAIL = 'feedback@mitx.mit.edu' ...@@ -38,8 +46,8 @@ DEFAULT_FEEDBACK_EMAIL = 'feedback@mitx.mit.edu'
GENERATE_RANDOM_USER_CREDENTIALS = False GENERATE_RANDOM_USER_CREDENTIALS = False
WIKI_REQUIRE_LOGIN_EDIT = True SIMPLE_WIKI_REQUIRE_LOGIN_EDIT = True
WIKI_REQUIRE_LOGIN_VIEW = True SIMPLE_WIKI_REQUIRE_LOGIN_VIEW = False
PERFSTATS = False PERFSTATS = False
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
<section> <section>
<h1>Circuits &amp; Electronics</h1> <h1>Circuits &amp; Electronics</h1>
<h2>6.002x</h2> <h2>6.002x</h2>
<a class="enroll" rel="leanModal" href="#enroll"><noscript>In order to</noscript> Enroll in 6.002x Circuits <span>&amp;</span> Electronics <noscript>you need to have javascript enabled</noscript></a> <a class="enroll" rel="leanModal" href="/info">View 6.002x Circuits <span>&amp;</span> Electronics as a guest</a>
</section> </section>
<p>6.002x (Circuits and Electronics) is an experimental on-line adaptation of MIT&rsquo;s first undergraduate analog design course: 6.002. This course is running, free of charge, for students worldwide from March 5, 2012 through June 8, 2012.</p> <p>6.002x (Circuits and Electronics) is an experimental on-line adaptation of MIT&rsquo;s first undergraduate analog design course: 6.002. This course is running, free of charge, for students worldwide from March 5, 2012 through June 8, 2012.</p>
</section> </section>
...@@ -51,7 +51,7 @@ ...@@ -51,7 +51,7 @@
</section> </section>
<section class="cta"> <section class="cta">
<a class="enroll" rel="leanModal" href="#enroll"><noscript>In order to</noscript> Enroll in 6.002x Circuits &amp; Electronics <noscript>you need to have javascript enabled</noscript></a> <a class="enroll" rel="leanModal" href="/info">View 6.002x Circuits &amp; Electronics as a guest</a>
</section> </section>
</section> </section>
......
...@@ -23,11 +23,20 @@ $(document).ready(function(){ ...@@ -23,11 +23,20 @@ $(document).ready(function(){
<section class="main-content"> <section class="main-content">
<div class="info-wrapper"> <div class="info-wrapper">
% if user.is_authenticated():
<section class="updates"> <section class="updates">
<%include file="updates.html" /> <%include file="updates.html" />
</section> </section>
<section class="handouts"> <section class="handouts">
<%include file="handouts.html" /> <%include file="handouts.html" />
</section> </section>
% else:
<section class="updates">
<%include file="guest_updates.html" />
</section>
<section class="handouts">
<%include file="guest_handouts.html" />
</section>
% endif
</div> </div>
</section> </section>
...@@ -86,7 +86,9 @@ ...@@ -86,7 +86,9 @@
</div> </div>
</li> </li>
<li><a href="/s/help.html">Help</a></li> <li><a href="/s/help.html">Help</a></li>
<li><a href="/logout">Log out</a></li> % if user.is_authenticated():
<li><a href="${ settings.MITX_ROOT_URL }/logout">Log out</a></li>
% endif
</ul> </ul>
</nav> </nav>
</footer> </footer>
......
...@@ -3,17 +3,21 @@ ...@@ -3,17 +3,21 @@
<header> <header>
<hgroup> <hgroup>
<h1><em>MITx</em></h1> <h1><em>MITx</em></h1>
<h2><a href="/courseware">Circuits and Electronics</a></h2> <h2><a href="${ MITX_ROOT_URL }/courseware/">${ settings.COURSE_TITLE }</a></h2>
</hgroup> </hgroup>
<nav class="${active_page}"> <nav class="${active_page}">
<ul class="coursenav"> <ul class="coursenav">
<li class="courseware"><a href="/courseware">Courseware</a></li> <li class="courseware"><a href="${ MITX_ROOT_URL }/courseware/">Courseware</a></li>
<li class="info"><a href="/info">Course Info</a></li> <li class="info"><a href="${ MITX_ROOT_URL }/info">Course Info</a></li>
<li class="book"><a href="/book">Textbook</a></li> % if user.is_authenticated():
<li class="discussion"><a href="/discussion/questions">Discussion</a></li> <li class="book"><a href="${ MITX_ROOT_URL }/book">Textbook</a></li>
<li class="wiki"><a href="/wiki/view">Wiki</a></li> <li class="discussion"><a href="${ MITX_ROOT_URL }/discussion/questions/">Discussion</a></li>
<li class="profile"><a href="/profile">Profile</a></li> % endif
<li class="wiki"><a href="${ MITX_ROOT_URL }/wiki/view/">Wiki</a></li>
% if user.is_authenticated():
<li class="profile"><a href="${ MITX_ROOT_URL }/profile">Profile</a></li>
% endif
</ul> </ul>
</nav> </nav>
</header> </header>
......
function ${ id }_load() { function ${ id }_content_updated() {
$('#main_${ id }').load('${ ajax_url }problem_get?id=${ id }',
function() {
MathJax.Hub.Queue(["Typeset",MathJax.Hub]); MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
update_schematics(); update_schematics();
$('#check_${ id }').click(function() { $('#check_${ id }').unbind('click').click(function() {
$("input.schematic").each(function(index,element){ element.schematic.update_value(); }); $("input.schematic").each(function(index,element){ element.schematic.update_value(); });
var submit_data={}; var submit_data={};
$.each($("[id^=input_${ id }_]"), function(index,value){ $.each($("[id^=input_${ id }_]"), function(index,value){
...@@ -25,36 +23,37 @@ function ${ id }_load() { ...@@ -25,36 +23,37 @@ function ${ id }_load() {
submit_data[value.id]=value.value; submit_data[value.id]=value.value;
} }
}); });
postJSON('/modx/problem/${ id }/problem_check', postJSON('${ MITX_ROOT_URL }/modx/problem/${ id }/problem_check',
submit_data, submit_data,
function(json) { function(json) {
switch(json.success) { switch(json.success) {
case 'incorrect': // Worked, but answer not case 'incorrect': // Worked, but answer not
case 'correct': case 'correct':
${ id }_load(); $('#main_${ id }').html(json.contents);
//alert("!!"+json.success); ${ id }_content_updated();
break; break;
default: default:
alert(json.success); alert(json.success);
} }}
}); );
log_event('problem_check', submit_data); log_event('problem_check', submit_data);
}); });
$('#reset_${ id }').click(function() { $('#reset_${ id }').unbind('click').click(function() {
var submit_data={}; var submit_data={};
$.each($("[id^=input_${ id }_]"), function(index,value){ $.each($("[id^=input_${ id }_]"), function(index,value){
submit_data[value.id]=value.value; submit_data[value.id]=value.value;
}); });
postJSON('/modx/problem/${ id }/problem_reset', {'id':'${ id }'}, function(json) { postJSON('${ MITX_ROOT_URL }/modx/problem/${ id }/problem_reset', {'id':'${ id }'}, function(html_as_json) {
${ id }_load(); $('#main_${ id }').html(html_as_json);
${ id }_content_updated();
}); });
log_event('problem_reset', submit_data); log_event('problem_reset', submit_data);
}); });
$('#show_${ id }').click(function() { $('#show_${ id }').unbind('click').click(function() {
postJSON('/modx/problem/${ id }/problem_show', {}, function(data) { postJSON('${ MITX_ROOT_URL }/modx/problem/${ id }/problem_show', {}, function(data) {
for (var key in data) { for (var key in data) {
if ($.isArray(data[key])){ if ($.isArray(data[key])){
for (var ans_index in data[key]){ for (var ans_index in data[key]){
...@@ -66,24 +65,28 @@ function ${ id }_load() { ...@@ -66,24 +65,28 @@ function ${ id }_load() {
} }
}); });
log_event('problem_show', {'problem':'${ id }'}); log_event('problem_show', {'problem':'${ id }'});
}); });
$('#save_${ id }').click(function() { $('#save_${ id }').unbind('click').click(function() {
$("input.schematic").each(function(index,element){ element.schematic.update_value(); }); $("input.schematic").each(function(index,element){ element.schematic.update_value(); });
var submit_data={}; var submit_data={};
$.each($("[id^=input_${ id }_]"), function(index,value){ $.each($("[id^=input_${ id }_]"), function(index,value) {
submit_data[value.id]=value.value;}); submit_data[value.id]=value.value;
postJSON('/modx/problem/${ id }/problem_save', });
submit_data, function(data){ postJSON('${ MITX_ROOT_URL }/modx/problem/${ id }/problem_save',
if(data.success) { submit_data,
alert('Saved'); function(data) {
}} if(data.success) {
); alert('Saved');
}});
log_event('problem_save', submit_data); log_event('problem_save', submit_data);
}); });
} }
);}
function ${ id }_load() {
$('#main_${ id }').load('${ ajax_url }problem_get?id=${ id }', ${ id }_content_updated);
}
$(function() { $(function() {
${ id }_load(); ${ id }_load();
......
...@@ -53,7 +53,7 @@ function disablePrev() { ...@@ -53,7 +53,7 @@ function disablePrev() {
function ${ id }goto(i) { function ${ id }goto(i) {
log_event("seq_goto", {'old':${id}loc, 'new':i,'id':'${id}'}); log_event("seq_goto", {'old':${id}loc, 'new':i,'id':'${id}'});
postJSON('/modx/sequential/${ id }/goto_position', postJSON('${ MITX_ROOT_URL }/modx/sequential/${ id }/goto_position',
{'position' : i }); {'position' : i });
if (${ id }loc!=-1) if (${ id }loc!=-1)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment