Example #1
0
    def replace_static_url(original, prefix, quote, rest):
        """
        Replace a single matched url.
        """
        # Don't mess with things that end in '?raw'
        if rest.endswith('?raw'):
            return original

        # In debug mode, if we can find the url as is,
        if settings.DEBUG and finders.find(rest, True):
            return original
        # if we're running with a MongoBacked store course_namespace is not None, then use studio style urls
        elif (not static_asset_path) \
                and course_id \
                and modulestore().get_modulestore_type(course_id) != ModuleStoreEnum.Type.xml:
            # first look in the static file pipeline and see if we are trying to reference
            # a piece of static content which is in the edx-platform repo (e.g. JS associated with an xmodule)

            exists_in_staticfiles_storage = False
            try:
                exists_in_staticfiles_storage = staticfiles_storage.exists(
                    rest)
            except Exception as err:
                log.warning(
                    u"staticfiles_storage couldn't find path {0}: {1}".format(
                        rest, unicode(err)))

            if exists_in_staticfiles_storage:
                url = staticfiles_storage.url(rest)
            else:
                # if not, then assume it's courseware specific content and then look in the
                # Mongo-backed database
                url = StaticContent.convert_legacy_static_url_with_course_id(
                    rest, course_id)

                if AssetLocator.CANONICAL_NAMESPACE in url:
                    url = url.replace('block@', 'block/', 1)

        # Otherwise, look the file up in staticfiles_storage, and append the data directory if needed
        else:
            course_path = "/".join((static_asset_path or data_directory, rest))

            try:
                if staticfiles_storage.exists(rest):
                    url = staticfiles_storage.url(rest)
                else:
                    url = staticfiles_storage.url(course_path)
            # And if that fails, assume that it's course content, and add manually data directory
            except Exception as err:
                log.warning(
                    "staticfiles_storage couldn't find path {0}: {1}".format(
                        rest, str(err)))
                url = "".join([prefix, course_path])

        return "".join([quote, url, quote])
Example #2
0
    def replace_static_url(match):
        original = match.group(0)
        prefix = match.group('prefix')
        quote = match.group('quote')
        rest = match.group('rest')

        # Don't mess with things that end in '?raw'
        if rest.endswith('?raw'):
            return original

        # In debug mode, if we can find the url as is,
        if settings.DEBUG and finders.find(rest, True):
            return original
        # if we're running with a MongoBacked store course_namespace is not None, then use studio style urls
        elif (not static_asset_path) and course_id and modulestore(
        ).get_modulestore_type(course_id) != XML_MODULESTORE_TYPE:
            # first look in the static file pipeline and see if we are trying to reference
            # a piece of static content which is in the mitx repo (e.g. JS associated with an xmodule)

            exists_in_staticfiles_storage = False
            try:
                exists_in_staticfiles_storage = staticfiles_storage.exists(
                    rest)
            except Exception as err:
                log.warning(
                    "staticfiles_storage couldn't find path {0}: {1}".format(
                        rest, str(err)))

            if exists_in_staticfiles_storage:
                url = staticfiles_storage.url(rest)
            else:
                # if not, then assume it's courseware specific content and then look in the
                # Mongo-backed database
                url = StaticContent.convert_legacy_static_url_with_course_id(
                    rest, course_id)
        # Otherwise, look the file up in staticfiles_storage, and append the data directory if needed
        else:
            course_path = "/".join((static_asset_path or data_directory, rest))

            try:
                if staticfiles_storage.exists(rest):
                    url = staticfiles_storage.url(rest)
                else:
                    url = staticfiles_storage.url(course_path)
            # And if that fails, assume that it's course content, and add manually data directory
            except Exception as err:
                log.warning(
                    "staticfiles_storage couldn't find path {0}: {1}".format(
                        rest, str(err)))
                url = "".join([prefix, course_path])

        return "".join([quote, url, quote])
Example #3
0
    def replace_static_url(original, prefix, quote, rest):
        """
        Replace a single matched url.
        """
        # Don't mess with things that end in '?raw'
        if rest.endswith('?raw'):
            return original

        # In debug mode, if we can find the url as is,
        if settings.DEBUG and finders.find(rest, True):
            return original
        # if we're running with a MongoBacked store course_namespace is not None, then use studio style urls
        elif (not static_asset_path) \
                and course_id \
                and modulestore().get_modulestore_type(course_id) != ModuleStoreEnum.Type.xml:
            # first look in the static file pipeline and see if we are trying to reference
            # a piece of static content which is in the edx-platform repo (e.g. JS associated with an xmodule)

            exists_in_staticfiles_storage = False
            try:
                exists_in_staticfiles_storage = staticfiles_storage.exists(rest)
            except Exception as err:
                log.warning("staticfiles_storage couldn't find path {0}: {1}".format(
                    rest, str(err)))

            if exists_in_staticfiles_storage:
                url = staticfiles_storage.url(rest)
            else:
                # if not, then assume it's courseware specific content and then look in the
                # Mongo-backed database
                url = StaticContent.convert_legacy_static_url_with_course_id(rest, course_id)

                if AssetLocator.CANONICAL_NAMESPACE in url:
                    url = url.replace('block@', 'block/', 1)

        # Otherwise, look the file up in staticfiles_storage, and append the data directory if needed
        else:
            course_path = "/".join((static_asset_path or data_directory, rest))

            try:
                if staticfiles_storage.exists(rest):
                    url = staticfiles_storage.url(rest)
                else:
                    url = staticfiles_storage.url(course_path)
            # And if that fails, assume that it's course content, and add manually data directory
            except Exception as err:
                log.warning("staticfiles_storage couldn't find path {0}: {1}".format(
                    rest, str(err)))
                url = "".join([prefix, course_path])

        return "".join([quote, url, quote])
    def replace_static_url(match):
        original = match.group(0)
        prefix = match.group("prefix")
        quote = match.group("quote")
        rest = match.group("rest")

        # Don't mess with things that end in '?raw'
        if rest.endswith("?raw"):
            return original

        # In debug mode, if we can find the url as is,
        if settings.DEBUG and finders.find(rest, True):
            return original
        # if we're running with a MongoBacked store course_namespace is not None, then use studio style urls
        elif (
            (not static_asset_path)
            and course_id
            and modulestore().get_modulestore_type(course_id) != XML_MODULESTORE_TYPE
        ):
            # first look in the static file pipeline and see if we are trying to reference
            # a piece of static content which is in the edx-platform repo (e.g. JS associated with an xmodule)

            exists_in_staticfiles_storage = False
            try:
                exists_in_staticfiles_storage = staticfiles_storage.exists(rest)
            except Exception as err:
                log.warning("staticfiles_storage couldn't find path {0}: {1}".format(rest, str(err)))

            if exists_in_staticfiles_storage:
                url = staticfiles_storage.url(rest)
            else:
                # if not, then assume it's courseware specific content and then look in the
                # Mongo-backed database
                url = StaticContent.convert_legacy_static_url_with_course_id(rest, course_id)
        # Otherwise, look the file up in staticfiles_storage, and append the data directory if needed
        else:
            course_path = "/".join((static_asset_path or data_directory, rest))

            try:
                if staticfiles_storage.exists(rest):
                    url = staticfiles_storage.url(rest)
                else:
                    url = staticfiles_storage.url(course_path)
            # And if that fails, assume that it's course content, and add manually data directory
            except Exception as err:
                log.warning("staticfiles_storage couldn't find path {0}: {1}".format(rest, str(err)))
                url = "".join([prefix, course_path])

        return "".join([quote, url, quote])
Example #5
0
 def render_js(self, package, path):
     template_name = package.template_name or "pipeline/js.html"
     context = package.extra_context
     context.update({
         'url': staticfiles_storage.url(path)
     })
     return render_to_string(template_name, context)
Example #6
0
def favicon_path(default=getattr(settings, 'FAVICON_PATH',
                                 'images/favicon.ico')):
    """
    Django template tag that outputs the configured favicon:
    {% favicon_path %}
    """
    return staticfiles_storage.url(microsite.get_value('favicon_path',
                                                       default))
Example #7
0
 def render_js(self, package, path):
     template_name = package.template_name or "pipeline/js.html"
     context = package.extra_context
     context.update({
         'type': guess_type(path, 'text/javascript'),
         'url': staticfiles_storage.url(path)
     })
     return render_to_string(template_name, context)
Example #8
0
 def render_js(self, package, path):
     template_name = package.template_name or "pipeline/js.html"
     context = package.extra_context
     context.update({
         'type': guess_type(path, 'text/javascript'),
         'url': staticfiles_storage.url(path)
     })
     return render_to_string(template_name, context)
Example #9
0
    def replace_static_url(match):
        original = match.group(0)
        prefix = match.group('prefix')
        quote = match.group('quote')
        rest = match.group('rest')

        # Don't mess with things that end in '?raw'
        if rest.endswith('?raw'):
            return original

        # In debug mode, if we can find the url as is,
        if settings.DEBUG and finders.find(rest, True):
            return original
        # if we're running with a MongoBacked store course_namespace is not
        # None, then use studio style urls
        elif course_namespace is not None and not isinstance(modulestore(), XMLModuleStore):
            # first look in the static file pipeline and see if we are trying to reference
            # a piece of static content which is in the mitx repo (e.g. JS
            # associated with an xmodule)
            if staticfiles_storage.exists(rest):
                url = staticfiles_storage.url(rest)
            else:
                # if not, then assume it's courseware specific content and then look in the
                # Mongo-backed database
                url = StaticContent.convert_legacy_static_url(
                    rest, course_namespace)
        # Otherwise, look the file up in staticfiles_storage, and append the
        # data directory if needed
        else:
            course_path = "/".join((data_directory, rest))

            try:
                if staticfiles_storage.exists(rest):
                    url = staticfiles_storage.url(rest)
                else:
                    url = staticfiles_storage.url(course_path)
            # And if that fails, assume that it's course content, and add
            # manually data directory
            except Exception as err:
                log.warning("staticfiles_storage couldn't find path {0}: {1}".format(
                    rest, str(err)))
                url = "".join([prefix, course_path])

        return "".join([quote, url, quote])
Example #10
0
    def get(self, request, course_id, usage_id):
        """Display the view for face photo submission.

        Args:
            request(HttpRequest): HttpRequest object
            course_id(str): A string of course id
            usage_id(str): Location of Reverification XBlock in courseware

        Returns:
            HttpResponse
        """
        # Check that in-course re-verification is enabled or not
        incourse_reverify_enabled = InCourseReverificationConfiguration.current().enabled

        if not incourse_reverify_enabled:
            log.error(
                u"In-course reverification is not enabled.  "
                u"You can enable it in Django admin by setting "
                u"InCourseReverificationConfiguration to enabled."
            )
            raise Http404

        user = request.user
        course_key = CourseKey.from_string(course_id)
        course = modulestore().get_course(course_key)
        if course is None:
            log.error(u"Could not find course '%s' for in-course reverification.", course_key)
            raise Http404

        checkpoint = VerificationCheckpoint.get_verification_checkpoint(course_key, usage_id)
        if checkpoint is None:
            log.error(
                u"No verification checkpoint exists for the "
                u"course '%s' and checkpoint location '%s'.",
                course_key, usage_id
            )
            raise Http404

        initial_verification = SoftwareSecurePhotoVerification.get_initial_verification(user)
        if not initial_verification:
            return self._redirect_no_initial_verification(user, course_key)

        # emit the reverification event
        self._track_reverification_events(
            EVENT_NAME_USER_ENTERED_INCOURSE_REVERIFY_VIEW, user.id, course_id, checkpoint.checkpoint_name
        )

        context = {
            'course_key': unicode(course_key),
            'course_name': course.display_name_with_default,
            'checkpoint_name': checkpoint.checkpoint_name,
            'platform_name': settings.PLATFORM_NAME,
            'usage_id': usage_id,
            'capture_sound': staticfiles_storage.url("audio/camera_capture.wav"),
        }
        return render_to_response("verify_student/incourse_reverify.html", context)
Example #11
0
def get_xmodule_urls():
    """
    Returns a list of the URLs to hit to grab all the XModule JS
    """
    if settings.DEBUG:
        paths = [path.replace(".coffee", ".js") for path in
                 settings.PIPELINE_JS['module-js']['source_filenames']]
    else:
        paths = [settings.PIPELINE_JS['module-js']['output_filename']]
    return [staticfiles_storage.url(path) for path in paths]
Example #12
0
def static_url(path):
    """
    Take a static file path and return the correct URL.

    Simple wrapper around staticfiles.storage.staticfiles_storage.
    """
    try:
        return staticfiles_storage.url(path)
    except ValueError:
        # URL couldn't be found.  Let's just return the path.
        return path
Example #13
0
def get_xmodule_urls():
    """
    Returns a list of the URLs to hit to grab all the XModule JS
    """
    if settings.DEBUG:
        paths = [
            path.replace(".coffee", ".js")
            for path in settings.PIPELINE_JS['module-js']['source_filenames']
        ]
    else:
        paths = [settings.PIPELINE_JS['module-js']['output_filename']]
    return [staticfiles_storage.url(path) for path in paths]
Example #14
0
def try_staticfiles_lookup(path):
    """
    Try to lookup a path in staticfiles_storage.  If it fails, return
    a dead link instead of raising an exception.
    """
    try:
        url = staticfiles_storage.url(path)
    except Exception as err:
        log.warning("staticfiles_storage couldn't find path {0}: {1}".format(path, str(err)))
        # Just return the original path; don't kill everything.
        url = path
    return url
Example #15
0
def _absolute_url_staticfile(is_secure, name):
    """Construct an absolute URL back to a static resource on the site.

    Arguments:
        is_secure (bool): If true, use HTTPS as the protocol.
        name (unicode): The name of the static resource to retrieve.

    Returns:
        unicode

    """
    url_path = staticfiles_storage.url(name)
    return _absolute_url(is_secure, url_path)
Example #16
0
def try_staticfiles_lookup(path):
    """
    Try to lookup a path in staticfiles_storage.  If it fails, return
    a dead link instead of raising an exception.
    """
    try:
        url = staticfiles_storage.url(path)
    except Exception as err:
        log.warning("staticfiles_storage couldn't find path {0}: {1}".format(
            path, str(err)))
        # Just return the original path; don't kill everything.
        url = path
    return url
Example #17
0
def get_logo_url():
    """
    Return the url for the branded logo image to be used
    """

    # if the MicrositeConfiguration has a value for the logo_image_url
    # let's use that
    image_url = microsite.get_value('logo_image_url')
    if image_url:
        return '{static_url}{image_url}'.format(static_url=settings.STATIC_URL,
                                                image_url=image_url)

    # otherwise, use the legacy means to configure this
    university = microsite.get_value('university')

    if university is None and settings.FEATURES.get('IS_EDX_DOMAIN', False):
        return staticfiles_storage.url('images/edx-theme/edx-logo-77x36.png')
    elif university:
        return staticfiles_storage.url(
            'images/{uni}-on-edx-logo.png'.format(uni=university))
    else:
        return staticfiles_storage.url('images/default-theme/logo.png')
Example #18
0
def get_logo_url():
    """
    Return the url for the branded logo image to be used
    """

    # if the MicrositeConfiguration has a value for the logo_image_url
    # let's use that
    image_url = microsite.get_value('logo_image_url')
    if image_url:
        return '{static_url}{image_url}'.format(
            static_url=settings.STATIC_URL,
            image_url=image_url
        )

    # otherwise, use the legacy means to configure this
    university = microsite.get_value('university')

    if university is None and settings.FEATURES.get('IS_EDX_DOMAIN', False):
        return staticfiles_storage.url('images/edx-theme/edx-logo-77x36.png')
    elif university:
        return staticfiles_storage.url('images/{uni}-on-edx-logo.png'.format(uni=university))
    else:
        return staticfiles_storage.url('images/logo.png')
Example #19
0
    def render(self, path):
        """Render the HTML tag."""
        if not self.package.template_name:
            template_name = {"js": "pipeline/js.jinja", "css": "pipeline/css.jinja"}[self.package_type]
        else:
            template_name = self.package.template_name

        mimetype = {"js": "text/javascript", "css": "text/css"}[self.package_type]

        context = self.package.extra_context
        context.update({"type": guess_type(path, mimetype), "url": staticfiles_storage.url(path)})

        env = Environment(loader=self.loader)
        tpl = env.get_template(template_name)
        return tpl.render(**context)
def render_url(context, file):
    __M_caller = context.caller_stack._push_frame()
    try:
        __M_writer = context.writer()
        # SOURCE LINE 6

        try:
            url = staticfiles_storage.url(file)
        except:
            url = file

        # SOURCE LINE 11
        __M_writer(filters.decode.utf8(url))
        return ""
    finally:
        context.caller_stack._pop_frame()
Example #21
0
    def get(self, request):
        """
        Render the reverification flow.

        Most of the work is done client-side by composing the same
        Backbone views used in the initial verification flow.
        """
        status, _ = SoftwareSecurePhotoVerification.user_status(request.user)
        if status in ["must_reverify", "expired"]:
            context = {
                "user_full_name": request.user.profile.name,
                "platform_name": microsite.get_value("platform_name", settings.PLATFORM_NAME),
                "capture_sound": staticfiles_storage.url("audio/camera_capture.wav"),
            }
            return render_to_response("verify_student/reverify.html", context)
        else:
            context = {"status": status}
            return render_to_response("verify_student/reverify_not_allowed.html", context)
Example #22
0
    def _template_url(self, template_name):
        """Determine the path to a template.

        This uses staticfiles, so the path will include MD5
        hashes when used in production.  This is really important,
        because otherwise the JavaScript won't be able to find
        the templates!

        Arguments:
            template_name (str): The name of the template, relative
                to the "static/templates" directory.

        Returns:
            string

        """
        template_path = u"templates/{name}".format(name=template_name)
        return (
            staticfiles_storage.url(template_path)
            if template_name is not None else ""
        )
Example #23
0
File: api.py Project: rhndg/openedx
def _absolute_url_staticfile(is_secure, name):
    """Construct an absolute URL to a static resource on the site.

    Arguments:
        is_secure (bool): If true, use HTTPS as the protocol.
        name (unicode): The name of the static resource to retrieve.

    Returns:
        unicode

    """
    url_path = staticfiles_storage.url(name)

    # In production, the static files URL will be an absolute
    # URL pointing to a CDN.  If this happens, we can just
    # return the URL.
    if urlparse.urlparse(url_path).netloc:
        return url_path

    # For local development, the returned URL will be relative,
    # so we need to make it absolute.
    return _absolute_url(is_secure, url_path)
Example #24
0
File: api.py Project: epixia/spark
def _absolute_url_staticfile(is_secure, name):
    """Construct an absolute URL to a static resource on the site.

    Arguments:
        is_secure (bool): If true, use HTTPS as the protocol.
        name (unicode): The name of the static resource to retrieve.

    Returns:
        unicode

    """
    url_path = staticfiles_storage.url(name)

    # In production, the static files URL will be an absolute
    # URL pointing to a CDN.  If this happens, we can just
    # return the URL.
    if urlparse.urlparse(url_path).netloc:
        return url_path

    # For local development, the returned URL will be relative,
    # so we need to make it absolute.
    return _absolute_url(is_secure, url_path)
Example #25
0
    def render(self, path):
        """Render the HTML tag."""
        if not self.package.template_name:
            template_name = {
                'js': 'pipeline/js.jinja',
                'css': 'pipeline/css.jinja',
            }[self.package_type]
        else:
            template_name = self.package.template_name

        mimetype = {
            'js': 'text/javascript',
            'css': 'text/css',
        }[self.package_type]

        context = self.package.extra_context
        context.update({
            'type': guess_type(path, mimetype),
            'url': staticfiles_storage.url(path)
        })

        env = Environment(loader=self.loader)
        tpl = env.get_template(template_name)
        return tpl.render(**context)
Example #26
0
    def render(self, path):
        """Render the HTML tag."""
        if not self.package.template_name:
            template_name = {
                'js': 'pipeline/js.jinja',
                'css': 'pipeline/css.jinja',
            }[self.package_type]
        else:
            template_name = self.package.template_name

        mimetype = {
            'js': 'text/javascript',
            'css': 'text/css',
        }[self.package_type]

        context = self.package.extra_context
        context.update({
            'type': guess_type(path, mimetype),
            'url': staticfiles_storage.url(path)
        })

        env = Environment(loader=self.loader)
        tpl = env.get_template(template_name)
        return tpl.render(**context)
def render_css(context,group):
    __M_caller = context.caller_stack._push_frame()
    try:
        settings = context.get('settings', UNDEFINED)
        __M_writer = context.writer()
        # SOURCE LINE 13
        __M_writer(u'\n')
        # SOURCE LINE 14
        if settings.MITX_FEATURES['USE_DJANGO_PIPELINE']:
            # SOURCE LINE 15
            __M_writer(u'    ')
            __M_writer(filters.decode.utf8(compressed_css(group)))
            __M_writer(u'\n')
            # SOURCE LINE 16
        else:
            # SOURCE LINE 17
            for filename in settings.PIPELINE_CSS[group]['source_filenames']:
                # SOURCE LINE 18
                __M_writer(u'      <link rel="stylesheet" href="')
                __M_writer(filters.decode.utf8(staticfiles_storage.url(filename.replace('.scss', '.css'))))
                __M_writer(u'" type="text/css" media="all" / >\n')
        return ''
    finally:
        context.caller_stack._pop_frame()
def render_js(context,group):
    __M_caller = context.caller_stack._push_frame()
    try:
        settings = context.get('settings', UNDEFINED)
        __M_writer = context.writer()
        # SOURCE LINE 22
        __M_writer(u'\n')
        # SOURCE LINE 23
        if settings.MITX_FEATURES['USE_DJANGO_PIPELINE']:
            # SOURCE LINE 24
            __M_writer(u'    ')
            __M_writer(filters.decode.utf8(compressed_js(group)))
            __M_writer(u'\n')
            # SOURCE LINE 25
        else:
            # SOURCE LINE 26
            for filename in settings.PIPELINE_JS[group]['source_filenames']:
                # SOURCE LINE 27
                __M_writer(u'      <script type="text/javascript" src="')
                __M_writer(filters.decode.utf8(staticfiles_storage.url(filename.replace('.coffee', '.js'))))
                __M_writer(u'"></script>\n')
        return ''
    finally:
        context.caller_stack._pop_frame()
Example #29
0
def static(path):
    """
    A template tag that returns the URL to a file
    using staticfiles' storage backend
    """
    return staticfiles_storage.url(path)
Example #30
0
def _footer_static_url(request, name):
    """Construct an absolute URL to a static asset. """
    return request.build_absolute_uri(staticfiles_storage.url(name))
Example #31
0
def _footer_static_url(request, name):
    """Construct an absolute URL to a static asset. """
    return request.build_absolute_uri(staticfiles_storage.url(name))
Example #32
0
def render_require_js_path_overrides(path_overrides):  # pylint: disable=invalid-name
    """Render JavaScript to override default RequireJS paths.

    The Django pipeline appends a hash to JavaScript files,
    so if the JS asset isn't included in the bundle for the page,
    we need to tell RequireJS where to look.

    For example:

        "js/vendor/jquery.min.js" --> "js/vendor/jquery.min.abcd1234"

    We would then add a line in a <script> tag:

        require.paths['jquery'] = 'js/vendor/jquery.min.abcd1234'

    so that any reference to 'jquery' in a JavaScript module
    will cause RequireJS to load '/static/js/vendor/jquery.min.abcd1234.js'

    If running in DEBUG mode (as in devstack), the resolved JavaScript URLs
    won't contain hashes, so the new paths will match the original paths.

    Arguments:
        path_overrides (dict): Mapping of RequireJS module names to
            filesystem paths.

    Returns:
        unicode: The HTML of the <script> tag with the path overrides.

    """
    # Render the <script> tag that overrides the paths defined in `require.paths`
    # Note: We don't use a Mako template to render this because Mako apparently
    # acquires a lock when loading templates, which can lead to a deadlock if
    # this function is called from within another template.
    html = ['<script type="text/javascript">']

    # The rendered <script> tag with overrides should be included *after*
    # the application's RequireJS config, which defines a `require` object.
    # Just in case the `require` object hasn't been loaded, we create a default
    # object.  This will avoid a JavaScript error that might cause the rest of the
    # page to fail; however, it may mean that these overrides won't be available
    # to RequireJS.
    html.extend([
        'var require = require || {};', 'require.paths = require.paths || [];'
    ])

    # Specify override the base URL to point to STATIC_URL
    html.append(
        "require.baseUrl = '{url}'".format(url=django_settings.STATIC_URL))

    for module, url_path in path_overrides.iteritems():
        # Calculate the full URL, including any hashes added to the filename by the pipeline.
        # This will also include the base static URL (for example, "/static/") and the
        # ".js" extension.
        actual_url = staticfiles_storage.url(url_path)

        # RequireJS assumes that every file it tries to load has a ".js" extension, so
        # we need to remove ".js" from the module path.
        # RequireJS also already has a base URL set to the base static URL, so we can remove that.
        path = actual_url.replace('.js',
                                  '').replace(django_settings.STATIC_URL, '')

        # Add the path override to the inline JavaScript.
        html.append("require.paths['{module}'] = '{path}';".format(
            module=module, path=path))
    html.append('</script>')
    return "\n".join(html)
Example #33
0
    def get(
        self, request, course_id,
        always_show_payment=False,
        current_step=None,
        message=FIRST_TIME_VERIFY_MSG
    ):
        """Render the pay/verify requirements page.

        Arguments:
            request (HttpRequest): The request object.
            course_id (unicode): The ID of the course the user is trying
                to enroll in.

        Keyword Arguments:
            always_show_payment (bool): If True, show the payment steps
                even if the user has already paid.  This is useful
                for users returning to the flow after paying.
            current_step (string): The current step in the flow.
            message (string): The messaging to display.

        Returns:
            HttpResponse

        Raises:
            Http404: The course does not exist or does not
                have a verified mode.

        """
        # Parse the course key
        # The URL regex should guarantee that the key format is valid.
        course_key = CourseKey.from_string(course_id)
        course = modulestore().get_course(course_key)

        # Verify that the course exists and has a verified mode
        if course is None:
            log.warn(u"No course specified for verification flow request.")
            raise Http404

        # Check whether the user has access to this course
        # based on country access rules.
        redirect_url = embargo_api.redirect_if_blocked(
            course_key,
            user=request.user,
            ip_address=get_ip(request),
            url=request.path
        )
        if redirect_url:
            return redirect(redirect_url)

        expired_verified_course_mode, unexpired_paid_course_mode = self._get_expired_verified_and_paid_mode(course_key)

        # Check that the course has an unexpired paid mode
        if unexpired_paid_course_mode is not None:
            if CourseMode.is_verified_mode(unexpired_paid_course_mode):
                log.info(
                    u"Entering verified workflow for user '%s', course '%s', with current step '%s'.",
                    request.user.id, course_id, current_step
                )
        elif expired_verified_course_mode is not None:
            # Check if there is an *expired* verified course mode;
            # if so, we should show a message explaining that the verification
            # deadline has passed.
            log.info(u"Verification deadline for '%s' has passed.", course_id)
            context = {
                'course': course,
                'deadline': (
                    get_default_time_display(expired_verified_course_mode.expiration_datetime)
                    if expired_verified_course_mode.expiration_datetime else ""
                )
            }
            return render_to_response("verify_student/missed_verification_deadline.html", context)
        else:
            # Otherwise, there has never been a verified/paid mode,
            # so return a page not found response.
            log.warn(
                u"No paid/verified course mode found for course '%s' for verification/payment flow request",
                course_id
            )
            raise Http404

        # Check whether the user has verified, paid, and enrolled.
        # A user is considered "paid" if he or she has an enrollment
        # with a paid course mode (such as "verified").
        # For this reason, every paid user is enrolled, but not
        # every enrolled user is paid.
        # If the course mode is not verified(i.e only paid) then already_verified is always True
        already_verified = self._check_already_verified(request.user) \
            if CourseMode.is_verified_mode(unexpired_paid_course_mode) else True
        already_paid, is_enrolled = self._check_enrollment(request.user, course_key)

        # Redirect the user to a more appropriate page if the
        # messaging won't make sense based on the user's
        # enrollment / payment / verification status.
        redirect_response = self._redirect_if_necessary(
            message,
            already_verified,
            already_paid,
            is_enrolled,
            course_key
        )
        if redirect_response is not None:
            return redirect_response

        display_steps = self._display_steps(
            always_show_payment,
            already_verified,
            already_paid,
            unexpired_paid_course_mode
        )
        requirements = self._requirements(display_steps, request.user.is_active)

        if current_step is None:
            current_step = display_steps[0]['name']

        # Allow the caller to skip the first page
        # This is useful if we want the user to be able to
        # use the "back" button to return to the previous step.
        # This parameter should only work for known skip-able steps
        if request.GET.get('skip-first-step') and current_step in self.SKIP_STEPS:
            display_step_names = [step['name'] for step in display_steps]
            current_step_idx = display_step_names.index(current_step)
            if (current_step_idx + 1) < len(display_steps):
                current_step = display_steps[current_step_idx + 1]['name']

        courseware_url = ""
        if not course.start or course.start < datetime.datetime.today().replace(tzinfo=UTC):
            courseware_url = reverse(
                'course_root',
                kwargs={'course_id': unicode(course_key)}
            )

        full_name = (
            request.user.profile.name
            if request.user.profile.name
            else ""
        )

        # If the user set a contribution amount on another page,
        # use that amount to pre-fill the price selection form.
        contribution_amount = request.session.get(
            'donation_for_course', {}
        ).get(unicode(course_key), '')

        # Remember whether the user is upgrading
        # so we can fire an analytics event upon payment.
        request.session['attempting_upgrade'] = (message == self.UPGRADE_MSG)

        # Determine the photo verification status
        verification_good_until = self._verification_valid_until(request.user)

        # get available payment processors
        if unexpired_paid_course_mode.sku:
            # transaction will be conducted via ecommerce service
            processors = ecommerce_api_client(request.user).payment.processors.get()
        else:
            # transaction will be conducted using legacy shopping cart
            processors = [settings.CC_PROCESSOR_NAME]

        # Render the top-level page
        context = {
            'contribution_amount': contribution_amount,
            'course': course,
            'course_key': unicode(course_key),
            'course_mode': unexpired_paid_course_mode,
            'courseware_url': courseware_url,
            'current_step': current_step,
            'disable_courseware_js': True,
            'display_steps': display_steps,
            'is_active': json.dumps(request.user.is_active),
            'message_key': message,
            'platform_name': settings.PLATFORM_NAME,
            'processors': processors,
            'requirements': requirements,
            'user_full_name': full_name,
            'verification_deadline': (
                get_default_time_display(unexpired_paid_course_mode.expiration_datetime)
                if unexpired_paid_course_mode.expiration_datetime else ""
            ),
            'already_verified': already_verified,
            'verification_good_until': verification_good_until,
            'capture_sound': staticfiles_storage.url("audio/camera_capture.wav"),
        }
        return render_to_response("verify_student/pay_and_verify.html", context)
Example #34
0
def static(path):
    """
    A template tag that returns the URL to a file
    using staticfiles' storage backend
    """
    return staticfiles_storage.url(path)
Example #35
0
def favicon_path(default=getattr(settings, 'FAVICON_PATH', 'images/favicon.ico')):
    """
    Django template tag that outputs the configured favicon:
    {% favicon_path %}
    """
    return staticfiles_storage.url(microsite.get_value('favicon_path', default))
Example #36
0
 def render_css(self, package, path):
     template_name = package.template_name or "pipeline/css.html"
     context = package.extra_context
     context.update({"type": guess_type(path, "text/css"), "url": staticfiles_storage.url(path)})
     return render_to_string(template_name, context)