Ejemplo n.º 1
0
def activate_account(request, key):
    ''' When link in activation e-mail is clicked
    '''
    r = Registration.objects.filter(activation_key=key)
    if len(r) == 1:
        user_logged_in = request.user.is_authenticated()
        already_active = True
        if not r[0].user.is_active:
            r[0].activate()
            already_active = False

        #Enroll student in any pending courses he/she may have if auto_enroll flag is set
        student = User.objects.filter(id=r[0].user_id)
        if student:
            ceas = CourseEnrollmentAllowed.objects.filter(email=student[0].email)
            for cea in ceas:
                if cea.auto_enroll:
                    course_id = cea.course_id
                    enrollment, created = CourseEnrollment.objects.get_or_create(user_id=student[0].id, course_id=course_id)

        resp = render_to_response("registration/activation_complete.html", {'user_logged_in': user_logged_in, 'already_active': already_active})
        return resp
    if len(r) == 0:
        return render_to_response("registration/activation_invalid.html", {'csrf': csrf(request)['csrf_token']})
    return HttpResponse("Unknown error. Please e-mail us to let us know how it happened.")
Ejemplo n.º 2
0
def mktg_course_about(request, course_id):

    try:
        course = get_course_with_access(request.user, course_id, 'see_exists')
    except (ValueError, Http404) as e:
        # if a course does not exist yet, display a coming
        # soon button
        return render_to_response('courseware/mktg_coming_soon.html',
                                  {'course_id': course_id})

    registered = registered_for_course(course, request.user)

    if has_access(request.user, course, 'load'):
        course_target = reverse('info', args=[course.id])
    else:
        course_target = reverse('about_course', args=[course.id])

    allow_registration = has_access(request.user, course, 'enroll')

    show_courseware_link = (has_access(request.user, course, 'load') or
                            settings.MITX_FEATURES.get('ENABLE_LMS_MIGRATION'))

    return render_to_response(
        'courseware/mktg_course_about.html', {
            'course': course,
            'registered': registered,
            'allow_registration': allow_registration,
            'course_target': course_target,
            'show_courseware_link': show_courseware_link
        })
Ejemplo n.º 3
0
def mktg_course_about(request, course_id):

    try:
        course = get_course_with_access(request.user, course_id, "see_exists")
    except (ValueError, Http404) as e:
        # if a course does not exist yet, display a coming
        # soon button
        return render_to_response("courseware/mktg_coming_soon.html", {"course_id": course_id})

    registered = registered_for_course(course, request.user)

    if has_access(request.user, course, "load"):
        course_target = reverse("info", args=[course.id])
    else:
        course_target = reverse("about_course", args=[course.id])

    allow_registration = has_access(request.user, course, "enroll")

    show_courseware_link = has_access(request.user, course, "load") or settings.MITX_FEATURES.get(
        "ENABLE_LMS_MIGRATION"
    )

    return render_to_response(
        "courseware/mktg_course_about.html",
        {
            "course": course,
            "registered": registered,
            "allow_registration": allow_registration,
            "course_target": course_target,
            "show_courseware_link": show_courseware_link,
        },
    )
Ejemplo n.º 4
0
def mktg_course_about(request, course_id):
    """
    This is the button that gets put into an iframe on the Drupal site
    """

    try:
        course = get_course_with_access(request.user, course_id, 'see_exists')
    except (ValueError, Http404) as e:
        # if a course does not exist yet, display a coming
        # soon button
        return render_to_response('courseware/mktg_coming_soon.html',
                                  {'course_id': course_id})

    registered = registered_for_course(course, request.user)

    if has_access(request.user, course, 'load'):
        course_target = reverse('info', args=[course.id])
    else:
        course_target = reverse('about_course', args=[course.id])

    allow_registration = has_access(request.user, course, 'enroll')

    show_courseware_link = (has_access(request.user, course, 'load') or
                            settings.MITX_FEATURES.get('ENABLE_LMS_MIGRATION'))
    course_modes = CourseMode.modes_for_course(course.id)

    return render_to_response('courseware/mktg_course_about.html',
                              {
                                  'course': course,
                                  'registered': registered,
                                  'allow_registration': allow_registration,
                                  'course_target': course_target,
                                  'show_courseware_link': show_courseware_link,
                                  'course_modes': course_modes,
                              })
Ejemplo n.º 5
0
def view_revision(request, revision_number, article_path, course_id=None):
    course = get_opt_course_with_access(request.user, course_id, 'load')

    (article, err) = get_article(request, article_path, course)
    if err:
        return err

    try:
        revision = Revision.objects.get(counter=int(revision_number),
                                        article=article)
    except:
        d = {'wiki_err_norevision': revision_number}
        update_template_dictionary(d, request, course, article)
        return render_to_response('simplewiki/simplewiki_error.html', d)

    perm_err = check_permissions(request,
                                 article,
                                 course,
                                 check_read=True,
                                 check_deleted=True,
                                 revision=revision)
    if perm_err:
        return perm_err

    d = {}
    update_template_dictionary(d, request, course, article, revision)

    return render_to_response('simplewiki/simplewiki_view.html', d)
Ejemplo n.º 6
0
def activate_account(request, key):
    ''' When link in activation e-mail is clicked
    '''
    r = Registration.objects.filter(activation_key=key)
    if len(r) == 1:
        user_logged_in = request.user.is_authenticated()
        already_active = True
        if not r[0].user.is_active:
            r[0].activate()
            already_active = False

        #Enroll student in any pending courses he/she may have if auto_enroll flag is set
        student = User.objects.filter(id=r[0].user_id)
        if student:
            ceas = CourseEnrollmentAllowed.objects.filter(email=student[0].email)
            for cea in ceas:
                if cea.auto_enroll:
                    course_id = cea.course_id
                    enrollment, created = CourseEnrollment.objects.get_or_create(user_id=student[0].id, course_id=course_id)

        resp = render_to_response("registration/activation_complete.html", {'user_logged_in': user_logged_in, 'already_active': already_active})
        return resp
    if len(r) == 0:
        return render_to_response("registration/activation_invalid.html", {'csrf': csrf(request)['csrf_token']})
    return HttpResponse("Unknown error. Please e-mail us to let us know how it happened.")
Ejemplo n.º 7
0
def confirm_email_change(request, key):
    ''' User requested a new e-mail. This is called when the activation
    link is clicked. We confirm with the old e-mail, and update
    '''
    try:
        try:
            pec = PendingEmailChange.objects.get(activation_key=key)
        except PendingEmailChange.DoesNotExist:
            transaction.rollback()
            return render_to_response("invalid_email_key.html", {})

        user = pec.user
        address_context = {
            'old_email': user.email,
            'new_email': pec.new_email
        }

        if len(User.objects.filter(email=pec.new_email)) != 0:
            transaction.rollback()
            return render_to_response("email_exists.html", {})

        subject = render_to_string('emails/email_change_subject.txt', address_context)
        subject = ''.join(subject.splitlines())
        message = render_to_string('emails/confirm_email_change.txt', address_context)
        up = UserProfile.objects.get(user=user)
        meta = up.get_meta()
        if 'old_emails' not in meta:
            meta['old_emails'] = []
        meta['old_emails'].append([user.email, datetime.datetime.now().isoformat()])
        up.set_meta(meta)
        up.save()
        # Send it to the old email...
        try:
            user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
        except Exception:
            transaction.rollback()
            log.warning('Unable to send confirmation email to old address', exc_info=True)
            return render_to_response("email_change_failed.html", {'email': user.email})

        user.email = pec.new_email
        user.save()
        pec.delete()
        # And send it to the new email...
        try:
            user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
        except Exception:
            transaction.rollback()
            log.warning('Unable to send confirmation email to new address', exc_info=True)
            return render_to_response("email_change_failed.html", {'email': pec.new_email})

        transaction.commit()
        return render_to_response("email_change_successful.html", address_context)
    except Exception:
        # If we get an unexpected exception, be sure to rollback the transaction
        transaction.rollback()
        raise
Ejemplo n.º 8
0
def confirm_email_change(request, key):
    ''' User requested a new e-mail. This is called when the activation
    link is clicked. We confirm with the old e-mail, and update
    '''
    try:
        try:
            pec = PendingEmailChange.objects.get(activation_key=key)
        except PendingEmailChange.DoesNotExist:
            transaction.rollback()
            return render_to_response("invalid_email_key.html", {})

        user = pec.user
        address_context = {
            'old_email': user.email,
            'new_email': pec.new_email
        }

        if len(User.objects.filter(email=pec.new_email)) != 0:
            transaction.rollback()
            return render_to_response("email_exists.html", {})

        subject = render_to_string('emails/email_change_subject.txt', address_context)
        subject = ''.join(subject.splitlines())
        message = render_to_string('emails/confirm_email_change.txt', address_context)
        up = UserProfile.objects.get(user=user)
        meta = up.get_meta()
        if 'old_emails' not in meta:
            meta['old_emails'] = []
        meta['old_emails'].append([user.email, datetime.datetime.now().isoformat()])
        up.set_meta(meta)
        up.save()
        # Send it to the old email...
        try:
            user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
        except Exception:
            transaction.rollback()
            log.warning('Unable to send confirmation email to old address', exc_info=True)
            return render_to_response("email_change_failed.html", {'email': user.email})

        user.email = pec.new_email
        user.save()
        pec.delete()
        # And send it to the new email...
        try:
            user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
        except Exception:
            transaction.rollback()
            log.warning('Unable to send confirmation email to new address', exc_info=True)
            return render_to_response("email_change_failed.html", {'email': pec.new_email})

        transaction.commit()
        return render_to_response("email_change_successful.html", address_context)
    except Exception:
        # If we get an unexpected exception, be sure to rollback the transaction
        transaction.rollback()
        raise
Ejemplo n.º 9
0
def activate_account(request, key):
    ''' When link in activation e-mail is clicked
    '''
    r = Registration.objects.filter(activation_key=key)
    if len(r) == 1:
        user_logged_in = request.user.is_authenticated()
        already_active = True
        if not r[0].user.is_active:
            r[0].activate()
            already_active = False
        resp = render_to_response("registration/activation_complete.html", {'user_logged_in': user_logged_in, 'already_active': already_active})
        return resp
    if len(r) == 0:
        return render_to_response("registration/activation_invalid.html", {'csrf': csrf(request)['csrf_token']})
    return HttpResponse("Unknown error. Please e-mail us to let us know how it happened.")
Ejemplo n.º 10
0
def manage_users(request, location):
    '''
    This view will return all CMS users who are editors for the specified course
    '''
    # check that logged in user has permissions to this item
    if not has_access(request.user, location,
                      role=INSTRUCTOR_ROLE_NAME) and not has_access(
                          request.user, location, role=STAFF_ROLE_NAME):
        raise PermissionDenied()

    course_module = modulestore().get_item(location)

    return render_to_response(
        'manage_users.html', {
            'active_tab':
            'users',
            'context_course':
            course_module,
            'staff':
            get_users_in_course_group_by_role(location, STAFF_ROLE_NAME),
            'add_user_postback_url':
            reverse('add_user', args=[location]).rstrip('/'),
            'remove_user_postback_url':
            reverse('remove_user', args=[location]).rstrip('/'),
            'allow_actions':
            has_access(request.user, location, role=INSTRUCTOR_ROLE_NAME),
            'request_user_id':
            request.user.id
        })
Ejemplo n.º 11
0
def followed_threads(request, course_id, user_id):
    nr_transaction = newrelic.agent.current_transaction()

    course = get_course_with_access(request.user, course_id, 'load_forum')
    try:
        profiled_user = cc.User(id=user_id, course_id=course_id)

        query_params = {
            'page': request.GET.get('page', 1),
            'per_page':
            THREADS_PER_PAGE,  # more than threads_per_page to show more activities
            'sort_key': request.GET.get('sort_key', 'date'),
            'sort_order': request.GET.get('sort_order', 'desc'),
        }

        threads, page, num_pages = profiled_user.subscribed_threads(
            query_params)
        query_params['page'] = page
        query_params['num_pages'] = num_pages
        user_info = cc.User.from_django_user(request.user).to_dict()

        with newrelic.agent.FunctionTrace(nr_transaction,
                                          "get_metadata_for_threads"):
            annotated_content_info = utils.get_metadata_for_threads(
                course_id, threads, request.user, user_info)
        if request.is_ajax():
            return utils.JsonResponse({
                'annotated_content_info':
                annotated_content_info,
                'discussion_data':
                map(utils.safe_content, threads),
                'page':
                query_params['page'],
                'num_pages':
                query_params['num_pages'],
            })
        else:

            context = {
                'course':
                course,
                'user':
                request.user,
                'django_user':
                User.objects.get(id=user_id),
                'profiled_user':
                profiled_user.to_dict(),
                'threads':
                saxutils.escape(json.dumps(threads), escapedict),
                'user_info':
                saxutils.escape(json.dumps(user_info), escapedict),
                'annotated_content_info':
                saxutils.escape(json.dumps(annotated_content_info),
                                escapedict),
                #                'content': content,
            }

            return render_to_response('discussion/user_profile.html', context)
    except User.DoesNotExist:
        raise Http404
Ejemplo n.º 12
0
    def _payment_page_response(self, post_params, callback_url):
        """
        Render the payment page to a response.  This is an HTML form
        that triggers a POST request to `callback_url`.

        The POST params are described in the CyberSource documentation:
        http://apps.cybersource.com/library/documentation/dev_guides/HOP_UG/html/wwhelp/wwhimpl/js/html/wwhelp.htm

        To figure out the POST params to send to the callback,
        we either:

        1) Use fake static data (e.g. always send user name "John Doe")
        2) Use the same info we received (e.g. send the same `course_id` and `amount`)
        3) Dynamically calculate signatures using a shared secret
        """

        # Build the context dict used to render the HTML form,
        # filling in values for the hidden input fields.
        # These will be sent in the POST request to the callback URL.
        context_dict = {

            # URL to send the POST request to
            "callback_url": callback_url,

            # POST params embedded in the HTML form
            'post_params': self.response_post_params(post_params)
        }

        return render_to_response('shoppingcart/test/fake_payment_page.html', context_dict)
Ejemplo n.º 13
0
def show_receipt(request, ordernum):
    """
    Displays a receipt for a particular order.
    404 if order is not yet purchased or request.user != order.user
    """
    try:
        order = Order.objects.get(id=ordernum)
    except Order.DoesNotExist:
        raise Http404('Order not found!')

    if order.user != request.user or order.status != 'purchased':
        raise Http404('Order not found!')

    order_items = OrderItem.objects.filter(order=order).select_subclasses()
    any_refunds = any(i.status == "refunded" for i in order_items)
    receipt_template = 'shoppingcart/receipt.html'
    __, instructions = order.generate_receipt_instructions()
    # we want to have the ability to override the default receipt page when
    # there is only one item in the order
    context = {
        'order': order,
        'order_items': order_items,
        'any_refunds': any_refunds,
        'instructions': instructions,
    }

    if order_items.count() == 1:
        receipt_template = order_items[0].single_item_receipt_template
        context.update(order_items[0].single_item_receipt_context)

    return render_to_response(receipt_template, context)
Ejemplo n.º 14
0
def get_course_settings(request, org, course, name):
    """
    Send models and views as well as html for editing the course settings to the client.

    org, course, name: Attributes of the Location for the item to edit
    """
    location = get_location_and_verify_access(request, org, course, name)

    course_module = modulestore().get_item(location)

    return render_to_response(
        'settings.html', {
            'context_course':
            course_module,
            'course_location':
            location,
            'details_url':
            reverse(course_settings_updates,
                    kwargs={
                        "org": org,
                        "course": course,
                        "name": name,
                        "section": "details"
                    }),
            'about_page_editable':
            not settings.MITX_FEATURES.get('ENABLE_MKTG_SITE', False)
        })
Ejemplo n.º 15
0
def revision_feed(request, page=1, namespace=None, course_id=None):
    course = get_opt_course_with_access(request.user, course_id, 'load')

    page_size = 10

    if page is None:
        page = 1
    try:
        p = int(page)
    except ValueError:
        p = 1

    history = Revision.objects.order_by('-revision_date').select_related(
        'revision_user', 'article', 'previous_revision')

    page_count = (history.count() + (page_size - 1)) / page_size
    if p > page_count:
        p = 1
    beginItem = (p - 1) * page_size

    next_page = p + 1 if page_count > p else None
    prev_page = p - 1 if p > 1 else None

    d = {'wiki_page': p,
         'wiki_next_page': next_page,
         'wiki_prev_page': prev_page,
         'wiki_history': history[beginItem:beginItem + page_size],
         'show_delete_revision': request.user.is_superuser,
         'namespace': namespace}
    update_template_dictionary(d, request, course)

    return render_to_response('simplewiki/simplewiki_revision_feed.html', d)
Ejemplo n.º 16
0
def hint_manager(request, course_id):
    try:
        get_course_with_access(request.user, course_id, 'staff', depth=None)
    except Http404:
        out = 'Sorry, but students are not allowed to access the hint manager!'
        return HttpResponse(out)
    if request.method == 'GET':
        out = get_hints(request, course_id, 'mod_queue')
        return render_to_response('courseware/hint_manager.html', out)
    field = request.POST['field']
    if not (field == 'mod_queue' or field == 'hints'):
        # Invalid field.  (Don't let users continue - they may overwrite other db's)
        out = 'Error in hint manager - an invalid field was accessed.'
        return HttpResponse(out)

    if request.POST['op'] == 'delete hints':
        delete_hints(request, course_id, field)
    if request.POST['op'] == 'switch fields':
        pass
    if request.POST['op'] == 'change votes':
        change_votes(request, course_id, field)
    if request.POST['op'] == 'add hint':
        add_hint(request, course_id, field)
    if request.POST['op'] == 'approve':
        approve(request, course_id, field)
    rendered_html = render_to_string('courseware/hint_manager_inner.html',
                                     get_hints(request, course_id, field))
    return HttpResponse(
        json.dumps({
            'success': True,
            'contents': rendered_html
        }))
Ejemplo n.º 17
0
def combined_notifications(request, course_id):
    """
    Gets combined notifications from the grading controller and displays them
    """
    course = get_course_with_access(request.user, course_id, 'load')
    user = request.user
    notifications = open_ended_notifications.combined_notifications(
        course, user)
    response = notifications['response']
    notification_tuples = open_ended_notifications.NOTIFICATION_TYPES

    notification_list = []
    for response_num in xrange(0, len(notification_tuples)):
        tag = notification_tuples[response_num][0]
        if tag in response:
            url_name = notification_tuples[response_num][1]
            human_name = notification_tuples[response_num][2]
            url = _reverse_without_slash(url_name, course_id)
            has_img = response[tag]

            # check to make sure we have descriptions and alert messages
            if human_name in DESCRIPTION_DICT:
                description = DESCRIPTION_DICT[human_name]
            else:
                description = ""

            if human_name in ALERT_DICT:
                alert_message = ALERT_DICT[human_name]
            else:
                alert_message = ""

            notification_item = {
                'url': url,
                'name': human_name,
                'alert': has_img,
                'description': description,
                'alert_message': alert_message
            }
            #The open ended panel will need to link the "peer grading" button in the panel to a peer grading
            #xmodule defined in the course.  This checks to see if the human name of the server notification
            #that we are currently processing is "peer grading".  If it is, it looks for a peer grading
            #module in the course.  If none exists, it removes the peer grading item from the panel.
            if human_name == "Peer Grading":
                found_module, problem_url = find_peer_grading_module(course)
                if found_module:
                    notification_list.append(notification_item)
            else:
                notification_list.append(notification_item)

    ajax_url = _reverse_with_slash('open_ended_notifications', course_id)
    combined_dict = {
        'error_text': "",
        'notification_list': notification_list,
        'course': course,
        'success': True,
        'ajax_url': ajax_url,
    }

    return render_to_response(
        'open_ended_problems/combined_notifications.html', combined_dict)
Ejemplo n.º 18
0
def index(request):
    """
    List all courses available to the logged in user
    """
    courses = modulestore("direct").get_items(["i4x", None, None, "course", None])

    # filter out courses that we don't have access too
    def course_filter(course):
        return (
            has_access(request.user, course.location)
            # TODO remove this condition when templates purged from db
            and course.location.course != "templates"
            and course.location.org != ""
            and course.location.course != ""
            and course.location.name != ""
        )

    courses = filter(course_filter, courses)

    return render_to_response(
        "index.html",
        {
            "courses": [
                (
                    course.display_name,
                    get_url_reverse("CourseOutline", course),
                    get_lms_link_for_item(course.location, course_id=course.location.course_id),
                )
                for course in courses
            ],
            "user": request.user,
            "disable_course_creation": settings.MITX_FEATURES.get("DISABLE_COURSE_CREATION", False)
            and not request.user.is_staff,
        },
    )
Ejemplo n.º 19
0
def edit_subsection(request, location):
    # check that we have permissions to edit this item
    course = get_course_for_item(location)
    if not has_access(request.user, course.location):
        raise PermissionDenied()

    item = modulestore().get_item(location, depth=1)

    lms_link = get_lms_link_for_item(
        location, course_id=course.location.course_id)
    preview_link = get_lms_link_for_item(
        location, course_id=course.location.course_id, preview=True)

    # make sure that location references a 'sequential', otherwise return
    # BadRequest
    if item.location.category != 'sequential':
        return HttpResponseBadRequest()

    parent_locs = modulestore().get_parent_locations(location, None)

    # we're for now assuming a single parent
    if len(parent_locs) != 1:
        logging.error(
            'Multiple (or none) parents have been found for {0}'.format(location))

    # this should blow up if we don't find any parents, which would be
    # erroneous
    parent = modulestore().get_item(parent_locs[0])

    # remove all metadata from the generic dictionary that is presented in a
    # more normalized UI

    policy_metadata = dict(
        (field.name, field.read_from(item))
        for field
        in item.fields
        if field.name not in ['display_name', 'start', 'due', 'format'] and field.scope == Scope.settings
    )

    can_view_live = False
    subsection_units = item.get_children()
    for unit in subsection_units:
        state = compute_unit_state(unit)
        if state == UnitState.public or state == UnitState.draft:
            can_view_live = True
            break

    return render_to_response('edit_subsection.html',
                              {'subsection': item,
                               'context_course': course,
                               'create_new_unit_template': Location('i4x', 'edx', 'templates', 'vertical', 'Empty'),
                               'lms_link': lms_link,
                               'preview_link': preview_link,
                               'course_graders': json.dumps(CourseGradingModel.fetch(course.location).graders),
                               'parent_location': course.location,
                               'parent_item': parent,
                               'policy_metadata': policy_metadata,
                               'subsection_units': subsection_units,
                               'can_view_live': can_view_live
                               })
Ejemplo n.º 20
0
def instructor_dashboard_2(request, course_id):
    """ Display the instructor dashboard for a course. """

    course = get_course_by_id(course_id, depth=None)

    access = {
        "admin": request.user.is_staff,
        "instructor": has_access(request.user, course, "instructor"),
        "staff": has_access(request.user, course, "staff"),
        "forum_admin": has_forum_access(request.user, course_id, FORUM_ROLE_ADMINISTRATOR),
    }

    if not access["staff"]:
        raise Http404()

    sections = [
        _section_course_info(course_id),
        _section_membership(course_id, access),
        _section_student_admin(course_id, access),
        _section_data_download(course_id),
        _section_analytics(course_id),
    ]

    context = {
        "course": course,
        "old_dashboard_url": reverse("instructor_dashboard", kwargs={"course_id": course_id}),
        "sections": sections,
    }

    return render_to_response("instructor/instructor_dashboard_2/instructor_dashboard_2.html", context)
Ejemplo n.º 21
0
def check_permissions(request, article, course, check_read=False, check_write=False, check_locked=False, check_deleted=False, revision=None):
    read_err = check_read and not article.can_read(request.user)

    write_err = check_write and not article.can_write(request.user)

    locked_err = check_locked and article.locked

    if revision is None:
        revision = article.current_revision
    deleted_err = check_deleted and not (revision.deleted == 0)
    if (request.user.is_superuser):
        deleted_err = False
        locked_err = False

    if read_err or write_err or locked_err or deleted_err:
        d = {'wiki_article': article,
             'wiki_err_noread': read_err,
             'wiki_err_nowrite': write_err,
             'wiki_err_locked': locked_err,
             'wiki_err_deleted': deleted_err, }
        update_template_dictionary(d, request, course)
        # TODO: Make this a little less jarring by just displaying an error
        #       on the current page? (no such redirect happens for an anon upload yet)
        # benjaoming: I think this is the nicest way of displaying an error, but
        # these errors shouldn't occur, but rather be prevented on the other
        # pages.
        return render_to_response('simplewiki/simplewiki_error.html', d)
    else:
        return None
Ejemplo n.º 22
0
def not_found(request, article_path, course):
    """Generate a NOT FOUND message for some URL"""
    d = {'wiki_err_notfound': True,
         'article_path': article_path,
         'namespace': "edX"}
    update_template_dictionary(d, request, course)
    return render_to_response('simplewiki/simplewiki_error.html', d)
Ejemplo n.º 23
0
def course_index(request, org, course, name):
    """
    Display an editable course overview.

    org, course, name: Attributes of the Location for the item to edit
    """
    location = get_location_and_verify_access(request, org, course, name)

    lms_link = get_lms_link_for_item(location)

    upload_asset_callback_url = reverse('upload_asset', kwargs={
        'org': org,
        'course': course,
        'coursename': name
    })

    course = modulestore().get_item(location, depth=3)
    sections = course.get_children()

    return render_to_response('overview.html', {
        'active_tab': 'courseware',
        'context_course': course,
        'lms_link': lms_link,
        'sections': sections,
        'course_graders': json.dumps(CourseGradingModel.fetch(course.location).graders),
        'parent_location': course.location,
        'new_section_template': Location('i4x', 'edx', 'templates', 'chapter', 'Empty'),
        'new_subsection_template': Location('i4x', 'edx', 'templates', 'sequential', 'Empty'),  # for now they are the same, but the could be different at some point...
        'upload_asset_callback_url': upload_asset_callback_url,
        'create_new_unit_template': Location('i4x', 'edx', 'templates', 'vertical', 'Empty')
    })
Ejemplo n.º 24
0
def dashboard(request):
    """
    Slightly less hackish hack to show staff enrollment numbers and other
    simple queries.

    All queries here should be indexed and simple.  Mostly, this means don't
    touch courseware_studentmodule, as tempting as it may be.

    """
    if not request.user.is_staff:
        raise Http404

    # results are passed to the template.  The template knows how to render
    # two types of results: scalars and tables.  Scalars should be represented
    # as "Visible Title": Value and tables should be lists of lists where each
    # inner list represents a single row of the table
    results = {"scalars": {}, "tables": {}}

    # count how many users we have
    results["scalars"]["Unique Usernames"] = User.objects.filter().count()
    results["scalars"]["Activated Usernames"] = User.objects.filter(
        is_active=1).count()

    # count how many enrollments we have
    results["scalars"][
        "Total Enrollments Across All Courses"] = CourseEnrollment.objects.count(
        )

    # establish a direct connection to the database (for executing raw SQL)
    cursor = connection.cursor()

    # define the queries that will generate our user-facing tables
    # table queries need not take the form of raw SQL, but do in this case since
    # the MySQL backend for django isn't very friendly with group by or
    # distinct
    table_queries = {}
    table_queries["course enrollments"] = \
        "select " + \
        "course_id as Course, " + \
        "count(user_id) as Students " + \
        "from student_courseenrollment " + \
        "group by course_id " + \
        "order by students desc;"
    table_queries["number of students in each number of classes"] = \
        "select registrations as 'Registered for __ Classes' , " + \
        "count(registrations) as Users " + \
        "from (select count(user_id) as registrations " + \
        "from student_courseenrollment " + \
        "group by user_id) as registrations_per_user " + \
        "group by registrations;"

    # add the result for each of the table_queries to the results object
    for query in table_queries.keys():
        cursor.execute(table_queries[query])
        results["tables"][query] = SQL_query_to_list(cursor,
                                                     table_queries[query])

    context = {"results": results}

    return render_to_response("admin_dashboard.html", context)
Ejemplo n.º 25
0
def course_index(request, course_id, branch, version_guid, block):
    """
    Display an editable course overview.

    org, course, name: Attributes of the Location for the item to edit
    """
    location = BlockUsageLocator(course_id=course_id, branch=branch, version_guid=version_guid, usage_id=block)
    # TODO: when converting to split backend, if location does not have a usage_id,
    # we'll need to get the course's root block_id
    if not has_access(request.user, location):
        raise PermissionDenied()


    old_location = loc_mapper().translate_locator_to_location(location)

    lms_link = get_lms_link_for_item(old_location)

    course = modulestore().get_item(old_location, depth=3)
    sections = course.get_children()

    return render_to_response('overview.html', {
        'context_course': course,
        'lms_link': lms_link,
        'sections': sections,
        'course_graders': json.dumps(
            CourseGradingModel.fetch(course.location).graders
        ),
        'parent_location': course.location,
        'new_section_category': 'chapter',
        'new_subsection_category': 'sequential',
        'new_unit_category': 'vertical',
        'category': 'vertical'
    })
Ejemplo n.º 26
0
def _manage_users(request, location):
    """
    This view will return all CMS users who are editors for the specified course
    """
    old_location = loc_mapper().translate_locator_to_location(location)

    # check that logged in user has permissions to this item
    if not has_access(request.user, location,
                      role=INSTRUCTOR_ROLE_NAME) and not has_access(
                          request.user, location, role=STAFF_ROLE_NAME):
        raise PermissionDenied()

    course_module = modulestore().get_item(old_location)

    staff_groupname = get_course_groupname_for_role(location, "staff")
    staff_group, __ = Group.objects.get_or_create(name=staff_groupname)
    inst_groupname = get_course_groupname_for_role(location, "instructor")
    inst_group, __ = Group.objects.get_or_create(name=inst_groupname)

    return render_to_response(
        'manage_users.html', {
            'context_course':
            course_module,
            'staff':
            staff_group.user_set.all(),
            'instructors':
            inst_group.user_set.all(),
            'allow_actions':
            has_access(request.user, location, role=INSTRUCTOR_ROLE_NAME),
        })
Ejemplo n.º 27
0
    def get(self, request, course_id):
        """
        Handle the case where we have a get request
        """
        upgrade = request.GET.get('upgrade', False)
        if CourseEnrollment.enrollment_mode_for_user(request.user,
                                                     course_id) == 'verified':
            return redirect(reverse('dashboard'))
        verify_mode = CourseMode.mode_for_course(course_id, "verified")
        if course_id in request.session.get("donation_for_course", {}):
            chosen_price = request.session["donation_for_course"][course_id]
        else:
            chosen_price = verify_mode.min_price.format("{:g}")

        course = course_from_id(course_id)
        context = {
            "course_id": course_id,
            "course_name": course.display_name_with_default,
            "course_org": course.display_org_with_default,
            "course_num": course.display_number_with_default,
            "purchase_endpoint": get_purchase_endpoint(),
            "currency": verify_mode.currency.upper(),
            "chosen_price": chosen_price,
            "upgrade": upgrade,
        }
        return render_to_response('verify_student/verified.html', context)
Ejemplo n.º 28
0
def static_pages(request, org, course, coursename):

    location = get_location_and_verify_access(request, org, course, coursename)

    course = modulestore().get_item(location)

    return render_to_response("static-pages.html", {"active_tab": "pages", "context_course": course})
Ejemplo n.º 29
0
def edit_tabs(request, org, course, coursename):
    "Edit tabs"
    location = ['i4x', org, course, 'course', coursename]
    store = get_modulestore(location)
    course_item = store.get_item(location)

    # check that logged in user has permissions to this item
    if not has_access(request.user, location):
        raise PermissionDenied()

    # see tabs have been uninitialized (e.g. supporing courses created before tab support in studio)
    if course_item.tabs is None or len(course_item.tabs) == 0:
        initialize_course_tabs(course_item)

    # first get all static tabs from the tabs list
    # we do this because this is also the order in which items are displayed in the LMS
    static_tabs_refs = [t for t in course_item.tabs if t['type'] == 'static_tab']

    static_tabs = []
    for static_tab_ref in static_tabs_refs:
        static_tab_loc = Location(location)._replace(category='static_tab', name=static_tab_ref['url_slug'])
        static_tabs.append(modulestore('direct').get_item(static_tab_loc))

    components = [
        static_tab.location.url()
        for static_tab
        in static_tabs
    ]

    return render_to_response('edit-tabs.html', {
        'context_course': course_item,
        'components': components
    })
Ejemplo n.º 30
0
def edit_tabs(request, org, course, coursename):
    location = ["i4x", org, course, "course", coursename]
    course_item = modulestore().get_item(location)

    # check that logged in user has permissions to this item
    if not has_access(request.user, location):
        raise PermissionDenied()

    # see tabs have been uninitialized (e.g. supporing courses created before tab support in studio)
    if course_item.tabs is None or len(course_item.tabs) == 0:
        initialize_course_tabs(course_item)

    # first get all static tabs from the tabs list
    # we do this because this is also the order in which items are displayed in the LMS
    static_tabs_refs = [t for t in course_item.tabs if t["type"] == "static_tab"]

    static_tabs = []
    for static_tab_ref in static_tabs_refs:
        static_tab_loc = Location(location)._replace(category="static_tab", name=static_tab_ref["url_slug"])
        static_tabs.append(modulestore("direct").get_item(static_tab_loc))

    components = [static_tab.location.url() for static_tab in static_tabs]

    return render_to_response(
        "edit-tabs.html", {"active_tab": "pages", "context_course": course_item, "components": components}
    )
Ejemplo n.º 31
0
def revision_feed(request, page=1, namespace=None, course_id=None):
    course = get_opt_course_with_access(request.user, course_id, 'load')

    page_size = 10

    if page is None:
        page = 1
    try:
        p = int(page)
    except ValueError:
        p = 1

    history = Revision.objects.order_by('-revision_date').select_related(
        'revision_user', 'article', 'previous_revision')

    page_count = (history.count() + (page_size - 1)) / page_size
    if p > page_count:
        p = 1
    beginItem = (p - 1) * page_size

    next_page = p + 1 if page_count > p else None
    prev_page = p - 1 if p > 1 else None

    d = {
        'wiki_page': p,
        'wiki_next_page': next_page,
        'wiki_prev_page': prev_page,
        'wiki_history': history[beginItem:beginItem + page_size],
        'show_delete_revision': request.user.is_superuser,
        'namespace': namespace
    }
    update_template_dictionary(d, request, course)

    return render_to_response('simplewiki/simplewiki_revision_feed.html', d)
Ejemplo n.º 32
0
def index(request):
    """
    List all courses available to the logged in user
    """
    courses = modulestore('direct').get_items(['i4x', None, None, 'course', None])

    # filter out courses that we don't have access too
    def course_filter(course):
        return (has_access(request.user, course.location)
                # TODO remove this condition when templates purged from db
                and course.location.course != 'templates'
                and course.location.org != ''
                and course.location.course != ''
                and course.location.name != '')
    courses = filter(course_filter, courses)

    return render_to_response('index.html', {
        'courses': [(course.display_name,
                    get_url_reverse('CourseOutline', course),
                    get_lms_link_for_item(course.location, course_id=course.location.course_id))
                    for course in courses],
        'user': request.user,
        'request_course_creator_url': reverse('request_course_creator'),
        'course_creator_status': _get_course_creator_status(request.user),
        'csrf': csrf(request)['csrf_token']
    })
Ejemplo n.º 33
0
    def post(self, request):
        """
        Render a fake payment page.

        This is an HTML form that:

        * Triggers a POST to `postpay_callback()` on submit.

        * Has hidden fields for all the data CyberSource sends to the callback.
            - Most of this data is duplicated from the request POST params (e.g. `amount` and `course_id`)
            - Other params contain fake data (always the same user name and address.
            - Still other params are calculated (signatures)

        * Serves an error page (HTML) with a 200 status code
          if the signatures are invalid.  This is what CyberSource does.

        Since all the POST requests are triggered by HTML forms, this is
        equivalent to the CyberSource payment page, even though it's
        served by the shopping cart app.
        """
        if self._is_signature_valid(request.POST):
            return self._payment_page_response(request.POST, '/shoppingcart/postpay_callback/')

        else:
            return render_to_response('shoppingcart/test/fake_payment_error.html')
Ejemplo n.º 34
0
def total_course_enrollment(fs, mongodb,params):
    data = total_course_enrollment_query(fs, mongodb, params)
    course_enrollment_unis = []
    course_enrollment_courses = { }
    course_enrollment_terms = { };
    course_enrollment_courses_by_term = { };
    course_enrollment_terms_by_course = { };
    for i in range(0, len(data['course_id'])):
        mch = re.search('^(.*?)\/(.*?)\/(.*?)$', data['course_id'][i])
        uni = mch.group(1)
        course = mch.group(2)
        term = mch.group(3)
        if not uni in course_enrollment_unis:
            course_enrollment_unis.append(uni)
            course_enrollment_courses[uni] = []
            course_enrollment_terms[uni] = []
            course_enrollment_courses_by_term[uni] = { }
            course_enrollment_terms_by_course[uni] = { }
        if not course in course_enrollment_courses[uni]:
            course_enrollment_courses[uni].append(course)
            if not term in course_enrollment_terms[uni]:
                course_enrollment_terms[uni].append(term)
                if not term in course_enrollment_courses_by_term[uni]:
                    course_enrollment_courses_by_term[uni][term] = {}
                    course_enrollment_courses_by_term[uni][term][course] = data['students'][i]
                if not course in course_enrollment_terms_by_course[uni]:
                    course_enrollment_terms_by_course[uni][course] = {}
                    course_enrollment_terms_by_course[uni][course][term] = data['students'][i]
                  
    return render_to_response('user_stats_course_enrollment.html', { 'unis': course_enrollment_unis, 'courses': course_enrollment_courses, 'terms': course_enrollment_terms, 'courses_by_term': course_enrollment_courses_by_term, 'terms_by_course': course_enrollment_terms_by_course })
Ejemplo n.º 35
0
def index(request):
    """
    List all courses available to the logged in user
    """
    courses = modulestore('direct').get_items(
        ['i4x', None, None, 'course', None])

    # filter out courses that we don't have access too
    def course_filter(course):
        return (has_access(request.user, course.location)
                and course.location.course != 'templates'
                and course.location.org != '' and course.location.course != ''
                and course.location.name != '')

    courses = filter(course_filter, courses)

    return render_to_response(
        'index.html', {
            'new_course_template':
            Location('i4x', 'edx', 'templates', 'course', 'Empty'),
            'courses': [
                (course.display_name, get_url_reverse('CourseOutline', course),
                 get_lms_link_for_item(course.location,
                                       course_id=course.location.course_id))
                for course in courses
            ],
            'user':
            request.user,
            'disable_course_creation':
            settings.MITX_FEATURES.get('DISABLE_COURSE_CREATION', False)
            and not request.user.is_staff
        })
Ejemplo n.º 36
0
    def get(self, request, course_id):
        """
        Handle the case where we have a get request
        """
        upgrade = request.GET.get('upgrade', False)
        if CourseEnrollment.enrollment_mode_for_user(request.user, course_id) == 'verified':
            return redirect(reverse('dashboard'))
        verify_mode = CourseMode.mode_for_course(course_id, "verified")
        if course_id in request.session.get("donation_for_course", {}):
            chosen_price = request.session["donation_for_course"][course_id]
        else:
            chosen_price = verify_mode.min_price.format("{:g}")

        course = course_from_id(course_id)
        context = {
            "course_id": course_id,
            "course_name": course.display_name_with_default,
            "course_org": course.display_org_with_default,
            "course_num": course.display_number_with_default,
            "purchase_endpoint": get_purchase_endpoint(),
            "currency": verify_mode.currency.upper(),
            "chosen_price": chosen_price,
            "upgrade": upgrade,
        }
        return render_to_response('verify_student/verified.html', context)
Ejemplo n.º 37
0
def get_checklists(request, org, course, name):
    """
    Send models, views, and html for displaying the course checklists.

    org, course, name: Attributes of the Location for the item to edit
    """
    location = get_location_and_verify_access(request, org, course, name)

    modulestore = get_modulestore(location)
    course_module = modulestore.get_item(location)

    # If course was created before checklists were introduced, copy them over
    # from the template.
    copied = False
    if not course_module.checklists:
        course_module.checklists = CourseDescriptor.checklists.default
        copied = True

    checklists, modified = expand_checklist_action_urls(course_module)
    if copied or modified:
        course_module.save()
        modulestore.update_metadata(location, own_metadata(course_module))
    return render_to_response('checklists.html',
                              {
                                  'context_course': course_module,
                                  'checklists': checklists
                              })
Ejemplo n.º 38
0
    def get(self, request, course_id, error=None):
        """ Displays the course mode choice page """
        if CourseEnrollment.enrollment_mode_for_user(request.user, course_id) == 'verified':
            return redirect(reverse('dashboard'))
        modes = CourseMode.modes_for_course_dict(course_id)

        donation_for_course = request.session.get("donation_for_course", {})
        chosen_price = donation_for_course.get(course_id, None)

        course = course_from_id(course_id)
        context = {
            "course_id": course_id,
            "modes": modes,
            "course_name": course.display_name_with_default,
            "course_org": course.display_org_with_default,
            "course_num": course.display_number_with_default,
            "chosen_price": chosen_price,
            "error": error,
        }
        if "verified" in modes:
            context["suggested_prices"] = modes["verified"].suggested_prices.split(",")
            context["currency"] = modes["verified"].currency.upper()
            context["min_price"] = modes["verified"].min_price

        return render_to_response("course_modes/choose.html", context)
Ejemplo n.º 39
0
def get_course_settings(request, org, course, name):
    """
    Send models and views as well as html for editing the course settings to
    the client.

    org, course, name: Attributes of the Location for the item to edit
    """
    location = get_location_and_verify_access(request, org, course, name)

    course_module = modulestore().get_item(location)

    return render_to_response('settings.html', {
        'context_course': course_module,
        'course_location': location,
        'details_url': reverse(course_settings_updates,
                               kwargs={"org": org,
                                       "course": course,
                                       "name": name,
                                       "section": "details"}),

        'about_page_editable': not settings.MITX_FEATURES.get(
            'ENABLE_MKTG_SITE', False
        ),
        'upload_asset_url': reverse('upload_asset', kwargs={
            'org': org,
            'course': course,
            'coursename': name,
        })
    })
Ejemplo n.º 40
0
def course_index(request, org, course, name):
    """
    Display an editable course overview.

    org, course, name: Attributes of the Location for the item to edit
    """
    location = get_location_and_verify_access(request, org, course, name)

    lms_link = get_lms_link_for_item(location)

    upload_asset_callback_url = reverse('upload_asset', kwargs={
        'org': org,
        'course': course,
        'coursename': name
    })

    course = modulestore().get_item(location, depth=3)
    sections = course.get_children()

    return render_to_response('overview.html', {
        'context_course': course,
        'lms_link': lms_link,
        'sections': sections,
        'course_graders': json.dumps(
            CourseGradingModel.fetch(course.location).graders
        ),
        'parent_location': course.location,
        'new_section_category': 'chapter',
        'new_subsection_category': 'sequential',
        'upload_asset_callback_url': upload_asset_callback_url,
        'new_unit_category': 'vertical',
        'category': 'vertical'
    })
Ejemplo n.º 41
0
def instructor_dashboard_2(request, course_id):
    """ Display the instructor dashboard for a course. """

    course = get_course_by_id(course_id, depth=None)

    access = {
        'admin': request.user.is_staff,
        'instructor': has_access(request.user, course, 'instructor'),
        'staff': has_access(request.user, course, 'staff'),
        'forum_admin': has_forum_access(
            request.user, course_id, FORUM_ROLE_ADMINISTRATOR
        ),
    }

    if not access['staff']:
        raise Http404()

    sections = [
        _section_course_info(course_id, access),
        _section_membership(course_id, access),
        _section_student_admin(course_id, access),
        _section_data_download(course_id),
        _section_analytics(course_id),
    ]

    context = {
        'course': course,
        'old_dashboard_url': reverse('instructor_dashboard', kwargs={'course_id': course_id}),
        'sections': sections,
    }

    return render_to_response('instructor/instructor_dashboard_2/instructor_dashboard_2.html', context)
Ejemplo n.º 42
0
def view_tracking_log(request, args=''):
    """View to output contents of TrackingLog model.  For staff use only."""
    if not request.user.is_staff:
        return redirect('/')
    nlen = 100
    username = ''
    if args:
        for arg in args.split('/'):
            if arg.isdigit():
                nlen = int(arg)
            if arg.startswith('username='******'-time')
    if username:
        record_instances = record_instances.filter(username=username)
    record_instances = record_instances[0:nlen]

    # fix dtstamp
    fmt = '%a %d-%b-%y %H:%M:%S'  # "%Y-%m-%d %H:%M:%S %Z%z"
    for rinst in record_instances:
        rinst.dtstr = rinst.time.replace(tzinfo=pytz.utc).astimezone(
            pytz.timezone('US/Eastern')).strftime(fmt)

    return render_to_response('tracking_log.html',
                              {'records': record_instances})
Ejemplo n.º 43
0
def check_permissions(request, article, course, check_read=False, check_write=False, check_locked=False, check_deleted=False, revision=None):
    read_err = check_read and not article.can_read(request.user)

    write_err = check_write and not article.can_write(request.user)

    locked_err = check_locked and article.locked

    if revision is None:
        revision = article.current_revision
    deleted_err = check_deleted and not (revision.deleted == 0)
    if (request.user.is_superuser):
        deleted_err = False
        locked_err = False

    if read_err or write_err or locked_err or deleted_err:
        d = {'wiki_article': article,
                'wiki_err_noread': read_err,
                'wiki_err_nowrite': write_err,
                'wiki_err_locked': locked_err,
                'wiki_err_deleted': deleted_err, }
        update_template_dictionary(d, request, course)
        # TODO: Make this a little less jarring by just displaying an error
        #       on the current page? (no such redirect happens for an anon upload yet)
        # benjaoming: I think this is the nicest way of displaying an error, but
        # these errors shouldn't occur, but rather be prevented on the other pages.
        return render_to_response('simplewiki/simplewiki_error.html', d)
    else:
        return None
Ejemplo n.º 44
0
def not_found(request, article_path, course):
    """Generate a NOT FOUND message for some URL"""
    d = {'wiki_err_notfound': True,
         'article_path': article_path,
         'namespace': "edX"}
    update_template_dictionary(d, request, course)
    return render_to_response('simplewiki/simplewiki_error.html', d)
Ejemplo n.º 45
0
def index(request, course_id, book_index, page=None):
    """
    Serve static image-based textbooks.
    """
    course = get_course_with_access(request.user, course_id, 'load')
    staff_access = has_access(request.user, course, 'staff')

    book_index = int(book_index)
    if book_index < 0 or book_index >= len(course.textbooks):
        raise Http404("Invalid book index value: {0}".format(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',
        {
            '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,
        },
    )
Ejemplo n.º 46
0
def course_index(request, course_id, branch, version_guid, block):
    """
    Display an editable course overview.

    org, course, name: Attributes of the Location for the item to edit
    """
    location = BlockUsageLocator(course_id=course_id, branch=branch, version_guid=version_guid, usage_id=block)
    # TODO: when converting to split backend, if location does not have a usage_id,
    # we'll need to get the course's root block_id
    if not has_access(request.user, location):
        raise PermissionDenied()


    old_location = loc_mapper().translate_locator_to_location(location)

    lms_link = get_lms_link_for_item(old_location)

    course = modulestore().get_item(old_location, depth=3)
    sections = course.get_children()

    return render_to_response('overview.html', {
        'context_course': course,
        'lms_link': lms_link,
        'sections': sections,
        'course_graders': json.dumps(
            CourseGradingModel.fetch(course.location).graders
        ),
        'parent_location': course.location,
        'new_section_category': 'chapter',
        'new_subsection_category': 'sequential',
        'new_unit_category': 'vertical',
        'category': 'vertical'
    })
Ejemplo n.º 47
0
def course_info(request, org, course, name, provided_id=None):
    """
    Send models and views as well as html for editing the course info to the client.

    org, course, name: Attributes of the Location for the item to edit
    """
    location = get_location_and_verify_access(request, org, course, name)

    course_module = modulestore().get_item(location)

    # get current updates
    location = Location(['i4x', org, course, 'course_info', "updates"])

    return render_to_response(
        'course_info.html', {
            'active_tab':
            'courseinfo-tab',
            'context_course':
            course_module,
            'url_base':
            "/" + org + "/" + course + "/",
            'course_updates':
            json.dumps(get_course_updates(location)),
            'handouts_location':
            Location(['i4x', org, course, 'course_info', 'handouts']).url()
        })
Ejemplo n.º 48
0
def edit_tabs(request, org, course, coursename):
    location = ['i4x', org, course, 'course', coursename]
    store = get_modulestore(location)
    course_item = store.get_item(location)

    # check that logged in user has permissions to this item
    if not has_access(request.user, location):
        raise PermissionDenied()

    # see tabs have been uninitialized (e.g. supporing courses created before tab support in studio)
    if course_item.tabs is None or len(course_item.tabs) == 0:
        initialize_course_tabs(course_item)

    # first get all static tabs from the tabs list
    # we do this because this is also the order in which items are displayed in the LMS
    static_tabs_refs = [t for t in course_item.tabs if t['type'] == 'static_tab']

    static_tabs = []
    for static_tab_ref in static_tabs_refs:
        static_tab_loc = Location(location)._replace(category='static_tab', name=static_tab_ref['url_slug'])
        static_tabs.append(modulestore('direct').get_item(static_tab_loc))

    components = [
        static_tab.location.url()
        for static_tab
        in static_tabs
    ]

    return render_to_response('edit-tabs.html', {
        'context_course': course_item,
        'components': components
    })
Ejemplo n.º 49
0
def get_checklists(request, org, course, name):
    """
    Send models, views, and html for displaying the course checklists.

    org, course, name: Attributes of the Location for the item to edit
    """
    location = get_location_and_verify_access(request, org, course, name)

    modulestore = get_modulestore(location)
    course_module = modulestore.get_item(location)

    # If course was created before checklists were introduced, copy them over from the template.
    copied = False
    if not course_module.checklists:
        course_module.checklists = CourseDescriptor.checklists.default
        copied = True

    checklists, modified = expand_checklist_action_urls(course_module)
    if copied or modified:
        course_module.save()
        modulestore.update_metadata(location, own_metadata(course_module))
    return render_to_response('checklists.html',
                              {
                                  'context_course': course_module,
                                  'checklists': checklists
                              })
Ejemplo n.º 50
0
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(
        request,
        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, })
Ejemplo n.º 51
0
def university_profile(request, org_id):
    """
    Return the profile for the particular org_id.  404 if it's not valid.
    """
    virtual_orgs_ids = settings.VIRTUAL_UNIVERSITIES
    meta_orgs = getattr(settings, 'META_UNIVERSITIES', {})

    # Get all the ids associated with this organization
    all_courses = modulestore().get_courses()
    valid_orgs_ids = set(c.org for c in all_courses)
    valid_orgs_ids.update(virtual_orgs_ids + meta_orgs.keys())

    if org_id not in valid_orgs_ids:
        raise Http404("University Profile not found for {0}".format(org_id))

    # Grab all courses for this organization(s)
    org_ids = set([org_id] + meta_orgs.get(org_id, []))
    org_courses = []
    domain = request.META.get('HTTP_HOST')
    for key in org_ids:
        cs = get_courses_by_university(request.user, domain=domain)[key]
        org_courses.extend(cs)

    org_courses = sort_by_announcement(org_courses)

    context = dict(courses=org_courses, org_id=org_id)
    template_file = "university_profile/{0}.html".format(org_id).lower()

    return render_to_response(template_file, context)
Ejemplo n.º 52
0
def index(request):
    # courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    # courses = sorted(courses, key=lambda course: course.display_name.lower())

    courses = get_courses_drop(request.user.profile.district.state.name, request.user.profile.district.code)
    
    return render_to_response('administration/pepreg.html', {"courses": courses})
Ejemplo n.º 53
0
def show_receipt(request, ordernum):
    """
    Displays a receipt for a particular order.
    404 if order is not yet purchased or request.user != order.user
    """
    try:
        order = Order.objects.get(id=ordernum)
    except Order.DoesNotExist:
        raise Http404('Order not found!')

    if order.user != request.user or order.status != 'purchased':
        raise Http404('Order not found!')

    order_items = OrderItem.objects.filter(order=order).select_subclasses()
    any_refunds = any(i.status == "refunded" for i in order_items)
    receipt_template = 'shoppingcart/receipt.html'
    # we want to have the ability to override the default receipt page when
    # there is only one item in the order
    context = {
        'order': order,
        'order_items': order_items,
        'any_refunds': any_refunds,
    }

    if order_items.count() == 1:
        receipt_template = order_items[0].single_item_receipt_template

    return render_to_response(receipt_template, context)
Ejemplo n.º 54
0
def courses_search(request):
    """
    Render "find courses" page.  The course selection work is done in courseware.courses.
    """
    if request.is_ajax():
        query_string = ""
        courses = []
        query_string = request.GET['search_string']
        if query_string is not None:
            print "----------------------------------" + query_string + "\n"
            entry_query = normalize_query(query_string)
            allCourses = get_courses(request.user,
                                     request.META.get('HTTP_HOST'))
            for course in allCourses:
                title = get_course_about_section(course, 'title').lower()
                flag = True
                for query in entry_query:
                    if not query.lower() in title:
                        flag = False
                        break
                if flag:
                    courses.append(course)
            courses = sort_by_announcement(courses)

            if courses:
                return render_to_response("courseware/courses_search.html",
                                          {'courses': courses})
            else:
                return HttpResponse("No Courses Found")