def themed(self, name, theme):
        """
        Returns True if given asset override is provided by the given theme otherwise returns False.
        Args:
            name: asset name e.g. 'images/logo.png'
            theme: theme name e.g. 'red-theme', 'edx.org'

        Returns:
            True if given asset override is provided by the given theme otherwise returns False
        """
        if not is_comprehensive_theming_enabled():
            return False

        # in debug mode check static asset from within the project directory
        if settings.DEBUG:
            themes_location = get_theme_base_dir(theme, suppress_error=True)
            # Nothing can be themed if we don't have a theme location or required params.
            if not all((themes_location, theme, name)):
                return False

            themed_path = "/".join(
                [themes_location, theme,
                 get_project_root_name(), "static/"])
            name = name[1:] if name.startswith("/") else name
            path = safe_join(themed_path, name)
            return os.path.exists(path)
        # in live mode check static asset in the static files dir defined by "STATIC_ROOT" setting
        else:
            return self.exists(os.path.join(theme, name))
    def handle(self, *args, **options):
        """
        Handle compile_sass command.
        """
        system, theme_dirs, themes, force, debug = self.parse_arguments(
            *args, **options)
        themes = [theme.theme_dir_name for theme in themes]

        if options.get("themes",
                       None) and not is_comprehensive_theming_enabled():
            # log a warning message to let the user know that asset compilation for themes is skipped
            self.stdout.write(
                self.style.WARNING(
                    "Skipping theme asset compilation: enable theming to process themed assets"
                ), )

        call_task(
            'pavelib.assets.compile_sass',
            options={
                'system': system,
                'theme_dirs': theme_dirs,
                'themes': themes,
                'force': force,
                'debug': debug
            },
        )
Example #3
0
def run():
    """
    Executed during django startup
    """
    third_party_auth.patch()
    django_db_models_options.patch()

    # Comprehensive theming needs to be set up before django startup,
    # because modifying django template paths after startup has no effect.
    if is_comprehensive_theming_enabled():
        enable_theming()

    django.setup()

    autostartup()

    add_mimetypes()

    if settings.FEATURES.get('USE_CUSTOM_THEME', False):
        enable_theme()

    # In order to allow descriptors to use a handler url, we need to
    # monkey-patch the x_module library.
    # TODO: Remove this code when Runtimes are no longer created by modulestores
    # https://openedx.atlassian.net/wiki/display/PLAT/Convert+from+Storage-centric+runtimes+to+Application-centric+runtimes
    xmodule.x_module.descriptor_global_handler_url = cms.lib.xblock.runtime.handler_url
    xmodule.x_module.descriptor_global_local_resource_url = xblock_local_resource_url
Example #4
0
def run():
    """
    Executed during django startup
    """
    third_party_auth.patch()
    django_db_models_options.patch()

    # Comprehensive theming needs to be set up before django startup,
    # because modifying django template paths after startup has no effect.
    if is_comprehensive_theming_enabled():
        enable_theming()

    django.setup()

    autostartup()

    add_mimetypes()

    if settings.FEATURES.get("USE_CUSTOM_THEME", False):
        enable_theme()

    # In order to allow descriptors to use a handler url, we need to
    # monkey-patch the x_module library.
    # TODO: Remove this code when Runtimes are no longer created by modulestores
    # https://openedx.atlassian.net/wiki/display/PLAT/Convert+from+Storage-centric+runtimes+to+Application-centric+runtimes
    xmodule.x_module.descriptor_global_handler_url = cms.lib.xblock.runtime.handler_url
    xmodule.x_module.descriptor_global_local_resource_url = xblock_local_resource_url
Example #5
0
def run():
    """
    Executed during django startup

    NOTE: DO **NOT** add additional code to this method or this file! The Platform Team
          is moving all startup code to more standard locations using Django best practices.
    """
    django_db_models_options.patch()

    # Comprehensive theming needs to be set up before django startup,
    # because modifying django template paths after startup has no effect.
    if is_comprehensive_theming_enabled():
        enable_theming()

    django.setup()

    autostartup()

    add_mimetypes()

    # In order to allow descriptors to use a handler url, we need to
    # monkey-patch the x_module library.
    # TODO: Remove this code when Runtimes are no longer created by modulestores
    # https://openedx.atlassian.net/wiki/display/PLAT/Convert+from+Storage-centric+runtimes+to+Application-centric+runtimes
    xmodule.x_module.descriptor_global_handler_url = cms.lib.xblock.runtime.handler_url
    xmodule.x_module.descriptor_global_local_resource_url = xblock_local_resource_url

    # Set the version of docs that help-tokens will go to.
    settings.HELP_TOKENS_LANGUAGE_CODE = settings.LANGUAGE_CODE
    settings.HELP_TOKENS_VERSION = doc_version()

    # validate configurations on startup
    validate_cms_config(settings)
Example #6
0
def run():
    """
    Executed during django startup
    """
    django_db_models_options.patch()

    # Comprehensive theming needs to be set up before django startup,
    # because modifying django template paths after startup has no effect.
    if is_comprehensive_theming_enabled():
        enable_theming()

    django.setup()

    autostartup()

    add_mimetypes()

    # In order to allow descriptors to use a handler url, we need to
    # monkey-patch the x_module library.
    # TODO: Remove this code when Runtimes are no longer created by modulestores
    # https://openedx.atlassian.net/wiki/display/PLAT/Convert+from+Storage-centric+runtimes+to+Application-centric+runtimes
    xmodule.x_module.descriptor_global_handler_url = cms.lib.xblock.runtime.handler_url
    xmodule.x_module.descriptor_global_local_resource_url = xblock_local_resource_url

    # Set the version of docs that help-tokens will go to.
    settings.HELP_TOKENS_LANGUAGE_CODE = settings.LANGUAGE_CODE
    settings.HELP_TOKENS_VERSION = doc_version()

    # validate configurations on startup
    validate_cms_config(settings)
Example #7
0
    def themed(self, name, theme):
        """
        Returns True if given asset override is provided by the given theme otherwise returns False.
        Args:
            name: asset name e.g. 'images/logo.png'
            theme: theme name e.g. 'red-theme', 'edx.org'

        Returns:
            True if given asset override is provided by the given theme otherwise returns False
        """
        if not is_comprehensive_theming_enabled():
            return False

        # in debug mode check static asset from within the project directory
        if settings.DEBUG:
            themes_location = get_theme_base_dir(theme, suppress_error=True)
            # Nothing can be themed if we don't have a theme location or required params.
            if not all((themes_location, theme, name)):
                return False

            themed_path = "/".join([
                themes_location,
                theme,
                get_project_root_name(),
                "static/"
            ])
            name = name[1:] if name.startswith("/") else name
            path = safe_join(themed_path, name)
            return os.path.exists(path)
        # in live mode check static asset in the static files dir defined by "STATIC_ROOT" setting
        else:
            return self.exists(os.path.join(theme, name))
Example #8
0
def run():
    """
    Executed during django startup
    """
    django_db_models_options.patch()

    # To override the settings before executing the autostartup() for python-social-auth
    if settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH', False):
        enable_third_party_auth()

    # Comprehensive theming needs to be set up before django startup,
    # because modifying django template paths after startup has no effect.
    if is_comprehensive_theming_enabled():
        enable_theming()

    # We currently use 2 template rendering engines, mako and django_templates,
    # and one of them (django templates), requires the directories be added
    # before the django.setup().
    microsite.enable_microsites_pre_startup(log)

    django.setup()

    autostartup()

    add_mimetypes()

    # Mako requires the directories to be added after the django setup.
    microsite.enable_microsites(log)

    # Initialize Segment analytics module by setting the write_key.
    if settings.LMS_SEGMENT_KEY:
        analytics.write_key = settings.LMS_SEGMENT_KEY

    # register any dependency injections that we need to support in edx_proctoring
    # right now edx_proctoring is dependent on the openedx.core.djangoapps.credit
    if settings.FEATURES.get('ENABLE_SPECIAL_EXAMS'):
        # Import these here to avoid circular dependencies of the form:
        # edx-platform app --> DRF --> django translation --> edx-platform app
        from edx_proctoring.runtime import set_runtime_service
        from lms.djangoapps.instructor.services import InstructorService
        from openedx.core.djangoapps.credit.services import CreditService
        set_runtime_service('credit', CreditService())

        # register InstructorService (for deleting student attempts and user staff access roles)
        set_runtime_service('instructor', InstructorService())

    # In order to allow modules to use a handler url, we need to
    # monkey-patch the x_module library.
    # TODO: Remove this code when Runtimes are no longer created by modulestores
    # https://openedx.atlassian.net/wiki/display/PLAT/Convert+from+Storage-centric+runtimes+to+Application-centric+runtimes
    xmodule.x_module.descriptor_global_handler_url = lms_xblock.runtime.handler_url
    xmodule.x_module.descriptor_global_local_resource_url = lms_xblock.runtime.local_resource_url

    # Set the version of docs that help-tokens will go to.
    settings.HELP_TOKENS_LANGUAGE_CODE = settings.LANGUAGE_CODE
    settings.HELP_TOKENS_VERSION = doc_version()

    # validate configurations on startup
    validate_lms_config(settings)
Example #9
0
    def test_is_comprehensive_theming_enabled(self):
        """
        Tests to make sure the is_comprehensive_theming_enabled function works as expected.
        Here are different scenarios that we need to test

        1. Theming is enabled and there is a SiteTheme record.
            is_comprehensive_theming_enabled should return True
        2. Theming is enabled and there is no SiteTheme record.
            is_comprehensive_theming_enabled should return False
        3. Theming is disabled, there is a SiteTheme record for the current site.
            is_comprehensive_theming_enabled should return False
        4. Theming is disabled, there is no SiteTheme record.
            is_comprehensive_theming_enabled should return False
        """
        # Theming is enabled, there is a SiteTheme record
        with patch(
                "openedx.core.djangoapps.theming.helpers.current_request_has_associated_site_theme",
                Mock(return_value=True),
        ):
            self.assertTrue(theming_helpers.is_comprehensive_theming_enabled())

        # Theming is enabled, there is not a SiteTheme record
        with patch(
                "openedx.core.djangoapps.theming.helpers.current_request_has_associated_site_theme",
                Mock(return_value=False),
        ):
            self.assertTrue(theming_helpers.is_comprehensive_theming_enabled())

        with override_settings(ENABLE_COMPREHENSIVE_THEMING=False):
            # Theming is disabled, there is a SiteTheme record
            with patch(
                    "openedx.core.djangoapps.theming.helpers.current_request_has_associated_site_theme",
                    Mock(return_value=True),
            ):
                self.assertFalse(
                    theming_helpers.is_comprehensive_theming_enabled())

            # Theming is disabled, there is no SiteTheme record
            with patch(
                    "openedx.core.djangoapps.theming.helpers.current_request_has_associated_site_theme",
                    Mock(return_value=False),
            ):
                self.assertFalse(
                    theming_helpers.is_comprehensive_theming_enabled())
Example #10
0
def run():
    """
    Executed during django startup
    """
    third_party_auth.patch()
    django_db_models_options.patch()

    # To override the settings before executing the autostartup() for python-social-auth
    if settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH', False):
        enable_third_party_auth()

    # Comprehensive theming needs to be set up before django startup,
    # because modifying django template paths after startup has no effect.
    if is_comprehensive_theming_enabled():
        enable_theming()

    # We currently use 2 template rendering engines, mako and django_templates,
    # and one of them (django templates), requires the directories be added
    # before the django.setup().
    microsite.enable_microsites_pre_startup(log)

    django.setup()

    autostartup()

    add_mimetypes()

    # Mako requires the directories to be added after the django setup.
    microsite.enable_microsites(log)

    # Initialize Segment analytics module by setting the write_key.
    if settings.LMS_SEGMENT_KEY:
        analytics.write_key = settings.LMS_SEGMENT_KEY

    # register any dependency injections that we need to support in edx_proctoring
    # right now edx_proctoring is dependent on the openedx.core.djangoapps.credit
    if settings.FEATURES.get('ENABLE_SPECIAL_EXAMS'):
        # Import these here to avoid circular dependencies of the form:
        # edx-platform app --> DRF --> django translation --> edx-platform app
        from edx_proctoring.runtime import set_runtime_service
        from instructor.services import InstructorService
        from openedx.core.djangoapps.credit.services import CreditService
        set_runtime_service('credit', CreditService())

        # register InstructorService (for deleting student attempts and user staff access roles)
        set_runtime_service('instructor', InstructorService())

    # In order to allow modules to use a handler url, we need to
    # monkey-patch the x_module library.
    # TODO: Remove this code when Runtimes are no longer created by modulestores
    # https://openedx.atlassian.net/wiki/display/PLAT/Convert+from+Storage-centric+runtimes+to+Application-centric+runtimes
    xmodule.x_module.descriptor_global_handler_url = lms_xblock.runtime.handler_url
    xmodule.x_module.descriptor_global_local_resource_url = lms_xblock.runtime.local_resource_url

    # validate configurations on startup
    validate_lms_config(settings)
    def parse_arguments(*args, **options):  # pylint: disable=unused-argument
        """
        Parse and validate arguments for compile_sass command.

        Args:
            *args: Positional arguments passed to the update_assets command
            **options: optional arguments passed to the update_assets command
        Returns:
            A tuple containing parsed values for themes, system, source comments and output style.
            1. system (list): list of system names for whom to compile theme sass e.g. 'lms', 'cms'
            2. theme_dirs (list): list of Theme objects
            3. themes (list): list of Theme objects
            4. force (bool): Force full compilation
            5. debug (bool): Disable Sass compression
        """
        system = options.get("system", ALL_SYSTEMS)
        given_themes = options.get("themes", ["all"])
        theme_dirs = options.get("theme_dirs", None)

        force = options.get("force", True)
        debug = options.get("debug", True)

        if theme_dirs:
            available_themes = {}
            for theme_dir in theme_dirs:
                available_themes.update({t.theme_dir_name: t for t in get_themes(theme_dir)})
        else:
            theme_dirs = get_theme_base_dirs()
            available_themes = {t.theme_dir_name: t for t in get_themes()}

        if 'no' in given_themes or 'all' in given_themes:
            # Raise error if 'all' or 'no' is present and theme names are also given.
            if len(given_themes) > 1:
                raise CommandError("Invalid themes value, It must either be 'all' or 'no' or list of themes.")
        # Raise error if any of the given theme name is invalid
        # (theme name would be invalid if it does not exist in themes directory)
        elif (not set(given_themes).issubset(available_themes.keys())) and is_comprehensive_theming_enabled():
            raise CommandError(
                "Given themes '{themes}' do not exist inside any of the theme directories '{theme_dirs}'".format(
                    themes=", ".join(set(given_themes) - set(available_themes.keys())),
                    theme_dirs=theme_dirs,
                ),
            )

        if "all" in given_themes:
            themes = list(available_themes.itervalues())
        elif "no" in given_themes:
            themes = []
        else:
            # convert theme names to Theme objects, this will remove all themes if theming is disabled
            themes = [available_themes.get(theme) for theme in given_themes if theme in available_themes]

        return system, theme_dirs, themes, force, debug
Example #12
0
    def parse_arguments(*args, **options):  # pylint: disable=unused-argument
        """
        Parse and validate arguments for compile_sass command.

        Args:
            *args: Positional arguments passed to the update_assets command
            **options: optional arguments passed to the update_assets command
        Returns:
            A tuple containing parsed values for themes, system, source comments and output style.
            1. system (list): list of system names for whom to compile theme sass e.g. 'lms', 'cms'
            2. theme_dirs (list): list of Theme objects
            3. themes (list): list of Theme objects
            4. force (bool): Force full compilation
            5. debug (bool): Disable Sass compression
        """
        system = options.get("system", ALL_SYSTEMS)
        given_themes = options.get("themes", ["all"])
        theme_dirs = options.get("theme_dirs", None)

        force = options.get("force", True)
        debug = options.get("debug", True)

        if theme_dirs:
            available_themes = {}
            for theme_dir in theme_dirs:
                available_themes.update({t.theme_dir_name: t for t in get_themes([theme_dir])})
        else:
            theme_dirs = get_theme_base_dirs()
            available_themes = {t.theme_dir_name: t for t in get_themes()}

        if 'no' in given_themes or 'all' in given_themes:
            # Raise error if 'all' or 'no' is present and theme names are also given.
            if len(given_themes) > 1:
                raise CommandError("Invalid themes value, It must either be 'all' or 'no' or list of themes.")
        # Raise error if any of the given theme name is invalid
        # (theme name would be invalid if it does not exist in themes directory)
        elif (not set(given_themes).issubset(list(available_themes.keys()))) and is_comprehensive_theming_enabled():
            raise CommandError(
                "Given themes '{themes}' do not exist inside any of the theme directories '{theme_dirs}'".format(
                    themes=", ".join(set(given_themes) - set(available_themes.keys())),
                    theme_dirs=theme_dirs,
                ),
            )

        if "all" in given_themes:
            themes = list(available_themes.values())
        elif "no" in given_themes:
            themes = []
        else:
            # convert theme names to Theme objects, this will remove all themes if theming is disabled
            themes = [available_themes.get(theme) for theme in given_themes if theme in available_themes]

        return system, theme_dirs, themes, force, debug
    def handle(self, *args, **options):
        """
        Handle compile_sass command.
        """
        system, theme_dirs, themes, force, debug = self.parse_arguments(*args, **options)
        themes = [theme.theme_dir_name for theme in themes]

        if options.get("themes", None) and not is_comprehensive_theming_enabled():
            # log a warning message to let the user know that asset compilation for themes is skipped
            self.stdout.write(
                self.style.WARNING(  # pylint: disable=no-member
                    "Skipping theme asset compilation: enable theming to process themed assets"
                ),
            )

        call_task(
            'pavelib.assets.compile_sass',
            options={'system': system, 'theme_dirs': theme_dirs, 'themes': themes, 'force': force, 'debug': debug},
        )
Example #14
0
def run():
    """
    Executed during django startup
    """
    django_db_models_options.patch()

    # Comprehensive theming needs to be set up before django startup,
    # because modifying django template paths after startup has no effect.
    if is_comprehensive_theming_enabled():
        enable_theming()

    django.setup()

    autostartup()

    add_mimetypes()

    if settings.FEATURES.get('ENABLE_NOTIFICATIONS', False):
        startup_notification_subsystem()

    if settings.FEATURES.get('EDX_SOLUTIONS_API', False) and \
            settings.FEATURES.get('DISABLE_SOLUTIONS_APPS_SIGNALS', False):
        disable_solutions_apps_signals()

    # In order to allow descriptors to use a handler url, we need to
    # monkey-patch the x_module library.
    # TODO: Remove this code when Runtimes are no longer created by modulestores
    # https://openedx.atlassian.net/wiki/display/PLAT/Convert+from+Storage-centric+runtimes+to+Application-centric+runtimes
    xmodule.x_module.descriptor_global_handler_url = cms.lib.xblock.runtime.handler_url
    xmodule.x_module.descriptor_global_local_resource_url = xblock_local_resource_url

    # Set the version of docs that help-tokens will go to.
    settings.HELP_TOKENS_LANGUAGE_CODE = settings.LANGUAGE_CODE
    settings.HELP_TOKENS_VERSION = doc_version()

    # validate configurations on startup
    validate_cms_config(settings)
Example #15
0
    def test_is_comprehensive_theming_enabled(self):
        """
        Tests to make sure the is_comprehensive_theming_enabled function works as expected.
        Here are different scenarios that we need to test

        1. Theming is enabled, there is a SiteTheme record and microsite configuration for the current site.
            is_comprehensive_theming_enabled should return True
        2. Theming is enabled, there is no SiteTheme record but there is microsite configuration for the current site.
            is_comprehensive_theming_enabled should return False
        3. Theming is enabled, there is neither a SiteTheme record nor microsite configuration for the current site.
            is_comprehensive_theming_enabled should return True
        4. Theming is disabled, there is a SiteTheme record and microsite configuration for the current site.
            is_comprehensive_theming_enabled should return False
        5. Theming is disabled, there is no SiteTheme record but there is microsite configuration for the current site.
            is_comprehensive_theming_enabled should return False
        6. Theming is disabled, there is neither a SiteTheme record nor microsite configuration for the current site.
            is_comprehensive_theming_enabled should return False
        """
        # Theming is enabled, there is a SiteTheme record and microsite configuration for the current site
        with patch(
            "openedx.core.djangoapps.theming.helpers.current_request_has_associated_site_theme",
            Mock(return_value=True),
        ):
            with patch(
                "openedx.core.djangoapps.theming.helpers.microsite.is_request_in_microsite",
                Mock(return_value=True),
            ):
                self.assertTrue(theming_helpers.is_comprehensive_theming_enabled())

        # Theming is enabled, there is no SiteTheme record but there is microsite configuration for the current site.
        with patch(
            "openedx.core.djangoapps.theming.helpers.current_request_has_associated_site_theme",
            Mock(return_value=False),
        ):
            with patch(
                "openedx.core.djangoapps.theming.helpers.microsite.is_request_in_microsite",
                Mock(return_value=True),
            ):
                self.assertFalse(theming_helpers.is_comprehensive_theming_enabled())

        # Theming is enabled, there is neither a SiteTheme record nor microsite configuration for the current site.
        with patch(
            "openedx.core.djangoapps.theming.helpers.current_request_has_associated_site_theme",
            Mock(return_value=False),
        ):
            with patch(
                "openedx.core.djangoapps.theming.helpers.microsite.is_request_in_microsite",
                Mock(return_value=False),
            ):
                self.assertTrue(theming_helpers.is_comprehensive_theming_enabled())

        with override_settings(ENABLE_COMPREHENSIVE_THEMING=False):
            # Theming is disabled, there is a SiteTheme record and microsite configuration for the current site.
            with patch(
                "openedx.core.djangoapps.theming.helpers.current_request_has_associated_site_theme",
                Mock(return_value=True),
            ):
                with patch(
                    "openedx.core.djangoapps.theming.helpers.microsite.is_request_in_microsite",
                    Mock(return_value=True),
                ):
                    self.assertFalse(theming_helpers.is_comprehensive_theming_enabled())

            # Theming is disabled, there is no SiteTheme record but
            # there is microsite configuration for the current site.
            with patch(
                "openedx.core.djangoapps.theming.helpers.current_request_has_associated_site_theme",
                Mock(return_value=False),
            ):
                with patch(
                    "openedx.core.djangoapps.theming.helpers.microsite.is_request_in_microsite",
                    Mock(return_value=True),
                ):
                    self.assertFalse(theming_helpers.is_comprehensive_theming_enabled())

            # Theming is disabled, there is neither a SiteTheme record nor microsite configuration for the current site.
            with patch(
                "openedx.core.djangoapps.theming.helpers.current_request_has_associated_site_theme",
                Mock(return_value=False),
            ):
                with patch(
                    "openedx.core.djangoapps.theming.helpers.microsite.is_request_in_microsite",
                    Mock(return_value=False),
                ):
                    self.assertFalse(theming_helpers.is_comprehensive_theming_enabled())