def no_lang(self):
     resp = Response()
     set_lang(None)
     resp.write(_("No language"))
     set_lang([])
     resp.write(_("No languages"))
     return resp
Example #2
0
    def __call__(self, environ, start_response):
        cl_key = "CONTENT_LENGTH"
        if environ["REQUEST_METHOD"] == "POST":
            if (cl_key not in environ) or int(environ[cl_key]) > self.max_size:
                r = Response()
                r.status_code = 500
                r.content = '<html><head></head><body><script type="text/javascript">parent.too_big();</script>request too big</body></html>'
                return r(environ, start_response)

        return self.app(environ, start_response)
Example #3
0
    def __call__(self, environ, start_response):
        cl_key = 'CONTENT_LENGTH'
        if environ['REQUEST_METHOD'] == 'POST':
            if cl_key not in environ:
                r = Response()
                r.status_code = 411
                r.content = '<html><head></head><body>length required</body></html>'
                return r(environ, start_response)

            try:
                cl_int = int(environ[cl_key])
            except ValueError:
                r = Response()
                r.status_code = 400
                r.content = '<html><head></head><body>bad request</body></html>'
                return r(environ, start_response)

            if cl_int > self.max_size:
                from r2.lib.strings import string_dict
                error_msg = string_dict['css_validator_messages']['max_size'] % dict(max_size = self.max_size/1024)
                r = Response()
                r.status_code = 413
                r.content = ("<html>"
                             "<head>"
                             "<script type='text/javascript'>"
                             "parent.completedUploadImage('failed',"
                             "''," 
                             "''," 
                             "[['BAD_CSS_NAME', ''], ['IMAGE_ERROR', '", error_msg,"']],"
                             "'image-upload');"
                             "</script></head><body>you shouldn\'t be here</body></html>")
                return r(environ, start_response)

        return self.app(environ, start_response)
Example #4
0
    def __call__(self, environ, start_response):
        g = config["pylons.g"]
        http_host = environ.get("HTTP_HOST", "localhost").lower()
        domain, s, port = http_host.partition(":")

        # remember the port
        try:
            environ["request_port"] = int(port)
        except ValueError:
            pass

        # localhost is exempt so paster run/shell will work
        # media_domain doesn't need special processing since it's just ads
        if domain == "localhost" or is_subdomain(domain, g.media_domain):
            return self.app(environ, start_response)

        # tell reddit_base to redirect to the appropriate subreddit for
        # a legacy CNAME
        if not is_subdomain(domain, g.domain):
            environ["legacy-cname"] = domain
            return self.app(environ, start_response)

        # figure out what subdomain we're on if any
        subdomains = domain[: -len(g.domain) - 1].split(".")
        extension_subdomains = dict(m="mobile", i="compact", api="api", rss="rss", xml="xml", json="json")

        sr_redirect = None
        for subdomain in subdomains[:]:
            if subdomain in g.reserved_subdomains:
                continue

            extension = extension_subdomains.get(subdomain)
            if extension:
                environ["reddit-domain-extension"] = extension
            elif self.lang_re.match(subdomain):
                environ["reddit-prefer-lang"] = subdomain
                environ["reddit-domain-prefix"] = subdomain
            else:
                sr_redirect = subdomain
                subdomains.remove(subdomain)

        # if there was a subreddit subdomain, redirect
        if sr_redirect and environ.get("FULLPATH"):
            r = Response()
            if not subdomains and g.domain_prefix:
                subdomains.append(g.domain_prefix)
            subdomains.append(g.domain)
            redir = "%s/r/%s/%s" % (".".join(subdomains), sr_redirect, environ["FULLPATH"])
            redir = "http://" + redir.replace("//", "/")
            r.status_code = 301
            r.headers["location"] = redir
            r.content = ""
            return r(environ, start_response)

        return self.app(environ, start_response)
Example #5
0
    def __call__(self, environ, start_response):
        cl_key = 'CONTENT_LENGTH'
        if environ['REQUEST_METHOD'] == 'POST':
            if ((cl_key not in environ)
                or int(environ[cl_key]) > self.max_size):
                r = Response()
                r.status_code = 500
                r.content = '<html><head></head><body><script type="text/javascript">parent.too_big();</script>request too big</body></html>'
                return r(environ, start_response)

        return self.app(environ, start_response)
Example #6
0
    def listing(self):
        """Listing to generate from the builder"""
        if (getattr(c.site, "_id", -1) == get_promote_srid()
                and not c.user_is_sponsor):
            abort(403, 'forbidden')
        listing = LinkListing(self.builder_obj, show_nums=self.show_nums)
        try:
            return listing.listing()
        except SolrError, e:
            errmsg = "SolrError: %r %r" % (e, self.builder_obj)

            if (str(e) == 'None'):
                # Production error logs only get non-None errors
                g.log.debug(errmsg)
            else:
                g.log.error(errmsg)

            sf = SearchFail()

            us = unsafe(sf.render())

            errpage = pages.RedditError(_('search failed'), us)

            c.response = Response()
            c.response.status_code = 503
            request.environ['usable_error_content'] = errpage.render()
            request.environ['retry_after'] = 60

            abort(503)
Example #7
0
    def search_fail(self, exception):
        from r2.lib.contrib.pysolr import SolrError
        from r2.lib.indextank import IndextankException
        if isinstance(exception, SolrError):
            errmsg = "SolrError: %r" % exception

            if (str(exception) == 'None'):
                # Production error logs only get non-None errors
                g.log.debug(errmsg)
            else:
                g.log.error(errmsg)
        elif isinstance(exception, (IndextankException, socket.error)):
            g.log.error("IndexTank Error: %s" % repr(exception))

        sf = pages.SearchFail()

        us = filters.unsafe(sf.render())

        errpage = pages.RedditError(_('search failed'), us)

        c.response = Response()
        c.response.status_code = 503
        request.environ['usable_error_content'] = errpage.render()
        request.environ['retry_after'] = 60

        abort(503)
Example #8
0
    def __call__(self, environ, start_response):
        true_client_ip = environ.get('HTTP_TRUE_CLIENT_IP')
        ip_hash = environ.get('HTTP_TRUE_CLIENT_IP_HASH')
        forwarded_for = environ.get('HTTP_X_FORWARDED_FOR', ())
        remote_addr = environ.get('REMOTE_ADDR')

        if (g.ip_hash
            and true_client_ip
            and ip_hash
            and hashlib.md5(true_client_ip + g.ip_hash).hexdigest() \
            == ip_hash.lower()):
            request.ip = true_client_ip
        elif remote_addr in g.proxy_addr and forwarded_for:
            request.ip = forwarded_for.split(',')[-1]
        else:
            request.ip = environ['REMOTE_ADDR']

        #if x-dont-decode is set, pylons won't unicode all the paramters
        if environ.get('HTTP_X_DONT_DECODE'):
            request.charset = None

        request.get = storify(request.GET)
        request.post = storify(request.POST)
        request.referer = environ.get('HTTP_REFERER')
        request.path = environ.get('PATH_INFO')
        request.user_agent = environ.get('HTTP_USER_AGENT')
        request.fullpath = environ.get('FULLPATH', request.path)
        request.port = environ.get('request_port')
        
        if_modified_since = environ.get('HTTP_IF_MODIFIED_SINCE')
        if if_modified_since:
            request.if_modified_since = read_http_date(if_modified_since)
        else:
            request.if_modified_since = None

        #set the function to be called
        action = request.environ['pylons.routes_dict'].get('action')
        if action:
            meth = request.method.upper()
            if meth == 'HEAD':
                meth = 'GET'
            request.environ['pylons.routes_dict']['action'] = \
                    meth + '_' + action

        c.thread_pool = environ['paste.httpserver.thread_pool']

        c.response = Response()
        try:
            res = WSGIController.__call__(self, environ, start_response)
        except Exception as e:
            if g.exception_logging:
                try:
                    log_exception(e, *sys.exc_info())
                except Exception as f:
                    print "log_exception() freaked out: %r" % f
                    print "sorry for breaking the stack trace:"
            raise
        return res
Example #9
0
def validate_id(func, self, id, *args, **kwargs):
    if c.auth_user and c.view_user and c.auth_user.canManage(c.view_user):
        if c.view_user and c.auth_user.canManage(c.view_user):
            c.admin_server = model.Server.get_by(id=id)
            return func(self, id, *args, **kwargs)
        else:
            return Response("Not your server")
    else:
        h.redirect_to('login')
Example #10
0
 def filter(self, execution_func, prof_arg=None):
     # put thie imports here so the app doesn't choke if profiling
     # is not present (this is a debug-only feature anyway)
     import cProfile as profile
     from pstats import Stats
     from r2.lib.contrib import gprof2dot
     # profiling needs an actual file to dump to.  Everything else
     # can be mitigated with streams
     tmpfile = tempfile.NamedTemporaryFile()
     dotfile = StringIO()
     # simple cutoff validation
     try:
         cutoff = .01 if prof_arg is None else float(prof_arg) / 100
     except ValueError:
         cutoff = .01
     try:
         # profile the code in the current context
         profile.runctx('execution_func()', globals(), locals(),
                        tmpfile.name)
         # parse the data
         parser = gprof2dot.PstatsParser(tmpfile.name)
         prof = parser.parse()
         # remove nodes and edges with less than cutoff work
         prof.prune(cutoff, cutoff)
         # make the dotfile
         dot = gprof2dot.DotWriter(dotfile)
         dot.graph(prof, gprof2dot.TEMPERATURE_COLORMAP)
         # convert the dotfile to PNG in local stdout
         proc = subprocess.Popen("dot -Tpng",
                                 shell=True,
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
         out, error = proc.communicate(input=dotfile.getvalue())
         # generate the response
         r = Response()
         r.status_code = 200
         r.headers['content-type'] = "image/png"
         r.content = out
         return r
     finally:
         tmpfile.close()
Example #11
0
 def filter(self, execution_func, prof_arg = None):
     # put thie imports here so the app doesn't choke if profiling
     # is not present (this is a debug-only feature anyway)
     import cProfile as profile
     from pstats import Stats
     from r2.lib.contrib import gprof2dot
     # profiling needs an actual file to dump to.  Everything else
     # can be mitigated with streams
     tmpfile = tempfile.NamedTemporaryFile()
     dotfile = StringIO()
     # simple cutoff validation
     try:
         cutoff = .01 if prof_arg is None else float(prof_arg)/100
     except ValueError:
         cutoff = .01
     try:
         # profile the code in the current context
         profile.runctx('execution_func()',
                        globals(), locals(), tmpfile.name)
         # parse the data
         parser = gprof2dot.PstatsParser(tmpfile.name)
         prof = parser.parse()
         # remove nodes and edges with less than cutoff work
         prof.prune(cutoff, cutoff)
         # make the dotfile
         dot = gprof2dot.DotWriter(dotfile)
         dot.graph(prof, gprof2dot.TEMPERATURE_COLORMAP)
         # convert the dotfile to PNG in local stdout
         proc = subprocess.Popen("dot -Tpng",
                                 shell = True,
                                 stdin =subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
         out, error =  proc.communicate(input = dotfile.getvalue())
         # generate the response
         r = Response()
         r.status_code = 200
         r.headers['content-type'] = "image/png"
         r.content = out
         return r
     finally:
         tmpfile.close()
Example #12
0
    def GET_s(self, rest):
        """/s/http://..., show a given URL with the toolbar. if it's
           submitted, redirect to /tb/$id36"""
        force_html()
        path = demangle_url(request.fullpath)

        if not path:
            # it was malformed
            self.abort404()

        # if the domain is shame-banned, bail out.
        if is_shamed_domain(path, request.ip)[0]:
            self.abort404()

        link = utils.link_from_url(path, multiple=False)

        if c.cname and not c.authorized_cname:
            # In this case, we make some bad guesses caused by the
            # cname frame on unauthorised cnames.
            # 1. User types http://foo.com/http://myurl?cheese=brie
            #    (where foo.com is an unauthorised cname)
            # 2. We generate a frame that points to
            #    http://www.reddit.com/r/foo/http://myurl?cnameframe=0.12345&cheese=brie
            # 3. Because we accept everything after the /r/foo/, and
            #    we've now parsed, modified, and reconstituted that
            #    URL to add cnameframe, we really can't make any good
            #    assumptions about what we've done to a potentially
            #    already broken URL, and we can't assume that we've
            #    rebuilt it in the way that it was originally
            #    submitted (if it was)
            # We could try to work around this with more guesses (by
            # having demangle_url try to remove that param, hoping
            # that it's not already a malformed URL, and that we
            # haven't re-ordered the GET params, removed
            # double-slashes, etc), but for now, we'll just refuse to
            # do this operation
            return self.abort404()

        if link:
            # we were able to find it, let's send them to the
            # link-id-based URL so that their URL is reusable
            return self.redirect(add_sr("/tb/" + link._id36))

        title = utils.domain(path)
        res = Frame(title=title, url=path)

        # we don't want clients to think that this URL is actually a
        # valid URL for search-indexing or the like
        c.response = Response()
        c.response.status_code = 404
        request.environ['usable_error_content'] = spaceCompress(res.render())

        return c.response
Example #13
0
    def __call__(self, environ, start_response):
        # get base domain as defined in INI file
        base_domain = config['global_conf']['domain']

        sub_domains = environ['HTTP_HOST']
        if not sub_domains.endswith(base_domain):
            #if the domain doesn't end with base_domain, don't do anything
            return self.app(environ, start_response)

        sub_domains = sub_domains[:-len(base_domain)].strip('.')
        sub_domains = sub_domains.split('.')

        sr_redirect = None
        for sd in list(sub_domains):
            # subdomains to disregard completely
            if sd in ('www', 'origin', 'beta'):
                continue
            # subdomains which change the extension
            elif sd == 'm':
                environ['reddit-domain-extension'] = 'mobile'
            elif sd in ('api', 'rss', 'xml', 'json'):
                environ['reddit-domain-extension'] = sd
            elif (len(sd) == 2 or (len(sd) == 5 and sd[2] == '-')) and self.lang_re.match(sd):
                environ['reddit-prefer-lang'] = sd
            else:
                sr_redirect = sd
                sub_domains.remove(sd)

        if sr_redirect and environ.get("FULLPATH"):
            r = Response()
            sub_domains.append(base_domain)
            redir = "%s/r/%s/%s" % ('.'.join(sub_domains),
                                    sr_redirect, environ['FULLPATH'])
            redir = "http://" + redir.replace('//', '/')
            r.status_code = 301
            r.headers['location'] = redir
            r.content = ""
            return r(environ, start_response)
        
        return self.app(environ, start_response)
Example #14
0
 def no_lang(self):
     resp = Response()
     set_lang(None)
     resp.write(_('No language'))
     set_lang([])
     resp.write(_('No languages'))
     return resp
Example #15
0
    def __call__(self, environ, start_response):
        true_client_ip = environ.get('HTTP_TRUE_CLIENT_IP')
        ip_hash = environ.get('HTTP_TRUE_CLIENT_IP_HASH')
        forwarded_for = environ.get('HTTP_X_FORWARDED_FOR', ())
        remote_addr = environ.get('REMOTE_ADDR')

        if (g.ip_hash
            and true_client_ip
            and ip_hash
            and md5.new(true_client_ip + g.ip_hash).hexdigest() \
            == ip_hash.lower()):
            request.ip = true_client_ip
        elif g.trust_local_proxies and forwarded_for and is_local_address(
                remote_addr):
            request.ip = forwarded_for.split(',')[-1]
        else:
            request.ip = environ['REMOTE_ADDR']

        #if x-dont-decode is set, pylons won't unicode all the paramters
        if environ.get('HTTP_X_DONT_DECODE'):
            request.charset = None

        request.get = storify(request.GET)
        request.post = storify(request.POST)
        request.referer = environ.get('HTTP_REFERER')
        request.path = _force_utf8(environ.get(
            'PATH_INFO'))  # Enforce only valid utf8 chars in request path
        request.user_agent = environ.get('HTTP_USER_AGENT')
        request.fullpath = environ.get('FULLPATH', request.path)
        request.port = environ.get('request_port')

        if_modified_since = environ.get('HTTP_IF_MODIFIED_SINCE')
        if if_modified_since:
            request.if_modified_since = read_http_date(if_modified_since)
        else:
            request.if_modified_since = None

        #set the function to be called
        action = request.environ['pylons.routes_dict'].get('action')
        if action:
            meth = request.method.upper()
            if meth == 'HEAD':
                meth = 'GET'
            request.environ['pylons.routes_dict']['action'] = \
                    meth + '_' + action

        c.response = Response()
        res = WSGIController.__call__(self, environ, start_response)
        return res
Example #16
0
    def __call__(self, environ, start_response):
        cl_key = 'CONTENT_LENGTH'
        if environ['REQUEST_METHOD'] == 'POST':
            if cl_key not in environ:
                r = Response()
                r.status_code = 411
                r.content = '<html><head></head><body>length required</body></html>'
                return r(environ, start_response)

            try:
                cl_int = int(environ[cl_key])
            except ValueError:
                r = Response()
                r.status_code = 400
                r.content = '<html><head></head><body>bad request</body></html>'
                return r(environ, start_response)

            if cl_int > self.max_size:
                r = Response()
                r.status_code = 413
                r.content = '<html><head></head><body><script type="text/javascript">parent.too_big();</script>request entity too large</body></html>'
                return r(environ, start_response)

        return self.app(environ, start_response)
Example #17
0
    def _search(self, query_obj, num, after, reverse, count=0):
        """Helper function for interfacing with search.  Basically a
        thin wrapper for SearchBuilder."""

        builder = SearchBuilder(query_obj,
                                after=after,
                                num=num,
                                reverse=reverse,
                                count=count,
                                wrap=ListingController.builder_wrapper)

        listing = LinkListing(builder, show_nums=True)

        # have to do it in two steps since total_num and timing are only
        # computed after fetch_more
        try:
            res = listing.listing()
        except SolrError, e:
            try:
                errmsg = "SolrError: %r %r" % (e, query_obj)
            except UnicodeEncodeError:
                errmsg = "SolrError involving unicode"

            if (str(e) == 'None'):
                # Production error logs only get non-None errors
                g.log.debug(errmsg)
            else:
                g.log.error(errmsg)

            sf = SearchFail()
            sb = SearchBar(prev_search=query_obj.q)

            us = unsafe(sb.render() + sf.render())

            errpage = pages.RedditError(_('search failed'), us)

            c.response = Response()
            c.response.status_code = 503
            request.environ['usable_error_content'] = errpage.render()
            request.environ['retry_after'] = 60

            abort(503)
Example #18
0
 def test_keyslist_cache_decorator(self, id, id2="123"):
     pylons.g.counter += 1
     return Response('Counter=%s, id=%s' % (pylons.g.counter, id))
Example #19
0
 def test_expire_cache_decorator(self):
     pylons.g.counter += 1
     return Response('Counter=%s' % pylons.g.counter)
Example #20
0
 def session_increment(self):
     session.setdefault('counter', -1)
     session['counter'] += 1
     session.save()
     return Response('session incrementer')
Example #21
0
    def __call__(self, environ, start_response):
        cl_key = 'CONTENT_LENGTH'
        if environ['REQUEST_METHOD'] == 'POST':
            if cl_key not in environ:
                r = Response()
                r.status_code = 411
                r.content = '<html><head></head><body>length required</body></html>'
                return r(environ, start_response)

            try:
                cl_int = int(environ[cl_key])
            except ValueError:
                r = Response()
                r.status_code = 400
                r.content = '<html><head></head><body>bad request</body></html>'
                return r(environ, start_response)

            if cl_int > self.max_size:
                r = Response()
                r.status_code = 413
                r.content = '<html><head></head><body><script type="text/javascript">parent.too_big();</script>request entity too large</body></html>'
                return r(environ, start_response)

        return self.app(environ, start_response)
Example #22
0
    def __call__(self, environ, start_response):
        cl_key = 'CONTENT_LENGTH'
        if environ['REQUEST_METHOD'] == 'POST':
            if cl_key not in environ:
                r = Response()
                r.status_code = 411
                r.content = '<html><head></head><body>length required</body></html>'
                return r(environ, start_response)

            try:
                cl_int = int(environ[cl_key])
            except ValueError:
                r = Response()
                r.status_code = 400
                r.content = '<html><head></head><body>bad request</body></html>'
                return r(environ, start_response)

            if cl_int > self.max_size:
                from r2.lib.strings import string_dict
                error_msg = string_dict['css_validator_messages'][
                    'max_size'] % dict(max_size=self.max_size / 1024)
                r = Response()
                r.status_code = 413
                r.content = (
                    "<html>"
                    "<head>"
                    "<script type='text/javascript'>"
                    "parent.completedUploadImage('failed',"
                    "'',"
                    "'',"
                    "[['BAD_CSS_NAME', ''], ['IMAGE_ERROR', '", error_msg,
                    "']],"
                    "'image-upload');"
                    "</script></head><body>you shouldn\'t be here</body></html>"
                )
                return r(environ, start_response)

        return self.app(environ, start_response)
Example #23
0
 def test_only_get(self):
     return Response('It was a get!')
Example #24
0
 def test_default_cache_decorator(self):
     g.counter += 1
     return Response('Counter=%s' % g.counter)
Example #25
0
 def impossible(self):
     return Response('This should never be shown')
Example #26
0
 def i18n_index(self):
     locale_list = request.languages
     set_lang(request.languages)
     return Response(unicode(_('basic index page')))
Example #27
0
 def deprecated_h(self):
     return Response('%s is %s' % \
                         (h.url_for(), deprecated_h.url_for()))
Example #28
0
 def myself(self):
     return Response(h.url_for())
Example #29
0
    def __call__(self, environ, start_response):
        # get base domain as defined in INI file
        base_domain = config["global_conf"]["domain"]
        try:
            sub_domains, request_port = environ["HTTP_HOST"].split(":")
            environ["request_port"] = int(request_port)
        except ValueError:
            sub_domains = environ["HTTP_HOST"].split(":")[0]
        except KeyError:
            sub_domains = "localhost"

        # If the domain doesn't end with base_domain, assume
        # this is a cname, and redirect to the frame controller.
        # Ignore localhost so paster shell still works.
        # If this is an error, don't redirect
        if not sub_domains.endswith(base_domain) and (not sub_domains == "localhost"):
            environ["sub_domain"] = sub_domains
            if not environ.get("extension"):
                if environ["PATH_INFO"].startswith("/frame"):
                    return self.app(environ, start_response)
                elif self.is_auth_cname(sub_domains):
                    environ["frameless_cname"] = True
                    environ["authorized_cname"] = True
                elif (
                    "redditSession=cname" in environ.get("HTTP_COOKIE", "")
                    and environ["REQUEST_METHOD"] != "POST"
                    and not environ["PATH_INFO"].startswith("/error")
                ):
                    environ["original_path"] = environ["PATH_INFO"]
                    environ["FULLPATH"] = environ["PATH_INFO"] = "/frame"
                else:
                    environ["frameless_cname"] = True
            return self.app(environ, start_response)

        sub_domains = sub_domains[: -len(base_domain)].strip(".")
        sub_domains = sub_domains.split(".")

        sr_redirect = None
        for sd in list(sub_domains):
            # subdomains to disregard completely
            if sd in ("www", "origin", "beta", "lab", "pay", "buttons", "ssl"):
                continue
            # subdomains which change the extension
            elif sd == "m":
                environ["reddit-domain-extension"] = "mobile"
            elif sd == "I":
                environ["reddit-domain-extension"] = "compact"
            elif sd == "i":
                environ["reddit-domain-extension"] = "compact"
            elif sd in ("api", "rss", "xml", "json"):
                environ["reddit-domain-extension"] = sd
            elif (len(sd) == 2 or (len(sd) == 5 and sd[2] == "-")) and self.lang_re.match(sd):
                environ["reddit-prefer-lang"] = sd
                environ["reddit-domain-prefix"] = sd
            else:
                sr_redirect = sd
                sub_domains.remove(sd)

        if sr_redirect and environ.get("FULLPATH"):
            r = Response()
            sub_domains.append(base_domain)
            redir = "%s/r/%s/%s" % (".".join(sub_domains), sr_redirect, environ["FULLPATH"])
            redir = "http://" + redir.replace("//", "/")
            r.status_code = 301
            r.headers["location"] = redir
            r.content = ""
            return r(environ, start_response)

        return self.app(environ, start_response)
Example #30
0
 def global_store(self, id):
     if id:
         g.counter += int(id)
     return Response(str(g.counter))
Example #31
0
 def test_only_post(self):
     return Response('It was a post!')
Example #32
0
 def globalup(self):
     return Response(g.message)
Example #33
0
 def myparams(self):
     return Response(str(request.params))
Example #34
0
    def __call__(self, environ, start_response):
        # get base domain as defined in INI file
        base_domain = config['global_conf']['domain']
        try:
            sub_domains, request_port  = environ['HTTP_HOST'].split(':')
            environ['request_port'] = int(request_port)
        except ValueError:
            sub_domains = environ['HTTP_HOST'].split(':')[0]
        except KeyError:
            sub_domains = "localhost"

        #If the domain doesn't end with base_domain, assume
        #this is a cname, and redirect to the frame controller.
        #Ignore localhost so paster shell still works.
        #If this is an error, don't redirect

        if (not sub_domains.endswith(base_domain)
            and (not sub_domains == 'localhost')):
            environ['sub_domain'] = sub_domains
            if not environ.get('extension'):
                if environ['PATH_INFO'].startswith('/frame'):
                    return self.app(environ, start_response)
                elif self.is_auth_cname(sub_domains):
                    environ['frameless_cname'] = True
                    environ['authorized_cname'] = True
                elif ("redditSession" in environ.get('HTTP_COOKIE', '')
                      and environ['REQUEST_METHOD'] != 'POST'
                      and not environ['PATH_INFO'].startswith('/error')):
                    environ['original_path'] = environ['PATH_INFO']
                    environ['PATH_INFO'] = '/frame'
                else:
                    environ['frameless_cname'] = True
            return self.app(environ, start_response)

        sub_domains = sub_domains[:-len(base_domain)].strip('.')
        sub_domains = sub_domains.split('.')

        sr_redirect = None
        for sd in list(sub_domains):
            # subdomains to disregard completely
            if sd in ('www', 'origin', 'beta'):
                continue
            # subdomains which change the extension
            elif sd == 'm':
                environ['reddit-domain-extension'] = 'mobile'
            elif sd in ('api', 'rss', 'xml', 'json'):
                environ['reddit-domain-extension'] = sd
            elif (len(sd) == 2 or (len(sd) == 5 and sd[2] == '-')) and self.lang_re.match(sd):
                environ['reddit-prefer-lang'] = sd
            else:
                sr_redirect = sd
                sub_domains.remove(sd)

        if sr_redirect and environ.get("FULLPATH"):
            r = Response()
            sub_domains.append(base_domain)
            redir = "%s/r/%s/%s" % ('.'.join(sub_domains),
                                    sr_redirect, environ['FULLPATH'])
            redir = "http://" + redir.replace('//', '/')
            r.status_code = 301
            r.headers['location'] = redir
            r.content = ""
            return r(environ, start_response)

        return self.app(environ, start_response)
Example #35
0
    def __call__(self, environ, start_response):
        g = config['pylons.g']
        http_host = environ.get('HTTP_HOST', 'localhost').lower()
        domain, s, port = http_host.partition(':')

        # remember the port
        try:
            environ['request_port'] = int(port)
        except ValueError:
            pass

        # localhost is exempt so paster run/shell will work
        # media_domain doesn't need special processing since it's just ads
        if domain == "localhost" or is_subdomain(domain, g.media_domain):
            return self.app(environ, start_response)

        # tell reddit_base to redirect to the appropriate subreddit for
        # a legacy CNAME
        if not is_subdomain(domain, g.domain):
            environ['legacy-cname'] = domain
            return self.app(environ, start_response)

        # figure out what subdomain we're on if any
        subdomains = domain[:-len(g.domain) - 1].split('.')
        extension_subdomains = dict(m="mobile",
                                    i="compact",
                                    api="api",
                                    rss="rss",
                                    xml="xml",
                                    json="json")

        sr_redirect = None
        for subdomain in subdomains[:]:
            if subdomain in g.reserved_subdomains:
                continue

            extension = extension_subdomains.get(subdomain)
            if extension:
                environ['reddit-domain-extension'] = extension
            elif self.lang_re.match(subdomain):
                environ['reddit-prefer-lang'] = subdomain
                environ['reddit-domain-prefix'] = subdomain
            else:
                sr_redirect = subdomain
                subdomains.remove(subdomain)

        # if there was a subreddit subdomain, redirect
        if sr_redirect and environ.get("FULLPATH"):
            r = Response()
            if not subdomains and g.domain_prefix:
                subdomains.append(g.domain_prefix)
            subdomains.append(g.domain)
            redir = "%s/r/%s/%s" % ('.'.join(subdomains), sr_redirect,
                                    environ['FULLPATH'])
            redir = "http://" + redir.replace('//', '/')
            r.status_code = 301
            r.headers['location'] = redir
            r.content = ""
            return r(environ, start_response)

        return self.app(environ, start_response)
Example #36
0
        c.test = "This is in c var"
        return render_response('testcheetah')

    def set_lang(self):
        lang = request.GET['lang']
        try:
            set_lang(lang)
        except (LanguageError, IOError), e:
            resp_unicode = _('Could not set language to "%(lang)s"') % {
                'lang': lang
            }
        else:
            session['lang'] = lang
            session.save()
            resp_unicode = _('Set language to "%(lang)s"') % {'lang': lang}
        return Response(resp_unicode)

    def i18n_index(self):
        locale_list = request.languages
        set_lang(request.languages)
        return Response(unicode(_('basic index page')))

    def no_lang(self):
        resp = Response()
        set_lang(None)
        resp.write(_('No language'))
        set_lang([])
        resp.write(_('No languages'))
        return resp

    def deprecated_h(self):
Example #37
0
 def test_get_cache_default(self):
     pylons.g.counter += 1
     return Response('Counter=%s' % pylons.g.counter)
Example #38
0
    def __call__(self, environ, start_response):
        # get base domain as defined in INI file
        base_domain = config['global_conf']['domain']
        try:
            sub_domains, request_port  = environ['HTTP_HOST'].split(':')
            environ['request_port'] = int(request_port)
        except ValueError:
            sub_domains = environ['HTTP_HOST'].split(':')[0]
        except KeyError:
            sub_domains = "localhost"

        #If the domain doesn't end with base_domain, assume
        #this is a cname, and redirect to the frame controller.
        #Ignore localhost so paster shell still works.
        #If this is an error, don't redirect
        if (not sub_domains.endswith(base_domain)
            and (not sub_domains == 'localhost')):
            environ['sub_domain'] = sub_domains
            if not environ.get('extension'):
                if environ['PATH_INFO'].startswith('/frame'):
                    return self.app(environ, start_response)
                elif self.is_auth_cname(sub_domains):
                    environ['frameless_cname'] = True
                    environ['authorized_cname'] = True
                elif ("redditSession=cname" in environ.get('HTTP_COOKIE', '')
                      and environ['REQUEST_METHOD'] != 'POST'
                      and not environ['PATH_INFO'].startswith('/error')):
                    environ['original_path'] = environ['PATH_INFO']
                    environ['FULLPATH'] = environ['PATH_INFO'] = '/frame'
                else:
                    environ['frameless_cname'] = True
            return self.app(environ, start_response)

        sub_domains = sub_domains[:-len(base_domain)].strip('.')
        sub_domains = sub_domains.split('.')

        sr_redirect = None
        for sd in list(sub_domains):
            # subdomains to disregard completely
            if sd in ('www', 'origin', 'beta', 'pay'):
                continue
            # subdomains which change the extension
            elif sd == 'm':
                environ['reddit-domain-extension'] = 'mobile'
            elif sd == 'I':
                environ['reddit-domain-extension'] = 'compact'
            elif sd == 'i':
                environ['reddit-domain-extension'] = 'compact'
            elif sd in ('api', 'rss', 'xml', 'json'):
                environ['reddit-domain-extension'] = sd
            elif (len(sd) == 2 or (len(sd) == 5 and sd[2] == '-')) and self.lang_re.match(sd):
                environ['reddit-prefer-lang'] = sd
                environ['reddit-domain-prefix'] = sd
            else:
                sr_redirect = sd
                sub_domains.remove(sd)

        if sr_redirect and environ.get("FULLPATH"):
            r = Response()
            sub_domains.append(base_domain)
            redir = "%s/r/%s/%s" % ('.'.join(sub_domains),
                                    sr_redirect, environ['FULLPATH'])
            redir = "http://" + redir.replace('//', '/')
            r.status_code = 301
            r.headers['location'] = redir
            r.content = ""
            return r(environ, start_response)

        return self.app(environ, start_response)
Example #39
0
 def index(self):
     return Response('basic index page')