Example #1
0
def change_locale(request):
    """
    Redirect to a given url while changing the locale in the path
    The url and the locale code need to be specified in the
    request parameters.
    """
    
    # we assume the target url shares the same script name !
    script_name = request.META["SCRIPT_NAME"] 
    
    next = request.REQUEST.get('next', None)
    if not next:
        next = urlsplit(request.META.get('HTTP_REFERER', None))[2]
    if not next:
        next = request.META["SCRIPT_NAME"]+"/" # root of the django project
    
    if not next.startswith(script_name):
        script_name = ""
        locale, path_info = utils.strip_path(next)
    else:
        locale, path_info = utils.strip_path(next[len(script_name):])
     
     
    if request.method == 'POST':
        locale = request.POST.get('locale', None)   
        if locale and check_for_language(locale):
            path = utils.locale_path(path, locale, script_name)
            response = http.HttpResponseRedirect(path)
            return response
    
    return http.HttpResponseRedirect(next) # we failed language change    
Example #2
0
def rmlocale(url):
    """Removes the locale prefix from the URL.
    
    The URL is expected to have the same script prefix as the current page."""
    script_prefix, path = utils.strip_script_prefix(url)
    _, path = utils.strip_path(path)
    return ''.join([script_prefix, path])
Example #3
0
    def process_request(self, request):
        locale, path = utils.strip_path(request.path_info)
        if localeurl_settings.USE_ACCEPT_LANGUAGE and not locale:
            accept_langs = filter(lambda x: x, [utils.supported_language(lang[0])
                                                for lang in
                                                parse_accept_lang_header(
                        request.META.get('HTTP_ACCEPT_LANGUAGE', ''))])
            if accept_langs:
                locale = accept_langs[0]
        locale_path = utils.locale_path(path, locale)
        if locale_path != request.path_info:
            locale_url = utils.add_script_prefix(locale_path)

            qs = request.META.get("QUERY_STRING", "")
            if qs:
                # Force this to remain a byte-string by encoding locale_path
                # first to avoid Unicode tainting - downstream will need to
                # handle the job of handling in-the-wild character encodings:
                locale_url = "%s?%s" % (locale_path.encode("utf-8"), qs)

            redirect_class = HttpResponsePermanentRedirect
            if not localeurl_settings.LOCALE_REDIRECT_PERMANENT:
                redirect_class = HttpResponseRedirect
            # @@@ iri_to_uri for Django 1.0; 1.1+ do it in HttpResp...Redirect
            return redirect_class(iri_to_uri(locale_url))
        request.path_info = path
        if not locale:
            try:
                locale = request.LANGUAGE_CODE
            except AttributeError:
                locale = settings.LANGUAGE_CODE
        translation.activate(locale)
        request.LANGUAGE_CODE = translation.get_language()
def alternate_languages(context):
    request = context['request']

    is_lang = False
    lang_list = []
    alternate = ""
    for lang in settings.LANGUAGES:
        lang_regex = ("/%s/") % lang[0]
        if lang_regex in request.path:
            is_lang = True
        else:
            lang_list.append(lang[0])

    if hasattr(request, 'urlconf') and request.urlconf is not None:
        urlconf = request.urlconf
    else:
        urlconf = get_urlconf()
    locale, path = utils.strip_path(request.path_info)
    hostname = request.get_host().split(":")[0]

    if is_lang:
        for lang in lang_list:
            locale_path = utils.locale_path(path,
                                            lang,
                                            host=hostname,
                                            urlconf=urlconf)
            alternate += (
                '<link rel="alternate" hreflang="%s" href="http://%s%s" />\n'
            ) % (lang, hostname, locale_path)
    return alternate
Example #5
0
    def process_response(self, request, response):
        session = request.COOKIES.get('_sc', None)

        if not session:
            session = uuid.uuid4().hex
            response.set_cookie('_sc', session, max_age=60 * 60 * 24 * 365)
        if request.is_ajax():
            return response

        path_parts = utils.strip_path(request.META.get('PATH_INFO', '').lower())
        if len(path_parts) > 1:
            path = path_parts[1]
        else:
            path = path_parts[0]
        ignore = False
        for ignore_path in IGNORED_PATHES:
            if path.startswith(ignore_path):
                ignore = True
        query = request.META.get('QUERY_STRING', '').lower()

        url_hash = hashlib.md5((path + query).encode('utf-8')).hexdigest()

        before = (datetime.datetime.now() - datetime.timedelta(minutes=URL_TIMEOUT))
        if PageView.objects.filter(datetime__gt=before, session=session, url_hash=url_hash).exists():
            ignore = True

        if session and not ignore:
            log_page_view(path=path, query=query, url_hash=url_hash, session=session)

        return response
Example #6
0
def url_exists(url, local=False):
    """
    Check if URL exists.

    :param str url:
    :param bool local:
    :return bool:
    """
    if not local:
        try:
            r = requests.head(url)
            return r.status_code == requests.codes.ok
        except (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,
                ProxyError, RetryError) as err:
            return False

    else:
        if 'localeurl' in settings.INSTALLED_APPS and callable(strip_path):
            url = strip_path(url)[1]

        try:
            resolve(url)
            return True
        except Resolver404 as err:
            return False
Example #7
0
    def process_request(self, request):
        locale, path = utils.strip_path(request.path_info)
        if localeurl_settings.USE_ACCEPT_LANGUAGE and not locale:
            accept_langs = filter(lambda x: x, [
                utils.supported_language(lang[0])
                for lang in parse_accept_lang_header(
                    request.META.get('HTTP_ACCEPT_LANGUAGE', ''))
            ])
            if accept_langs:
                locale = accept_langs[0]
        locale_path = utils.locale_path(path, locale)
        if locale_path != request.path_info:
            locale_url = utils.add_script_prefix(locale_path)

            qs = request.META.get("QUERY_STRING", "")
            if qs:
                # Force this to remain a byte-string by encoding locale_path
                # first to avoid Unicode tainting - downstream will need to
                # handle the job of handling in-the-wild character encodings:
                locale_url = "%s?%s" % (locale_path.encode("utf-8"), qs)

            redirect_class = HttpResponsePermanentRedirect
            if not localeurl_settings.LOCALE_REDIRECT_PERMANENT:
                redirect_class = HttpResponseRedirect
            # @@@ iri_to_uri for Django 1.0; 1.1+ do it in HttpResp...Redirect
            return redirect_class(iri_to_uri(locale_url))
        request.path_info = path
        if not locale:
            try:
                locale = request.LANGUAGE_CODE
            except AttributeError:
                locale = settings.LANGUAGE_CODE
        translation.activate(locale)
        request.LANGUAGE_CODE = translation.get_language()
Example #8
0
def watch(request):
    response = HttpResponse(status=200)
    session = request.COOKIES.get('_sc', None)

    if not session:
        session = uuid.uuid4().hex
        response.set_cookie('_sc', session, max_age=60 * 60 * 24 * 365)

    http_referer = request.META.get('HTTP_REFERER', None)
    if not http_referer:
        return response

    url_parts = urlparse(http_referer)
    path_parts = utils.strip_path(url_parts.path)
    if len(path_parts) > 1:
        path = path_parts[1]
    else:
        path = path_parts[0]
    ignore = False

    query = url_parts.query

    url_hash = hashlib.md5((path + query).encode('utf-8')).hexdigest()

    before = (datetime.datetime.now() - datetime.timedelta(minutes=URL_TIMEOUT))
    # if models.PageView.objects.filter(datetime__gt=before, session=session, url_hash=url_hash).exists():
    #     ignore = True

    user = None
    if request.user.is_authenticated():
        user = request.user
    if session and not ignore:
        models.log_page_view(path=path, query=query, url_hash=url_hash, session=session, user=user)

    return response
Example #9
0
 def process_request(self, request):
     locale, path = utils.strip_path(request.path_info)
     if localeurl_settings.USE_ACCEPT_LANGUAGE and not locale:
         accept_langs = filter(lambda x: x, [
             utils.supported_language(lang[0])
             for lang in parse_accept_lang_header(
                 request.META.get('HTTP_ACCEPT_LANGUAGE', ''))
         ])
         if accept_langs:
             locale = accept_langs[0]
     locale_path = utils.locale_path(path, locale)
     if locale_path != request.path_info:
         if request.META.get("QUERY_STRING", ""):
             locale_path = "%s?%s" % (locale_path,
                                      request.META['QUERY_STRING'])
         locale_url = utils.add_script_prefix(locale_path)
         redirect_class = HttpResponsePermanentRedirect
         if not localeurl_settings.LOCALE_REDIRECT_PERMANENT:
             redirect_class = HttpResponseRedirect
         # @@@ iri_to_uri for Django 1.0; 1.1+ do it in HttpResp...Redirect
         return redirect_class(iri_to_uri(locale_url))
     request.path_info = path
     if not locale:
         try:
             locale = request.LANGUAGE_CODE
         except AttributeError:
             locale = settings.LANGUAGE_CODE
     translation.activate(locale)
     request.LANGUAGE_CODE = translation.get_language()
Example #10
0
def change_locale(request):
    """
    Redirect to a given url while changing the locale in the path
    The url and the locale code need to be specified in the
    request parameters.
    """
    next = request.REQUEST.get('next', None)
    if not next:
        referrer = request.META.get('HTTP_REFERER', None)
        if referrer:
            next = urlsplit(referrer)[2]
    if not next:
        next = '/'
    _, path = utils.strip_path(next)
    if request.method == 'POST':
        locale = request.POST.get('locale', None)
        if locale and check_for_language(locale):
            if localeurl_settings.USE_SESSION:
                request.session['django_language'] = locale
            path = utils.locale_path(path, locale)
            signals.locale_change.send(sender=change_locale,
                                       locale=locale,
                                       user=request.user)

    response = http.HttpResponseRedirect(path)
    return response
Example #11
0
 def process_request(self, request):
     locale, path = utils.strip_path(request.path_info)
     if localeurl_settings.USE_ACCEPT_LANGUAGE and not locale:
         accept_langs = filter(lambda x: x, [utils.supported_language(lang[0])
                                             for lang in
                                             parse_accept_lang_header(
                     request.META.get('HTTP_ACCEPT_LANGUAGE', ''))])
         if accept_langs:
             locale = accept_langs[0]
     locale_path = utils.locale_path(path, locale)
     if locale_path != request.path_info:
         if request.META.get("QUERY_STRING", ""):
             locale_path = "%s?%s" % (locale_path,
                     request.META['QUERY_STRING'])
         locale_url = utils.add_script_prefix(locale_path)
         # @@@ iri_to_uri for Django 1.0; 1.1+ do it in HttpResp...Redirect
         return HttpResponsePermanentRedirect(iri_to_uri(locale_url))
     request.path_info = path
     if not locale:
         try:
             locale = request.LANGUAGE_CODE
         except AttributeError:
             locale = settings.LANGUAGE_CODE
     translation.activate(locale)
     request.LANGUAGE_CODE = translation.get_language()
def alternate_languages(context):
    request = context['request']

    is_lang = False
    lang_list = []
    alternate = ""
    for lang in settings.LANGUAGES:
        lang_regex = ("/%s/") % lang[0]
        if lang_regex in request.path:
            is_lang = True
        else:
            lang_list.append(lang[0])

    if hasattr(request, 'urlconf') and request.urlconf is not None:
            urlconf = request.urlconf
    else:
        urlconf = get_urlconf()
    locale, path = utils.strip_path(request.path_info)
    hostname = request.get_host().split(":")[0]

    if is_lang:
        for lang in lang_list:
            locale_path = utils.locale_path(path, lang, host=hostname, urlconf=urlconf)
            alternate += ('<link rel="alternate" hreflang="%s" href="http://%s%s" />\n') % (lang, hostname ,locale_path)
    return alternate
Example #13
0
def locale_redirect(*args, **kwargs):
    """ Redirect shortcut with forced locale.
    """
    locale = kwargs.pop('locale')
    url = reverse(*args, **kwargs)
    ignored, path = strip_path(url)
    url = locale_url(path, locale=locale)
    return redirect(url)
Example #14
0
def chlocale(url, locale):
    """
    Changes the URL's locale prefix if the path is not locale-independent.
    Otherwise removes locale prefix.
    """
    _, path = utils.strip_script_prefix(url)
    _, path = utils.strip_path(path)
    return utils.locale_url(path, locale)
Example #15
0
def chlocale(url, locale):
    """
    Changes the URL's locale prefix if the path is not locale-independent.
    Otherwise removes locale prefix.
    """
    _, path = utils.strip_script_prefix(url)
    _, path = utils.strip_path(path)
    return utils.locale_url(path, locale)
Example #16
0
 def split_locale_from_request(self, request):
     if localeurl.settings.URL_TYPE == 'domain':
         raise AssertionError("URL_TYPE 'domain' not yet supported")
     elif localeurl.settings.URL_TYPE == 'domain_component':
         locale, _ = utils.strip_domain(request.get_host())
         path_info = request.path_info
     else:
         locale, path_info = utils.strip_path(request.path_info)
     return locale, path_info
Example #17
0
    def clean(self, value):
        self.vt = None
        self.video = None

        super(UniSubBoundVideoField, self).clean(value)

        video_url = value

        if not video_url:
            return video_url

        host = Site.objects.get_current().domain
        url_start = 'http://' + host

        if video_url.startswith(url_start):
            # UniSub URL
            locale, path = strip_path(video_url[len(url_start):])
            video_url = url_start + path
            try:
                video_url = self.format_url(video_url)
                func, args, kwargs = resolve(video_url.replace(url_start, ''))

                if not 'video_id' in kwargs:
                    raise forms.ValidationError(
                        _('This URL does not contain video id.'))

                try:
                    self.video = Video.objects.get(video_id=kwargs['video_id'])
                except Video.DoesNotExist:
                    raise forms.ValidationError(_('Videos does not exist.'))

            except Http404:
                raise forms.ValidationError(_('Incorrect URL.'))
        else:
            # URL from other site
            try:
                self.vt = video_type_registrar.video_type_for_url(video_url)

                if hasattr(self, 'user'):
                    user = self.user
                else:
                    user = None

                if self.vt:
                    self.video, created = Video.get_or_create_for_url(
                        vt=self.vt, user=user)
            except VideoTypeError, e:
                self.video = None
                raise forms.ValidationError(e)

            if not self.video:
                raise forms.ValidationError(
                    mark_safe(
                        _(u"""Universal Subtitles does not support that website or video format.
If you'd like to us to add support for a new site or format, or if you
think there's been some mistake, <a
href="mailto:%s">contact us</a>!""") % settings.FEEDBACK_EMAIL))
Example #18
0
 def split_locale_from_request(self, request):
     if localeurl.settings.URL_TYPE == 'domain':
         raise AssertionError("URL_TYPE 'domain' not yet supported")
     elif localeurl.settings.URL_TYPE == 'domain_component':
         locale, _ = utils.strip_domain(request.get_host())
         path_info = request.path_info
     else:
         locale, path_info = utils.strip_path(request.path_info)
     return locale, path_info
Example #19
0
def chlocale(url, locale):
    """
    Changes the URL's locale prefix if the path is not locale-independent.
    Otherwise removes locale prefix.
    
    The URL is expected to have the same script prefix as the current page.
    """
    script_name, path = utils.strip_script_prefix(url)
    _, path = utils.strip_path(path)
    return utils.locale_url(path, locale, script_name)
Example #20
0
    def clean(self, value):
        self.vt = None
        self.video = None

        super(UniSubBoundVideoField, self).clean(value)

        video_url = value

        if not video_url:
            return video_url

        host = Site.objects.get_current().domain
        url_start = 'http://'+host

        if video_url.startswith(url_start):
            # UniSub URL
            locale, path = strip_path(video_url[len(url_start):])
            video_url = url_start+path
            try:
                video_url = self.format_url(video_url)
                func, args, kwargs = resolve(video_url.replace(url_start, ''))

                if not 'video_id' in kwargs:
                    raise forms.ValidationError(_('This URL does not contain video id.'))

                try:
                    self.video = Video.objects.get(video_id=kwargs['video_id'])
                except Video.DoesNotExist:
                    raise forms.ValidationError(_('Videos does not exist.'))

            except Http404:
                raise forms.ValidationError(_('Incorrect URL.'))
        else:
            # URL from other site
            try:
                self.vt = video_type_registrar.video_type_for_url(video_url)

                if hasattr(self, 'user'):
                    user = self.user
                else:
                    user = None

                if self.vt:
                    self.video, created = Video.get_or_create_for_url(vt=self.vt, user=user)
            except VideoTypeError, e:
                self.video = None
                raise forms.ValidationError(e)

            if not self.video:
                raise forms.ValidationError(mark_safe(_(u"""Universal Subtitles does not support that website or video format.
If you'd like to us to add support for a new site or format, or if you
think there's been some mistake, <a
href="mailto:%s">contact us</a>!""") % settings.FEEDBACK_EMAIL))
Example #21
0
 def split_locale_from_request(self, request):
     if localeurl.settings.URL_TYPE == 'domain':
         raise AssertionError("URL_TYPE 'domain' not yet supported")
     elif localeurl.settings.URL_TYPE == 'domain_component':
         locale, _ = utils.strip_domain(request.get_host())
         path_info = request.path_info
     else:
         locale, path_info = utils.strip_path(request.path_info)
         """ If no locale returned from path get next best from request """
         if not locale:
             locale = translation.get_language_from_request(request)
     return locale, path_info
Example #22
0
    def process_request(self, request):
        hostname = request.get_host().split(":")[0]

        locale, path = utils.strip_path(request.path_info)
        if localeurl_settings.USE_SESSION and not locale:
            slocale = request.session.get('django_language')
            if slocale and utils.supported_language(slocale):
                locale = slocale
        if localeurl_settings.USE_ACCEPT_LANGUAGE and not locale:
            accept_lang_header = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
            header_langs = parse_accept_lang_header(accept_lang_header)
            accept_langs = filter(
                None,
                [utils.supported_language(lang[0]) for lang in header_langs])
            if accept_langs:
                locale = accept_langs[0]

        if hasattr(request, 'urlconf') and request.urlconf is not None:
            urlconf = request.urlconf
        else:
            urlconf = get_urlconf()

        locale_path = utils.locale_path(path,
                                        locale,
                                        host=hostname,
                                        urlconf=urlconf)
        # locale case might be different in the two paths, that doesn't require
        # a redirect (besides locale they'll be identical anyway)
        if locale_path.lower() != request.path_info.lower():
            locale_url = utils.add_script_prefix(locale_path)

            qs = request.META.get("QUERY_STRING", "")
            if qs:
                # Force this to remain a byte-string by encoding locale_path
                # first to avoid Unicode tainting - downstream will need to
                # handle the job of handling in-the-wild character encodings:
                locale_url = "%s?%s" % (locale_path.encode("utf-8"), qs)

            redirect_class = HttpResponsePermanentRedirect
            if not localeurl_settings.LOCALE_REDIRECT_PERMANENT:
                redirect_class = HttpResponseRedirect
            # @@@ iri_to_uri for Django 1.0; 1.1+ do it in HttpResp...Redirect
            return redirect_class(iri_to_uri(locale_url))
        request.path_info = path
        if not locale:
            try:
                locale = request.LANGUAGE_CODE
            except AttributeError:
                locale = settings.LANGUAGE_CODE
        translation.activate(locale)
        request.LANGUAGE_CODE = translation.get_language()
Example #23
0
    def process_request(self, request):
        hostname = request.get_host().split(":")[0]

        locale, path = utils.strip_path(request.path_info)
        if localeurl_settings.USE_SESSION and not locale:
            slocale = request.session.get('django_language')
            if slocale and utils.supported_language(slocale):
                locale = slocale
        if localeurl_settings.USE_ACCEPT_LANGUAGE and not locale:
            accept_lang_header = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
            header_langs = parse_accept_lang_header(accept_lang_header)
            accept_langs = filter(
                None,
                [utils.supported_language(lang[0]) for lang in header_langs]
                )
            if accept_langs:
                locale = accept_langs[0]

        if hasattr(request, 'urlconf') and request.urlconf is not None:
            urlconf = request.urlconf
        else:
            urlconf = get_urlconf()

        locale_path = utils.locale_path(path, locale, host=hostname, urlconf=urlconf)
        # locale case might be different in the two paths, that doesn't require
        # a redirect (besides locale they'll be identical anyway)
        if locale_path.lower() != request.path_info.lower():
            locale_url = utils.add_script_prefix(locale_path)

            qs = request.META.get("QUERY_STRING", "")
            if qs:
                # Force this to remain a byte-string by encoding locale_path
                # first to avoid Unicode tainting - downstream will need to
                # handle the job of handling in-the-wild character encodings:
                locale_url = "%s?%s" % (locale_path.encode("utf-8"), qs)

            redirect_class = HttpResponsePermanentRedirect
            if not localeurl_settings.LOCALE_REDIRECT_PERMANENT:
                redirect_class = HttpResponseRedirect
            # @@@ iri_to_uri for Django 1.0; 1.1+ do it in HttpResp...Redirect
            return redirect_class(iri_to_uri(locale_url))
        request.path_info = path
        if not locale:
            try:
                locale = request.LANGUAGE_CODE
            except AttributeError:
                locale = settings.LANGUAGE_CODE
        translation.activate(locale)
        request.LANGUAGE_CODE = translation.get_language()
Example #24
0
 def process_request(self, request):
     locale, path = utils.strip_path(request.path_info)
     locale_path = utils.locale_path(path, locale)
     if locale_path != request.path_info:
         if request.META.get("QUERY_STRING", ""):
             locale_path = "%s?%s" % (locale_path,
                                      request.META['QUERY_STRING'])
         return HttpResponseRedirect(locale_path)
     request.path_info = path
     if not locale:
         try:
             locale = request.LANGUAGE_CODE
         except AttributeError:
             locale = settings.LANGUAGE_CODE
     translation.activate(locale)
     request.LANGUAGE_CODE = translation.get_language()
Example #25
0
 def test_strip_path(self):
     self.assertEqual(('', '/'), utils.strip_path('/'))
     self.assertEqual(('', '/about/'), utils.strip_path('/about/'))
     self.assertEqual(('', '/about/localeurl/'),
             utils.strip_path('/about/localeurl/'))
     self.assertEqual(('fr', '/about/localeurl/'),
             utils.strip_path('/fr/about/localeurl/'))
     self.assertEqual(('nl-be', '/about/localeurl/'),
             utils.strip_path('/nl-be/about/localeurl/'))
     self.assertEqual(('', '/de/about/localeurl/'),
             utils.strip_path('/de/about/localeurl/'))
Example #26
0
 def test_strip_path(self):
     self.assertEqual(('', '/'), utils.strip_path('/'))
     self.assertEqual(('', '/about/'), utils.strip_path('/about/'))
     self.assertEqual(('', '/about/localeurl/'),
                      utils.strip_path('/about/localeurl/'))
     self.assertEqual(('fr', '/about/localeurl/'),
                      utils.strip_path('/fr/about/localeurl/'))
     self.assertEqual(('nl-be', '/about/localeurl/'),
                      utils.strip_path('/nl-be/about/localeurl/'))
     self.assertEqual(('', '/de/about/localeurl/'),
                      utils.strip_path('/de/about/localeurl/'))
Example #27
0
def change_locale(request):
    """
    Redirect to a given url while changing the locale in the path
    The url and the locale code need to be specified in the
    request parameters.
    """
    next = request.REQUEST.get("next", None)
    if not next:
        next = urlsplit(request.META.get("HTTP_REFERER", None))[2]
    if not next:
        next = "/"
    _, path = utils.strip_path(next)
    if request.method == "POST":
        locale = request.POST.get("locale", None)
        if locale and check_for_language(locale):
            path = utils.locale_path(path, locale)

    response = http.HttpResponseRedirect(path)
    return response
Example #28
0
def change_locale(request):
    """
    Redirect to a given url while changing the locale in the path
    The url and the locale code need to be specified in the
    request parameters.
    """
    next = request.REQUEST.get('next', None)
    if not next:
        next = urlsplit(request.META.get('HTTP_REFERER', None))[2]
    if not next:
        next = '/'
    _, path = utils.strip_path(next)
    if request.method == 'POST':
        locale = request.POST.get('locale', None)
        if locale and check_for_language(locale):
            path = utils.locale_path(path, locale)

    response = http.HttpResponseRedirect(path)
    return response
Example #29
0
def change_locale(request):
    """
    Redirect to a given url while changing the locale in the path
    The url and the locale code need to be specified in the
    request parameters.
    """
    next = request.REQUEST.get('next', None)
    if not next:
        referrer = request.META.get('HTTP_REFERER', None)
        if referrer:
            next = urlsplit(referrer)[2]
    if not next:
        next = '/'
    _, path = utils.strip_path(next)
    locale = request.REQUEST.get('locale', None)
    if locale and check_for_language(locale):
        if localeurl_settings.USE_SESSION:
            request.session['django_language'] = locale
        path = utils.locale_path(path, locale)

    response = http.HttpResponseRedirect(path)
    return response
 def process_request(self, request):
     locale, path = utils.strip_path(request.path_info)
     if localeurl_settings.USE_ACCEPT_LANGUAGE and not locale:
         accept_langs = filter(lambda x: x, [utils.supported_language(lang[0])
                                             for lang in
                                             parse_accept_lang_header(
                     request.META.get('HTTP_ACCEPT_LANGUAGE', ''))])
         if accept_langs:
             locale = accept_langs[0]
     locale_path = utils.locale_path(path, locale)
     if locale_path != request.path_info:
         if request.META.get("QUERY_STRING", ""):
             locale_path = "%s?%s" % (locale_path,
                     request.META['QUERY_STRING'])
         return HttpResponsePermanentRedirect(locale_path)
     request.path_info = path
     if not locale:
         try:
             locale = request.LANGUAGE_CODE
         except AttributeError:
             locale = settings.LANGUAGE_CODE
     translation.activate(locale)
     request.LANGUAGE_CODE = translation.get_language()
Example #31
0
    def process_response(self, request, response):
        session = request.COOKIES.get('_sc', None)

        if not session:
            session = uuid.uuid4().hex
            response.set_cookie('_sc', session, max_age=60 * 60 * 24 * 365)
        if request.is_ajax():
            return response

        path_parts = utils.strip_path(
            request.META.get('PATH_INFO', '').lower())
        if len(path_parts) > 1:
            path = path_parts[1]
        else:
            path = path_parts[0]
        ignore = False
        for ignore_path in IGNORED_PATHES:
            if path.startswith(ignore_path):
                ignore = True
        query = request.META.get('QUERY_STRING', '').lower()

        url_hash = hashlib.md5((path + query).encode('utf-8')).hexdigest()

        before = (datetime.datetime.now() -
                  datetime.timedelta(minutes=URL_TIMEOUT))
        if PageView.objects.filter(datetime__gt=before,
                                   session=session,
                                   url_hash=url_hash).exists():
            ignore = True

        if session and not ignore:
            log_page_view(path=path,
                          query=query,
                          url_hash=url_hash,
                          session=session)

        return response
Example #32
0
def change_locale(request):
    """
    Redirect to a given url while changing the locale in the path
    The url and the locale code need to be specified in the
    request parameters.
    """
    next = request.REQUEST.get("next", None)
    if not next:
        referrer = request.META.get("HTTP_REFERER", None)
        if referrer:
            next = urlsplit(referrer)[2]
    if not next:
        next = "/"
    _, path = utils.strip_path(next)
    if request.method == "POST":
        locale = request.POST.get("locale", None)
        if locale and check_for_language(locale):
            if localeurl_settings.USE_SESSION:
                request.session["django_language"] = locale
            path = utils.locale_path(path, locale)
            signals.locale_change.send(sender=change_locale, locale=locale, user=request.user)

    response = http.HttpResponseRedirect(path)
    return response
Example #33
0
 def process_request(self, request):
     
     #  we check if another middleware has already set the language, eg. from domain name
     if not hasattr(request, "LANGUAGE_CODE") or not request.LANGUAGE_CODE: 
         
         locale, path = utils.strip_path(request.path_info)
          
         #return HttpResponse(str((request.META["SCRIPT_NAME"], request.path_info, locale)))
         
         if localeurl_settings.USE_ACCEPT_LANGUAGE and not locale:
             accept_langs = filter(lambda x: x, 
                                   [utils.supported_language(lang[0])
                                    for lang in parse_accept_lang_header(
                                    request.META.get('HTTP_ACCEPT_LANGUAGE', ''))])
             if accept_langs:
                 locale = accept_langs[0]
         locale_path = utils.locale_path(path, locale)
     
         if locale_path != request.path_info:
             
             full_path = ''.join([request.META["SCRIPT_NAME"], locale_path])
                                       
             query = request.META.get("QUERY_STRING", "")
             if query:
                 full_path = "%s?%s" % (full_path, query)
                 
             return HttpResponsePermanentRedirect(full_path)
         
         request.path_info = path
         if not locale:
             try:
                 locale = request.LANGUAGE_CODE
             except AttributeError:
                 locale = settings.LANGUAGE_CODE
         translation.activate(locale)
         request.LANGUAGE_CODE = locale
Example #34
0
def rmlocale(url):
    """Removes the locale prefix from the URL."""
    script_prefix, path = utils.strip_script_prefix(url)
    _, path = utils.strip_path(path)
    return ''.join([script_prefix, path])
Example #35
0
def rmlocale(url):
    """Removes the locale prefix from the URL."""
    script_prefix, path = utils.strip_script_prefix(url)
    _, path = utils.strip_path(path)
    return ''.join([script_prefix, path])
Example #36
0
 def test_strip_path_takes_longer_code_first(self):
     # Refs issue #15.
     self.assertEqual(('pt-br', '/about/localeurl/'),
                      utils.strip_path('/pt-br/about/localeurl/'))
Example #37
0
 def parse_url(self, url):
     parsed = urlparse(url)
     locale, path = strip_path(parsed.path)
     return path, parse_qs(parsed.query)
Example #38
0
 def user_object_localeurl(self, user, obj):
     l = self.get_user_language_code(user)
     url = locale_url(strip_path(obj.get_absolute_url())[1], l)
     return url
Example #39
0
 def test_strip_path_takes_longer_code_first(self):
     # Refs issue #15.
     self.assertEqual(('pt-br', '/about/localeurl/'),
             utils.strip_path('/pt-br/about/localeurl/'))
Example #40
0
 def change_language_in_path(path, language):
     locale,path = utils.strip_path(path)
     if locale:
         return utils.locale_path(path, language)
     else:
         return path
Example #41
0
def profile_edit(request, username, edit_profile_form=I4PEditProfileForm,
                 template_name='userena/profile_form.html', success_url=None,
                 extra_context=None):
    """
    Custom version of userena's profile edit, with the three following forms:
     - Profile edition ;
     - Password update ;
     - Email update.
    """
    current_user = request.user

    requested_user = get_object_or_404(User,
                                       username__iexact=username)

    profile = requested_user.get_profile()

    if not current_user.has_perm('change_profile', profile):
        return HttpResponseForbidden()

    user_initial = {'first_name': requested_user.first_name,
                    'last_name': requested_user.last_name}

    if not extra_context:
        extra_context = {}

    # From userena. 
    form = edit_profile_form(instance=profile, initial=user_initial)

    # Also pass the password and email forms
    extra_context.update({'password_form': PasswordChangeForm(user=current_user),
                          'email_form': ChangeEmailForm(user=current_user),
                          'profile_form': form}
                         )


    if request.method == 'POST':
        form = edit_profile_form(request.POST, request.FILES, instance=profile,
                                 initial=user_initial)

        if form.is_valid():
            profile = form.save()

            if userena_settings.USERENA_USE_MESSAGES:
                messages.success(request, _('Your profile has been updated.'),
                                 fail_silently=True)

            if success_url: redirect_to = success_url
            else: redirect_to = reverse('userena_profile_detail', kwargs={'username': username})

            # Ensure the redirect URL locale prefix matches the profile locale
            _locale, path = strip_path(redirect_to)
            redirect_to = locale_url(path, locale=profile.language)
            request.session['django_language'] = profile.language

            return redirect(redirect_to)

    if not extra_context: extra_context = dict()
    extra_context['form'] = form
    extra_context['profile'] = profile
    return direct_to_template(request,
                              template_name,
                              extra_context=extra_context)
Example #42
0
def jsurls(request):
    # Get locale_prefix if set by django-localeurl
    locale_prefix, _path = strip_path(request.path)

    # Pattern for recognizing named parameters in urls
    RE_KWARG = re.compile(r"(\(\?P\<(.*?)\>.*?\))")
    # Pattern for recognizing unnamed url parameters
    RE_ARG = re.compile(r"(\(.*?\))")

    def handle_url_module(js_patterns, module_name, prefix="", namespace="",
                          locale_prefix=''):
        """
        Load the module and output all of the patterns
        Recurse on the included modules
        """
        if isinstance(module_name, basestring):
            __import__(module_name)
            root_urls = sys.modules[module_name]
            patterns = root_urls.urlpatterns
        elif isinstance(module_name, types.ModuleType):
            root_urls = module_name
            patterns = root_urls.urlpatterns
        else:
            root_urls = module_name
            patterns = root_urls

        for pattern in patterns:
            if issubclass(pattern.__class__, RegexURLPattern):
                if pattern.name:
                    pattern_name = u':'.join((namespace, pattern.name)) if \
                                                    namespace else pattern.name
                    full_url = prefix + pattern.regex.pattern
                    for chr in ["^", "$"]:
                        full_url = full_url.replace(chr, "")
                    # Handle kwargs, args
                    kwarg_matches = RE_KWARG.findall(full_url)
                    if kwarg_matches:
                        for el in kwarg_matches:
                            # Prepare the output for JS resolver
                            full_url = full_url.replace(el[0], "<%s>" % el[1])
                    # After processing all kwargs try args
                    args_matches = RE_ARG.findall(full_url)
                    if args_matches:
                        for el in args_matches:
                            # Replace by a empty parameter name
                            full_url = full_url.replace(el, "<>")
                    # Add locale to path if django-localeurl is installed
                    full_url = locale_url("/" + full_url, locale=locale_prefix)
                    js_patterns[pattern_name] = full_url
            elif issubclass(pattern.__class__, RegexURLResolver):
                if ALLOWED_NAMESPACES is None:
                    pass
                elif pattern.namespace not in ALLOWED_NAMESPACES:
                    continue

                if pattern.urlconf_name:
                    handle_url_module(js_patterns, pattern.urlconf_name,
                                      prefix=pattern.regex.pattern,
                                      namespace=pattern.namespace,
                                      locale_prefix=locale_prefix)

    js_patterns = SortedDict()
    handle_url_module(js_patterns, settings.ROOT_URLCONF,
                      locale_prefix=locale_prefix)

    from django.template.loader import get_template

    response = HttpResponse(mimetype='text/javascript')
    response.write('django_js_utils_urlconf = ')
    json.dump(js_patterns, response)
    return response