def get_alt_src_langs(request, profile, translation_project): language = translation_project.language project = translation_project.project source_language = project.source_language langs = profile.alt_src_langs.exclude(id__in=(language.id, source_language.id)).filter( translationproject__project=project ) if not profile.alt_src_langs.count(): from pootle_language.models import Language accept = request.META.get("HTTP_ACCEPT_LANGUAGE", "") for accept_lang, unused in parse_accept_lang_header(accept): if accept_lang == "*": continue normalized = to_locale(data.normalize_code(data.simplify_to_common(accept_lang))) code = to_locale(accept_lang) if normalized in ("en", "en_US", source_language.code, language.code) or code in ( "en", "en_US", source_language.code, language.code, ): continue langs = Language.objects.filter(code__in=(normalized, code), translationproject__project=project) if langs.count(): break return langs
def matches(self, other, ignore_dialect=True): return ( (to_locale(self.code) == to_locale(other.code)) or (ignore_dialect and (self.base_code == (other.base_code))))
def perform_login(request, user, redirect_url=None, signup=False, **kwargs): """ Keyword arguments: signup -- Indicates whether or not sending the email is essential (during signup), or if it can be skipped (e.g. in case email verification is optional and we are only logging in). """ # not is_active: social users are redirected to a template # local users are stopped due to form validation checking is_active # assert user.is_active # the user have a verified email has_verified_email = EmailAddress.objects.filter(user=user, verified=True).exists() if not has_verified_email: email = user.email set_user_message(request, messages.WARNING, 'confirmation', 'please check your email to active your account ' + email) send_email_confirmation(request, user, signup=signup) return render(request, "tverification_sent.html", {"email": email}) else : # authentication backend, but I fail to see any added benefit # whereas I do see the downsides (having to bother the integrator # to set up authentication backend in settings.py if not hasattr(user, 'backend'): user.backend = "django.contrib.auth.backends.ModelBackend" login(request, user) to_locale(user.profile.lang.code or get_language()) return HttpResponseRedirect(get_login_redirect_url(request))
def javascript_catalog(request, domain='djangojs', packages=None): """ Returns the selected language catalog as a javascript library. Receives the list of packages to check for translations in the packages parameter either from an infodict or as a +-delimited string from the request. Default is 'django.conf'. Additionally you can override the gettext domain for this view, but usually you don't want to do that, as JavaScript messages go to the djangojs domain. But this might be needed if you deliver your JavaScript source from Django templates. """ locale = to_locale(get_language()) if request.GET and 'language' in request.GET: if check_for_language(request.GET['language']): locale = to_locale(request.GET['language']) if packages is None: packages = ['django.conf'] if isinstance(packages, six.string_types): packages = packages.split('+') catalog, plural = get_javascript_catalog(locale, domain, packages) return render_javascript_catalog(catalog, plural)
def javascript_catalog(request, domain='djangojs', packages=None): """ Returns the selected language catalog as a javascript library. Receives the list of packages to check for translations in the packages parameter either from an infodict or as a +-delimited string from the request. Default is 'django.conf'. Additionally you can override the gettext domain for this view, but usually you don't want to do that, as JavaScript messages go to the djangojs domain. But this might be needed if you deliver your JavaScript source from Django templates. """ locale = to_locale(get_language()) if request.GET and 'language' in request.GET: if check_for_language(request.GET['language']): locale = to_locale(request.GET['language']) if packages is None: packages = ['django.conf'] if isinstance(packages, six.string_types): packages = packages.split('+') catalog = None try: catalog, plural = get_javascript_catalog(locale, domain, packages) except TranslationError as ex: # We know how to handle one specific type of error - so let's do # something useful there. if re.match(r'.*duplicate message definition', ex.args[0]): return render_duplicate_error_js(ex.args[0]) raise Exception(ex.msg) return render_javascript_catalog(catalog, plural)
def get_alt_src_langs(request, user, translation_project): if request.user.is_anonymous: return language = translation_project.language project = translation_project.project source_language = project.source_language langs = list( user.alt_src_langs.exclude( id__in=(language.id, source_language.id) ).filter( translationproject__project=project)) if langs: return langs accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '') for accept_lang, __ in parse_accept_lang_header(accept): if accept_lang == '*': continue normalized = to_locale( data.normalize_code( data.simplify_to_common(accept_lang))) code = to_locale(accept_lang) is_source_lang = any( langcode in ('en', 'en_US', source_language.code, language.code) for langcode in [code, normalized]) if is_source_lang: continue langs = list( Language.objects.filter( code__in=(normalized, code), translationproject__project=project)) if langs: return langs
def test_to_locale(self): """ Tests the to_locale function and the special case of Serbian Latin (refs #12230 and r11299) """ self.assertEqual(to_locale("en-us"), "en_US") self.assertEqual(to_locale("sr-lat"), "sr_Lat")
def test_to_locale(self): """ Tests the to_locale function and the special case of Serbian Latin (refs #12230 and r11299) """ self.assertEqual(to_locale('en-us'), 'en_US') self.assertEqual(to_locale('sr-lat'), 'sr_Lat')
def get_alt_src_langs(request, user, translation_project): language = translation_project.language project = translation_project.project source_language = project.source_language langs = user.alt_src_langs.exclude( id__in=(language.id, source_language.id) ).filter(translationproject__project=project) if not user.alt_src_langs.count(): from pootle_language.models import Language accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '') for accept_lang, unused in parse_accept_lang_header(accept): if accept_lang == '*': continue simplified = data.simplify_to_common(accept_lang) normalized = to_locale(data.normalize_code(simplified)) code = to_locale(accept_lang) if (normalized in ('en', 'en_US', source_language.code, language.code) or code in ('en', 'en_US', source_language.code, language.code)): continue langs = Language.objects.filter( code__in=(normalized, code), translationproject__project=project, ) if langs.count(): break return langs
def process_request(self, request): # Under Windows, locale names are different and setlocale() # with regular locale names will fail; # so just set the default locale and quit early if os.name == 'nt': locale.setlocale(locale.LC_ALL, '') return #FIXME: some languages like arabic don't have a language only # locale for no good reason. we need a function to pick default # locale for these lang = translation.to_locale(translation.get_language()) try: if lang == 'tr' or lang.startswith('tr_'): raise ValueError("Turkish locale broken due to changed meaning of lower()") locale.setlocale(locale.LC_ALL, (lang, 'UTF-8')) except: logging.debug('Failed to set locale to %s; using Pootle default', lang) lang = translation.to_locale(settings.LANGUAGE_CODE) try: if lang == 'tr' or lang.startswith('tr_'): raise ValueError("Turkish locale broken due to changed meaning of lower()") locale.setlocale(locale.LC_ALL, (lang, 'UTF-8')) except: logging.debug('Failed to set locale to Pootle default (%s); loading system default', lang) locale.setlocale(locale.LC_ALL, '')
def get_locale_conv(loc=None): if loc is None: loc = to_locale(get_language()) startloc = loc # '-' is a language delimiter, not a locale, but people often mess that up if loc.find("-") > -1: loc = to_locale(loc) try: # log.debug('setting locale: %s', loc.encode('utf-8')) locale.setlocale(locale.LC_ALL, locale.normalize(loc)) return locale.localeconv() except (locale.Error, ValueError): # darn, try a different path pos = loc.find("_") if pos > -1: loc = loc[:pos] return get_locale_conv(loc) else: loc = to_locale(settings.LANGUAGE_CODE) if loc != startloc and loc[: loc.find("_")] != startloc: log.warn( u"Cannot set locale to '%s'. Using default locale '%s'.", startloc.encode("utf-8"), loc.encode("utf-8"), ) return get_locale_conv(loc) else: log.fatal(u"Cannot set locale to default locale '%s'. Something is misconfigured.", loc.encode("utf-8")) raise ImproperlyConfigured("bad settings.LANGUAGE_CODE")
def _get_format(): lang = translation.get_language() try: locale = Locale(translation.to_locale(lang)) except UnknownLocaleError: locale = Locale(translation.to_locale(settings.BABEL_FALLBACK.get( lang, 'en-US'))) return Format(locale)
def djangular_catalog(request): locale = to_locale(get_language_from_request(request)) if request.GET and 'lang' in request.GET: if check_for_language(request.GET['lang']): locale = to_locale(request.GET['lang']) catalog, plural = get_javascript_catalog(locale, 'djangular', ['django.conf']) return JsonResponse(catalog)
def render_to_fragment(self, request, course_id, user_access, **kwargs): """ Renders a course message fragment for the specified course. """ course_key = CourseKey.from_string(course_id) course = get_course_with_access(request.user, 'load', course_key) # Get time until the start date, if already started, or no start date, value will be zero or negative now = datetime.now(UTC) already_started = course.start and now > course.start days_until_start_string = "started" if already_started else format_timedelta( course.start - now, locale=to_locale(get_language()) ) course_start_data = { 'course_start_date': format_date(course.start, locale=to_locale(get_language())), 'already_started': already_started, 'days_until_start_string': days_until_start_string } # Register the course home messages to be loaded on the page _register_course_home_messages(request, course, user_access, course_start_data) # Register course date alerts for course_date_block in get_course_date_blocks(course, request.user): course_date_block.register_alerts(request, course) # Register a course goal message, if appropriate # Only show the set course goal message for enrolled, unverified # users that have not yet set a goal in a course that allows for # verified statuses. user_goal = get_course_goal(auth.get_user(request), course_key) is_already_verified = CourseEnrollment.is_enrolled_as_verified(request.user, course_key) if has_course_goal_permission(request, course_id, user_access) and not is_already_verified and not user_goal: _register_course_goal_message(request, course) # Grab the relevant messages course_home_messages = list(CourseHomeMessages.user_messages(request)) # Pass in the url used to set a course goal goal_api_url = get_goal_api_url(request) # Grab the logo image_src = 'course_experience/images/home_message_author.png' context = { 'course_home_messages': course_home_messages, 'goal_api_url': goal_api_url, 'image_src': image_src, 'course_id': course_id, 'username': request.user.username, } html = render_to_string('course_experience/course-messages-fragment.html', context) return Fragment(html)
def locale_html(translatedfield): """HTML attributes for languages different than the site language""" if not translatedfield: return "" site_locale = translation.to_locale(translation.get_language()) locale = translation.to_locale(translatedfield.locale) if locale == site_locale: return "" else: rtl_locales = map(translation.to_locale, settings.RTL_LANGUAGES) textdir = "rtl" if locale in rtl_locales else "ltr" return jinja2.Markup(' lang="%s" dir="%s"' % (jinja2.escape(translatedfield.locale), textdir))
def process_request(self, request): #FIXME: some languages like arabic don't have a language only # locale for no good reason. we need a function to pick default # locale for these lang = translation.to_locale(translation.get_language()) try: locale.setlocale(locale.LC_ALL, (lang, 'UTF-8')) except: logging.debug('failed to set locale to %s; using Pootle default', lang) lang = translation.to_locale(settings.LANGUAGE_CODE) try: locale.setlocale(locale.LC_ALL, (lang, 'UTF-8')) except: logging.debug('failed to set locale to pootle default (%s); loading system default', lang) locale.setlocale(locale.LC_ALL, '')
def get_locale_data(): language = get_language() if not language: language = settings.LANGUAGE_CODE locale_code = to_locale(language) locale = None try: locale = Locale.parse(locale_code) except (ValueError, UnknownLocaleError): # Invalid format or unknown locale # Fallback to the default language language = settings.LANGUAGE_CODE locale_code = to_locale(language) locale = Locale.parse(locale_code) return locale, locale_code
def lang_choices(): """generated locale choices for drop down lists in forms""" choices = [] for code, name in supported_langs(): name = data.tr_lang(translation.to_locale('en'))(name) tr_name = data.tr_lang(translation.to_locale(code))(name) if tr_name != name: # We have to use the LRO (left-to-right override) to ensure that # brackets in the English part of the name is rendered correctly # in an RTL layout like Arabic. We can't use markup because this # is used inside an option tag. name = u"%s | \u202d%s" % (tr_name, name) choices.append((code, name)) choices.sort(cmp=locale.strcoll, key=lambda choice: unicode(choice[1])) return choices
def set_user_language(user): try: lang = user.get_profile().language if lang: language = translation.to_locale(lang) translation.activate(language) else: # if user has no language and current is not default, then set the default # this is to avoid using the last selected language if not translation.get_language() == settings.LANGUAGE_CODE: language = translation.to_locale(settings.LANGUAGE_CODE) translation.activate(language) except: # in case of fail do nothing pass
def get_locale_from_lang(lang): """Pass in a language (u'en-US') get back a Locale object courtesy of Babel. Use this to figure out currencies, bidi, names, etc.""" # Special fake language can just act like English for formatting and such if not lang or lang == 'dbg': lang = 'en' return Locale(translation.to_locale(lang))
def InitBlogData(): global g_blog OptionSet.setValue('PluginActive',[u'googleAnalytics', u'wordpress', u'sys_plugin']) g_blog = Blog(key_name = 'default') g_blog.domain=os.environ['HTTP_HOST'] g_blog.baseurl="http://"+g_blog.domain g_blog.feedurl=g_blog.baseurl+"/feed" g_blog.admin_essential = False if os.environ.has_key('HTTP_ACCEPT_LANGUAGE'): lang=os.environ['HTTP_ACCEPT_LANGUAGE'].split(',')[0] from django.utils.translation import activate,to_locale g_blog.language=to_locale(lang) g_blog.admin_essential=False from django.conf import settings settings._target = None activate(g_blog.language) g_blog.save() entry=Entry(title="Hello world!".decode('utf8')) entry.content='<p>Welcome to micolog %s. This is your first post. Edit or delete it, then start blogging!</p>'%g_blog.version entry.save(True) link=Link(href='http://xuming.net',linktext="Xuming's blog".decode('utf8')) link.put() link=Link(href='http://eric.cloud-mes.com/',linktext="Eric Guo's blog".decode('utf8')) link.put() return g_blog
def handle(self, *args, **options): for module in options['module']: for domain in DOMAINS: for language in options['language']: locale = translation.to_locale(language) pofile = POFILE.format(module=module, locale=locale, domain=domain) pofile_dir = os.path.dirname(pofile) if not os.path.exists(pofile_dir): os.makedirs(pofile_dir) new_po = requests.get((POFILE_URL).format( language=language, project=options['project'], branch=options['branch'], module=module, domain=domain)) # Ensure to use UTF-8 encoding new_po.encoding = 'utf-8' with open(pofile, 'w+') as f: f.write(new_po.text.encode('utf-8'))
def _switch_locale(self): if self.source_locale: lang = self.source_locale else: lang = self.addon.default_locale tower.activate(lang) return Locale(translation.to_locale(lang))
def _format_date(self): """ Return this block's date in a human-readable format. If the date is None, returns the empty string. """ if self.date is None: return '' locale = to_locale(get_language()) delta = self.date - datetime.now(utc) try: relative_date = format_timedelta(delta, locale=locale) # Babel doesn't have translations for Esperanto, so we get # a KeyError when testing translations with # ?preview-lang=eo. This should not happen with any other # languages. See https://github.com/python-babel/babel/issues/107 except KeyError: relative_date = format_timedelta(delta) date_has_passed = delta.days < 0 # Translators: 'absolute' is a date such as "Jan 01, # 2020". 'relative' is a fuzzy description of the time until # 'absolute'. For example, 'absolute' might be "Jan 01, 2020", # and if today were December 5th, 2020, 'relative' would be "1 # month". date_format = _(u"{relative} ago - {absolute}") if date_has_passed else _(u"in {relative} - {absolute}") return date_format.format( relative=relative_date, absolute=self.date.astimezone(self.time_zone).strftime(self.date_format.encode('utf-8')).decode('utf-8'), )
def InitBlogData(self): OptionSet.setValue('PluginActive',[u'googleAnalytics', u'wordpress', u'sys_plugin']) self.domain=os.environ['HTTP_HOST'] self.feedurl=self.baseurl+"/feed" if os.environ.has_key('HTTP_ACCEPT_LANGUAGE'): lang=os.environ['HTTP_ACCEPT_LANGUAGE'].split(',')[0] else: lang='zh-CN' from django.utils.translation import to_locale self.language=to_locale(lang) self.put_async() entry=Entry(title="Hello world!".decode('utf8')) entry.content='<p>Welcome to micolog %s. This is your first post. Edit or delete it, then start blogging!</p>'%self.version entry.published=True entry.put_async() link=Link() link.populate(href='http://xuming.net',linktext="Xuming's blog".decode('utf8')) link.put_async() link=Link() link.populate(href='http://eric.cloud-mes.com/',linktext="Eric Guo's blog".decode('utf8')) link.put_async()
def get_context(self): """Return the template context used to render this summary block.""" date = '' if self.date is not None: # Translators: relative_date is a fuzzy description of the # time from now until absolute_date. For example, # absolute_date might be "Jan 01, 2020", and if today were # December 5th, 2020, relative_date would be "1 month". locale = to_locale(get_language()) try: relative_date = format_timedelta(self.date - datetime.now(pytz.UTC), locale=locale) # Babel doesn't have translations for Esperanto, so we get # a KeyError when testing translations with # ?preview-lang=eo. This should not happen with any other # languages. See https://github.com/python-babel/babel/issues/107 except KeyError: relative_date = format_timedelta(self.date - datetime.now(pytz.UTC)) date = _("in {relative_date} - {absolute_date}").format( relative_date=relative_date, absolute_date=self.date.strftime(self.date_format), ) return { 'title': self.title, 'date': date, 'description': self.description, 'css_class': self.css_class, 'link': self.link, 'link_text': self.link_text, }
def __init__(self, block=None): """ Attempt to load an XBlock-specific GNU gettext translator using the XBlock's own domain translation catalog, currently expected to be found at: <xblock_root>/conf/locale/<language>/LC_MESSAGES/<domain>.po|mo If we can't locate the domain translation catalog then we fall-back onto django.utils.translation, which will point to the system's own domain translation catalog This effectively achieves translations by coincidence for an XBlock which does not provide its own dedicated translation catalog along with its implementation. """ self.translator = django.utils.translation if block: xblock_class = getattr(block, 'unmixed_class', block.__class__) xblock_resource = xblock_class.__module__ xblock_locale_dir = '/translations' xblock_locale_path = resource_filename(xblock_resource, xblock_locale_dir) xblock_domain = 'text' selected_language = get_language() try: self.translator = gettext.translation( xblock_domain, xblock_locale_path, [to_locale(selected_language if selected_language else settings.LANGUAGE_CODE)] ) except IOError: # Fall back to the default Django translator if the XBlock translator is not found. pass
def get_context_data(self, **kwargs): context = super(MapDetailMixin, self).get_context_data(**kwargs) properties = { 'urls': _urls_for_js(), 'tilelayers': self.get_tilelayers(), 'allowEdit': self.is_edit_allowed(), 'default_iconUrl': "%sstorage/src/img/marker.png" % settings.STATIC_URL, # noqa 'storage_id': self.get_storage_id(), 'licences': dict((l.name, l.json) for l in Licence.objects.all()), } if self.get_short_url(): properties['shortUrl'] = self.get_short_url() if settings.USE_I18N: locale = settings.LANGUAGE_CODE # Check attr in case the middleware is not active if hasattr(self.request, "LANGUAGE_CODE"): locale = self.request.LANGUAGE_CODE locale = to_locale(locale) properties['locale'] = locale context['locale'] = locale map_settings = self.get_geojson() if "properties" not in map_settings: map_settings['properties'] = {} map_settings['properties'].update(properties) map_settings['properties']['datalayers'] = self.get_datalayers() context['map_settings'] = json.dumps(map_settings, indent=settings.DEBUG) return context
def get_context_data(self, **kwargs): context = super(MapDetailMixin, self).get_context_data(**kwargs) properties = {} properties['datalayers'] = self.get_datalayers() properties['urls'] = _urls_for_js() properties['tilelayers'] = self.get_tilelayers() if self.get_short_url(): properties['shortUrl'] = self.get_short_url() if settings.USE_I18N: locale = settings.LANGUAGE_CODE # Check attr in case the middleware is not active if hasattr(self.request, "LANGUAGE_CODE"): locale = self.request.LANGUAGE_CODE locale = to_locale(locale) properties['locale'] = locale context['locale'] = locale properties['allowEdit'] = self.is_edit_allowed() properties["default_iconUrl"] = "%sstorage/src/img/marker.png" % settings.STATIC_URL properties['storage_id'] = self.get_storage_id() properties['licences'] = dict((l.name, l.json) for l in Licence.objects.all()) # if properties['locateOnLoad']: # properties['locate'] = { # 'setView': True, # 'enableHighAccuracy': True, # 'timeout': 3000 # } map_settings = self.get_geojson() if not "properties" in map_settings: map_settings['properties'] = {} map_settings['properties'].update(properties) context['map_settings'] = simplejson.dumps(map_settings, indent=settings.DEBUG) return context
def iter_format_modules(lang, format_module_path=None): """ Does the heavy lifting of finding format modules. """ if not check_for_language(lang): return if format_module_path is None: format_module_path = settings.FORMAT_MODULE_PATH format_locations = [] if format_module_path: if isinstance(format_module_path, six.string_types): format_module_path = [format_module_path] for path in format_module_path: format_locations.append(path + '.%s') format_locations.append('django.conf.locale.%s') locale = to_locale(lang) locales = [locale] if '_' in locale: locales.append(locale.split('_')[0]) for location in format_locations: for loc in locales: try: yield import_module('%s.formats' % (location % loc)) except ImportError: pass
def render_to_fragment(self, request, course_id, user_access, **kwargs): """ Renders a course message fragment for the specified course. """ course_key = CourseKey.from_string(course_id) course = get_course_with_access(request.user, 'load', course_key) # Get time until the start date, if already started, or no start date, value will be zero or negative now = datetime.now(UTC) already_started = course.start and now > course.start days_until_start_string = "started" if already_started else format_timedelta( course.start - now, locale=to_locale(get_language())) course_start_data = { 'course_start_date': format_date(course.start, locale=to_locale(get_language())), 'already_started': already_started, 'days_until_start_string': days_until_start_string } # Register the course home messages to be loaded on the page _register_course_home_messages(request, course, user_access, course_start_data) # Register course date alerts for course_date_block in get_course_date_blocks(course, request.user): course_date_block.register_alerts(request, course) # Register a course goal message, if appropriate # Only show the set course goal message for enrolled, unverified # users that have not yet set a goal in a course that allows for # verified statuses. user_goal = get_course_goal(auth.get_user(request), course_key) is_already_verified = CourseEnrollment.is_enrolled_as_verified( request.user, course_key) if has_course_goal_permission( request, course_id, user_access) and not is_already_verified and not user_goal: _register_course_goal_message(request, course) # Grab the relevant messages course_home_messages = list(CourseHomeMessages.user_messages(request)) # Pass in the url used to set a course goal goal_api_url = get_goal_api_url(request) # Grab the logo image_src = 'course_experience/images/home_message_author.png' context = { 'course_home_messages': course_home_messages, 'goal_api_url': goal_api_url, 'image_src': image_src, 'course_id': course_id, 'username': request.user.username, } html = render_to_string( 'course_experience/course-messages-fragment.html', context) return Fragment(html)
def date_filter(value): return format_date( value.astimezone(get_current_timezone()), format='full', locale=to_locale(get_language()), )
def locale(request): return {'LOCALE': to_locale(get_language())}
def akismet_lang(self, language): """ Convert a Django language name to an Akismet blog_lang identifier. E.g.: "en-US" to "en_us" """ return translation.to_locale(language).lower()
def __init__(self, video, statement, lti_user): """Compute a valid xapi satement. Parameters ---------- video : Type[.models/videos] The video object used in the xAPI statement statement : dictionary Statement containing base information to send to the LRS An example of expected statement: { "verb": { "id": "http://adlnet.gov/expapi/verbs/initialized", "display": { "en-US": "initialized" } }, "context": { "extensions": { "https://w3id.org/xapi/video/extensions/volume": 1, "https://w3id.org/xapi/video/extensions/video-playback-size": "640x264", } } } lti_user : Type[lti.LTIUser] Object representing data stored in the JWT Token and related to the user authenticated with LTI """ try: user_id = lti_user.user_id except AttributeError: user_id = lti_user.session_id homepage = video.playlist.consumer_site.domain if re.match(r"^http(s?):\/\/.*", homepage) is None: homepage = f"http://{homepage}" if "id" not in statement: statement["id"] = str(uuid.uuid4()) statement["timestamp"] = timezone.now().isoformat() statement["context"].update({ "contextActivities": { "category": [{ "id": "https://w3id.org/xapi/video" }] } }) statement["actor"] = { "objectType": "Agent", "account": { "name": user_id, "homePage": homepage }, } statement["object"] = { "definition": { "type": "https://w3id.org/xapi/video/activity-type/video", "name": { to_locale(settings.LANGUAGE_CODE).replace("_", "-"): video.title }, }, "id": "uuid://{id}".format(id=str(video.id)), "objectType": "Activity", } object_extensions = {} if lti_user.course.get("school_name") is not None: object_extensions[ "https://w3id.org/xapi/acrossx/extensions/school"] = lti_user.course[ "school_name"] if lti_user.course.get("course_name") is not None: object_extensions[ "http://adlnet.gov/expapi/activities/course"] = lti_user.course[ "course_name"] if lti_user.course.get("course_run") is not None: object_extensions[ "http://adlnet.gov/expapi/activities/module"] = lti_user.course[ "course_run"] if object_extensions: statement["object"]["definition"]["extensions"] = object_extensions self.statement = statement
def render(self, context): args = [arg.resolve(context) for arg in self.args] kwargs = dict((smart_text(k, 'ascii'), v.resolve(context)) for k, v in self.kwargs.items()) # If user didn't specify the language in the template tag arguments get # language from Django settings if 'language' not in kwargs: kwargs.update({'language': get_language()}) # If user didn't specify the locale in the template tag, guess it from # the language if 'locale' not in kwargs: kwargs.update({'locale': to_locale(kwargs['language'])}) # Push 'social_widgets_javascript' list into context. We use that list # to keep track of loaded external JavaScript files and don't load # the same file multiple times in one page when there are multiple # widgets from the same social network. if 'social_widgets_javascript' not in context.dicts[0]: context.dicts[0]['social_widgets_javascript'] = [] kwargs.update({ 'social_widgets_javascript': context.dicts[0]['social_widgets_javascript'][:] }) try: template_path = args[0] except IndexError: return '' template = 'social_widgets/%s' % template_path # We assume that if there are multiple widget templates in directory # (for example in there are 5 templates in "social_widgets/pinterest" # directory) then they are all using the same external JavaScript code # for loading and initializing. We want to load this JavaScript code # only once when the first widget is rendered, so we use directory name # to track if code already had been used. Widget template must also # support this feature by checking. # # {% if not widget_service in social_widgets_javascript #} # <!-- Code to load external JavaScript file. --> # {% endif %} # # Alternatively you can disable external JavaScript loading by # specifying noscript=True in template tags parameters. try: widget_service = template_path.split('/')[0] kwargs['widget_service'] = widget_service if widget_service \ not in context.dicts[0]['social_widgets_javascript'] and \ not kwargs.get('noscript', False): context.dicts[0]['social_widgets_javascript']\ .append(widget_service) except IndexError: pass try: t = loader.get_template(template) return t.render(Context(kwargs)) except TemplateDoesNotExist: return ''
def get_language_from_django(): language = get_language() language = to_locale(language) if language is not None else "en_US" return language
def tr_lang(language_name): """Translates language names.""" language_code = translation.to_locale(translation.get_language()) return langdata.tr_lang(language_code)(language_name)
def javascript_catalog(request, domain='djangojs', packages=None): """ Returns the selected language catalog as a javascript library. Receives the list of packages to check for translations in the packages parameter either from an infodict or as a +-delimited string from the request. Default is 'django.conf'. Additionally you can override the gettext domain for this view, but usually you don't want to do that, as JavaScript messages go to the djangojs domain. But this might be needed if you deliver your JavaScript source from Django templates. """ if request.GET: if 'language' in request.GET: if check_for_language(request.GET['language']): activate(request.GET['language']) if packages is None: packages = ['django.conf'] if isinstance(packages, six.string_types): packages = packages.split('+') packages = [ p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS ] default_locale = to_locale(settings.LANGUAGE_CODE) locale = to_locale(get_language()) t = {} paths = [] en_selected = locale.startswith('en') en_catalog_missing = True # paths of requested packages for package in packages: p = importlib.import_module(package) path = os.path.join(os.path.dirname(upath(p.__file__)), 'locale') paths.append(path) # add the filesystem paths listed in the LOCALE_PATHS setting paths.extend(list(reversed(settings.LOCALE_PATHS))) # first load all english languages files for defaults for path in paths: try: catalog = gettext_module.translation(domain, path, ['en']) t.update(catalog._catalog) except IOError: pass else: # 'en' is the selected language and at least one of the packages # listed in `packages` has an 'en' catalog if en_selected: en_catalog_missing = False # next load the settings.LANGUAGE_CODE translations if it isn't english if default_locale != 'en': for path in paths: try: catalog = gettext_module.translation(domain, path, [default_locale]) except IOError: catalog = None if catalog is not None: t.update(catalog._catalog) # last load the currently selected language, if it isn't identical to the default. if locale != default_locale: # If the currently selected language is English but it doesn't have a # translation catalog (presumably due to being the language translated # from) then a wrong language catalog might have been loaded in the # previous step. It needs to be discarded. if en_selected and en_catalog_missing: t = {} else: locale_t = {} for path in paths: try: catalog = gettext_module.translation( domain, path, [locale]) except IOError: catalog = None if catalog is not None: locale_t.update(catalog._catalog) if locale_t: t = locale_t src = [LibHead] plural = None if '' in t: for l in t[''].split('\n'): if l.startswith('Plural-Forms:'): plural = l.split(':', 1)[1].strip() if plural is not None: # this should actually be a compiled function of a typical plural-form: # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2; plural = [ el.strip() for el in plural.split(';') if el.strip().startswith('plural=') ][0].split('=', 1)[1] src.append(PluralIdx % plural) else: src.append(SimplePlural) csrc = [] pdict = {} for k, v in t.items(): if k == '': continue if isinstance(k, six.string_types): csrc.append("catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(v))) elif isinstance(k, tuple): if k[0] not in pdict: pdict[k[0]] = k[1] else: pdict[k[0]] = max(k[1], pdict[k[0]]) csrc.append("catalog['%s'][%d] = '%s';\n" % (javascript_quote(k[0]), k[1], javascript_quote(v))) else: raise TypeError(k) csrc.sort() for k, v in pdict.items(): src.append("catalog['%s'] = [%s];\n" % (javascript_quote(k), ','.join(["''"] * (v + 1)))) src.extend(csrc) src.append(LibFoot) src.append(InterPolate) src.append(LibFormatHead) src.append(get_formats()) src.append(LibFormatFoot) src = ''.join(src) return http.HttpResponse(src, 'text/javascript')
def render(self, context): settings_code = [] domain = self._get_setting(context, 'snapengage_domain', 'SNAPENGAGE_DOMAIN') if domain is not None: settings_code.append(DOMAIN_CODE % domain) secure_connection = self._get_setting(context, 'snapengage_secure_connection', 'SNAPENGAGE_SECURE_CONNECTION', False) if secure_connection: settings_code.append(SECURE_CONNECTION_CODE) email = context.get('snapengage_email') if email is None: email = get_identity(context, 'snapengage', lambda u: u.email) if email is not None: if self._get_setting(context, 'snapengage_readonly_email', 'SNAPENGAGE_READONLY_EMAIL', False): readonly_tail = ',true' else: readonly_tail = '' settings_code.append(SETEMAIL_CODE % (email, readonly_tail)) locale = self._get_setting(context, 'snapengage_locale', 'SNAPENGAGE_LOCALE') if locale is None: locale = translation.to_locale(translation.get_language()) settings_code.append(SETLOCALE_CODE % locale) form_position = self._get_setting(context, 'snapengage_form_position', 'SNAPENGAGE_FORM_POSITION') if form_position is not None: settings_code.append(FORM_POSITION_CODE % form_position) form_top_position = self._get_setting(context, 'snapengage_form_top_position', 'SNAPENGAGE_FORM_TOP_POSITION') if form_top_position is not None: settings_code.append(FORM_TOP_POSITION_CODE % form_top_position) show_offline = self._get_setting(context, 'snapengage_show_offline', 'SNAPENGAGE_SHOW_OFFLINE', True) if not show_offline: settings_code.append(DISABLE_OFFLINE_CODE) screenshots = self._get_setting(context, 'snapengage_screenshots', 'SNAPENGAGE_SCREENSHOTS', True) if not screenshots: settings_code.append(DISABLE_SCREENSHOT_CODE) offline_screenshots = self._get_setting( context, 'snapengage_offline_screenshots', 'SNAPENGAGE_OFFLINE_SCREENSHOTS', True) if not offline_screenshots: settings_code.append(DISABLE_OFFLINE_SCREENSHOT_CODE) if not context.get('snapengage_proactive_chat', True): settings_code.append(DISABLE_PROACTIVE_CHAT_CODE) sounds = self._get_setting(context, 'snapengage_sounds', 'SNAPENGAGE_SOUNDS', True) if not sounds: settings_code.append(DISABLE_SOUNDS_CODE) button_effect = self._get_setting(context, 'snapengage_button_effect', 'SNAPENGAGE_BUTTON_EFFECT') if button_effect is not None: settings_code.append(BUTTONEFFECT_CODE % button_effect) button = self._get_setting(context, 'snapengage_button', 'SNAPENGAGE_BUTTON', BUTTON_STYLE_DEFAULT) if button == BUTTON_STYLE_NONE: settings_code.append(INIT_CODE % self.widget_id) else: if not isinstance(button, int): # Assume button as a URL to a custom image settings_code.append(SETBUTTON_CODE % button) button_location = self._get_setting(context, 'snapengage_button_location', 'SNAPENGAGE_BUTTON_LOCATION', BUTTON_LOCATION_LEFT) button_offset = self._get_setting( context, 'snapengage_button_location_offset', 'SNAPENGAGE_BUTTON_LOCATION_OFFSET', '55%') settings_code.append( ADDBUTTON_CODE % { 'id': self.widget_id, 'location': button_location, 'offset': button_offset, 'dynamic_tail': ',true' if (button == BUTTON_STYLE_LIVE) else '', }) html = SETUP_CODE % { 'widget_id': self.widget_id, 'settings_code': " ".join(settings_code), } return html
def locale(request): """Convert the language string to a locale""" """Copied from: http://stackoverflow.com/a/6362929 """ return {'LOCALE': to_locale(get_language())}
def _get_language_code(self): """Return language code or None.""" lang_code = translation.get_language() if lang_code: lang_code = translation.to_locale(lang_code).replace('_', '-') return lang_code
def current_locale(): return to_locale(get_language())
def time_remaining_string(self): """ Returns the time remaining as a localized string. """ locale = to_locale(get_language()) return format_timedelta(self.date - self.current_time, locale=locale)
def get_javascript_catalog(locale, domain, packages): default_locale = to_locale(settings.LANGUAGE_CODE) packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS] t = {} paths = [] en_selected = locale.startswith('en') en_catalog_missing = True # paths of requested packages for package in packages: p = importlib.import_module(package) path = os.path.join(os.path.dirname(upath(p.__file__)), 'locale') paths.append(path) # add the filesystem paths listed in the LOCALE_PATHS setting paths.extend(list(reversed(settings.LOCALE_PATHS))) # first load all english languages files for defaults for path in paths: try: catalog = gettext_module.translation(domain, path, ['en']) t.update(catalog._catalog) except IOError: pass else: # 'en' is the selected language and at least one of the packages # listed in `packages` has an 'en' catalog if en_selected: en_catalog_missing = False # next load the settings.LANGUAGE_CODE translations if it isn't english if default_locale != 'en': for path in paths: try: catalog = gettext_module.translation(domain, path, [default_locale]) except IOError: catalog = None if catalog is not None: t.update(catalog._catalog) # last load the currently selected language, if it isn't identical to the default. if locale != default_locale: # If the currently selected language is English but it doesn't have a # translation catalog (presumably due to being the language translated # from) then a wrong language catalog might have been loaded in the # previous step. It needs to be discarded. if en_selected and en_catalog_missing: t = {} else: locale_t = {} for path in paths: try: catalog = gettext_module.translation(domain, path, [locale]) except IOError: catalog = None if catalog is not None: locale_t.update(catalog._catalog) if locale_t: t = locale_t plural = None if '' in t: for l in t[''].split('\n'): if l.startswith('Plural-Forms:'): plural = l.split(':', 1)[1].strip() if plural is not None: # this should actually be a compiled function of a typical plural-form: # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2; plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=', 1)[1] pdict = {} maxcnts = {} catalog = {} for k, v in t.items(): if k == '': continue if isinstance(k, six.string_types): catalog[k] = v elif isinstance(k, tuple): msgid = k[0] cnt = k[1] maxcnts[msgid] = max(cnt, maxcnts.get(msgid, 0)) pdict.setdefault(msgid, {})[cnt] = v else: raise TypeError(k) for k, v in pdict.items(): catalog[k] = [v.get(i, '') for i in range(maxcnts[msgid] + 1)] return catalog, plural
def _get_format(): lang = translation.get_language() locale = Locale(translation.to_locale(lang)) return Format(locale)
def get(self, request, course_id, error=None): """Displays the course mode choice page. Args: request (`Request`): The Django Request object. course_id (unicode): The slash-separated course key. Keyword Args: error (unicode): If provided, display this error message on the page. Returns: Response """ course_key = CourseKey.from_string(course_id) # Check whether the user has access to this course # based on country access rules. embargo_redirect = embargo_api.redirect_if_blocked( course_key, user=request.user, ip_address=get_ip(request), url=request.path) if embargo_redirect: return redirect(embargo_redirect) enrollment_mode, is_active = CourseEnrollment.enrollment_mode_for_user( request.user, course_key) modes = CourseMode.modes_for_course_dict(course_key) ecommerce_service = EcommerceService() # We assume that, if 'professional' is one of the modes, it should be the *only* mode. # If there are both modes, default to non-id-professional. has_enrolled_professional = ( CourseMode.is_professional_slug(enrollment_mode) and is_active) if CourseMode.has_professional_mode( modes) and not has_enrolled_professional: purchase_workflow = request.GET.get("purchase_workflow", "single") verify_url = reverse('verify_student_start_flow', kwargs={'course_id': unicode(course_key)}) redirect_url = "{url}?purchase_workflow={workflow}".format( url=verify_url, workflow=purchase_workflow) if ecommerce_service.is_enabled(request.user): professional_mode = modes.get( CourseMode.NO_ID_PROFESSIONAL_MODE) or modes.get( CourseMode.PROFESSIONAL) if purchase_workflow == "single" and professional_mode.sku: redirect_url = ecommerce_service.get_checkout_page_url( professional_mode.sku) if purchase_workflow == "bulk" and professional_mode.bulk_sku: redirect_url = ecommerce_service.get_checkout_page_url( professional_mode.bulk_sku) return redirect(redirect_url) course = modulestore().get_course(course_key) # If there isn't a verified mode available, then there's nothing # to do on this page. Send the user to the dashboard. if not CourseMode.has_verified_mode(modes): return redirect(reverse('dashboard')) # If a user has already paid, redirect them to the dashboard. if is_active and (enrollment_mode in CourseMode.VERIFIED_MODES + [CourseMode.NO_ID_PROFESSIONAL_MODE]): # If the course has started redirect to course home instead if course.has_started(): return redirect( reverse('openedx.course_experience.course_home', kwargs={'course_id': course_key})) return redirect(reverse('dashboard')) donation_for_course = request.session.get("donation_for_course", {}) chosen_price = donation_for_course.get(unicode(course_key), None) if CourseEnrollment.is_enrollment_closed(request.user, course): locale = to_locale(get_language()) enrollment_end_date = format_datetime(course.enrollment_end, 'short', locale=locale) params = urllib.urlencode({'course_closed': enrollment_end_date}) return redirect('{0}?{1}'.format(reverse('dashboard'), params)) # When a credit mode is available, students will be given the option # to upgrade from a verified mode to a credit mode at the end of the course. # This allows students who have completed photo verification to be eligible # for univerity credit. # Since credit isn't one of the selectable options on the track selection page, # we need to check *all* available course modes in order to determine whether # a credit mode is available. If so, then we show slightly different messaging # for the verified track. has_credit_upsell = any( CourseMode.is_credit_mode(mode) for mode in CourseMode.modes_for_course(course_key, only_selectable=False)) course_id = course_key.to_deprecated_string() context = { "course_modes_choose_url": reverse("course_modes_choose", kwargs={'course_id': course_id}), "modes": modes, "has_credit_upsell": has_credit_upsell, "course_name": course.display_name_with_default_escaped, "course_org": course.display_org_with_default, "course_num": course.display_number_with_default, "chosen_price": chosen_price, "error": error, "responsive": True, "nav_hidden": True, } context.update( get_experiment_user_metadata_context( course, request.user, )) title_content = _( "Congratulations! You are now enrolled in {course_name}").format( course_name=course.display_name_with_default_escaped) context["title_content"] = title_content if "verified" in modes: verified_mode = modes["verified"] context["suggested_prices"] = [ decimal.Decimal(x.strip()) for x in verified_mode.suggested_prices.split(",") if x.strip() ] context["currency"] = verified_mode.currency.upper() context["min_price"] = verified_mode.min_price context["verified_name"] = verified_mode.name context["verified_description"] = verified_mode.description if verified_mode.sku: context[ "use_ecommerce_payment_flow"] = ecommerce_service.is_enabled( request.user) context[ "ecommerce_payment_page"] = ecommerce_service.payment_page_url( ) context["sku"] = verified_mode.sku context["bulk_sku"] = verified_mode.bulk_sku context['currency_data'] = [] if waffle.switch_is_active('local_currency'): if 'edx-price-l10n' not in request.COOKIES: currency_data = get_currency_data() try: context['currency_data'] = json.dumps(currency_data) except TypeError: pass return render_to_response("course_modes/choose.html", context)
def format_date(date): locale = to_locale(get_language()) return dates.format_date(date, format='medium', locale = locale)
def _get_locale(request): language = request.GET.get(LANGUAGE_QUERY_PARAMETER) if not (language and check_for_language(language)): language = get_language() return to_locale(language)
def prepare_pickup_conversation_message_notification(user, message): pickup = message.conversation.target group_tz = pickup.store.group.timezone language = user.language if not translation.check_for_language(language): language = 'en' with translation.override(language): with timezone.override(group_tz): weekday = format_date( pickup.date.astimezone(timezone.get_current_timezone()), 'EEEE', locale=translation.to_locale(language), ) time = format_time( pickup.date, format='short', locale=translation.to_locale(language), tzinfo=timezone.get_current_timezone(), ) date = format_date( pickup.date.astimezone(timezone.get_current_timezone()), format='long', locale=translation.to_locale(language), ) long_date = '{} {}, {}'.format(weekday, time, date) short_date = '{} {}'.format(weekday, time) reply_to_name = _('Pickup %(date)s') % { 'date': short_date, } conversation_name = _('Pickup %(date)s') % { 'date': long_date, } local_part = make_local_part(message.conversation, user) reply_to = formataddr( (reply_to_name, '{}@{}'.format(local_part, settings.SPARKPOST_RELAY_DOMAIN))) from_email = formataddr( (message.author.display_name, settings.DEFAULT_FROM_EMAIL)) return prepare_email('conversation_message_notification', from_email=from_email, user=user, reply_to=[reply_to], context={ 'conversation_name': conversation_name, 'author': message.author, 'message_content': message.content_rendered(), 'conversation_url': pickup_detail_url(pickup), 'mute_url': pickup_conversation_mute_url( pickup, message.conversation), })
def currency(number, currency = 'EUR'): locale = to_locale(get_language()) if not number: return "" return format_currency(number, currency, locale = locale)