def GET_s(self, urloid): """/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)[0]: self.abort404() listing = hot_links_by_url_listing(path, sr=c.site, num=1) link = listing.things[0] if listing.things else None if link: # we were able to find it, let's send them to the # toolbar (if enabled) or comments (if not) return self.redirect(add_sr("/tb/" + link._id36)) else: # It hasn't been submitted yet. Give them a chance to qs = utils.query_string({"url": path}) return self.redirect(add_sr("/submit" + qs))
def url_links_builder(url, exclude=None, num=None, after=None, reverse=None, count=None): from r2.lib.template_helpers import add_sr from r2.models import IDBuilder, Link, NotFound from operator import attrgetter if url.startswith('/'): url = add_sr(url, force_hostname=True) try: links = Link._by_url(url, None) except NotFound: links = [] links = [ link for link in links if link._fullname != exclude ] links.sort(key=attrgetter('num_comments'), reverse=True) # don't show removed links in duplicates unless admin or mod # or unless it's your own post def include_link(link): return (not link._spam or (c.user_is_loggedin and (link.author_id == c.user._id or c.user_is_admin or link.subreddit.is_moderator(c.user)))) builder = IDBuilder([link._fullname for link in links], skip=True, keep_fn=include_link, num=num, after=after, reverse=reverse, count=count) return builder
def GET_wiki_discussions(self, page, num, after, reverse, count): page_url = add_sr("%s/%s" % (c.wiki_base_url, page.name)) builder = url_links_builder(page_url, num=num, after=after, reverse=reverse, count=count) listing = LinkListing(builder).listing() return WikiDiscussions(listing, page=page.name, may_revise=this_may_revise(page)).render()
def url_links_builder(url, exclude=None, num=None, after=None, reverse=None, count=None): from r2.lib.template_helpers import add_sr from r2.models import IDBuilder, Link, NotFound from operator import attrgetter if url.startswith('/'): url = add_sr(url, force_hostname=True) try: links = tup(Link._by_url(url, None)) except NotFound: links = [] links = [ link for link in links if link._fullname != exclude ] links.sort(key=attrgetter('num_comments'), reverse=True) # don't show removed links in duplicates unless admin or mod # or unless it's your own post def include_link(link): return (not link._spam or (c.user_is_loggedin and (link.author_id == c.user._id or c.user_is_admin or link.subreddit.is_moderator(c.user)))) builder = IDBuilder([link._fullname for link in links], skip=True, keep_fn=include_link, num=num, after=after, reverse=reverse, count=count) return builder
def __init__(self, *args, **kwargs): self.base_url = add_sr( "/live/" + c.liveupdate_event._id, force_hostname=True, force_https=c.secure, ) super(LiveUpdateEventEmbed, self).__init__(*args, **kwargs)
def GET_s(self, urloid): """/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)[0]: self.abort404() listing = hot_links_by_url_listing(path, sr=c.site, num=1) link = listing.things[0] if listing.things else None 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 # toolbar (if enabled) or comments (if not) return self.redirect(add_sr("/tb/" + link._id36)) else: # It hasn't been submitted yet. Give them a chance to qs = utils.query_string({"url": path}) return self.redirect(add_sr("/submit?" + qs))
def update_creative(link, az_advertiser): """Add/update a reddit link as an Adzerk Creative""" if getattr(link, 'external_creative_id', None) is not None: az_creative = adzerk_api.Creative.get(link.external_creative_id) else: az_creative = None title = link._fullname url = add_sr(link.url, sr_path=False) if link.is_self else link.url # protocols are case sensitive (lower) in adzerk. # can cause double protocols: # http://Http://www.example.com url = re.sub(r"^(https?)", lambda m: m.group(0).lower(), url, flags=re.I) # as long as there are no 3rd party trackers for the link # it's DNT compliant. DNT_compliant = (not (hasattr(link, 'third_party_tracking_url') or hasattr(link, 'third_party_tracking_url_2'))) d = { 'Body': title, 'ScriptBody': render_link(link), 'AdTypeId': LEADERBOARD_AD_TYPE, 'Alt': '', 'Url': url, 'IsHTMLJS': True, 'IsSync': False, 'IsDeleted': False, 'IsActive': not link._deleted, 'IsNoTrack': DNT_compliant, } if az_creative: changed = update_changed(az_creative, **d) change_strs = make_change_strings(changed) if change_strs: log_text = 'updated %s: ' % az_creative + ', '.join(change_strs) else: log_text = None else: d.update({ 'AdvertiserId': az_advertiser.Id, 'Title': title, }) try: az_creative = adzerk_api.Creative.create(**d) except: raise ValueError(d) link.external_creative_id = az_creative.Id link._commit() log_text = 'created %s' % az_creative if log_text: PromotionLog.add(link, log_text) g.log.info(log_text) return az_creative
def GET_wiki_discussions(self, page, num, after, reverse, count): page_url = add_sr("%s/%s" % (c.wiki_base_url, page.name)) links = url_links(page_url) builder = IDBuilder([ link._fullname for link in links ], num = num, after = after, reverse = reverse, count = count, skip = False) listing = LinkListing(builder).listing() return WikiDiscussions(listing).render()
def _get_related_link_ids(cls, event_id): url = add_sr("/live/%s" % event_id, sr_path=False, force_hostname=True) try: links = tup(Link._by_url(url, sr=None)) except NotFound: links = [] return [link._id for link in links]
def __init__(self): links = self.get_links(c.liveupdate_event._id) self.more_links = len(links) > self.max_links self.links = links[:self.max_links] self.submit_url = "/submit?" + urllib.urlencode({ "url": add_sr("/live/" + c.liveupdate_event._id, sr_path=False, force_hostname=True), "title": c.liveupdate_event.title, }) Templated.__init__(self)
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)[0]: self.abort404() listing = hot_links_by_url_listing(path, sr=c.site, num=1) link = listing.things[0] if listing.things else None 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=match_current_reddit_subdomain(path), ) # we don't want clients to think that this URL is actually a # valid URL for search-indexing or the like request.environ['usable_error_content'] = spaceCompress(res.render()) abort(404)
def valid_feed(name, feedhash, path): if name and feedhash and path: from r2.lib.template_helpers import add_sr path = add_sr(path) try: user = Account._by_name(name) if (user.pref_private_feeds and constant_time_compare(feedhash, make_feedhash(user, path))): return user except NotFound: pass
def intermediate_redirect(cls, form_path): """ Generates a /login or /over18 redirect from the current fullpath, after having properly reformated the path via format_output_url. The reformatted original url is encoded and added as the "dest" parameter of the new url. """ from r2.lib.template_helpers import add_sr dest = cls.format_output_url(request.fullpath) path = add_sr(form_path + query_string({"dest": dest})) return cls.redirect(path)
def valid_feed(name, feedhash, path): if name and feedhash and path: from r2.lib.template_helpers import add_sr path = add_sr(path) try: user = Account._by_name(name) if (user.pref_private_feeds and constant_time_compare( feedhash, make_feedhash(user, path))): return user except NotFound: pass
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)[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=match_current_reddit_subdomain(path), ) # we don't want clients to think that this URL is actually a # valid URL for search-indexing or the like request.environ['usable_error_content'] = spaceCompress(res.render()) abort(404)
def GET_wiki_discussions(self, page, num, after, reverse, count): """Retrieve a list of discussions about this wiki `page`""" page_url = add_sr("%s/%s" % (c.wiki_base_url, page.name)) builder = url_links_builder(page_url, num=num, after=after, reverse=reverse, count=count) listing = LinkListing(builder).listing() return WikiDiscussions(listing, page=page.name, may_revise=this_may_revise(page), sr_path=not c.site.is_homepage).render()
def intermediate_redirect(cls, form_path): """ Generates a /login or /over18 redirect from the current fullpath, after having properly reformated the path via format_output_url. The reformatted original url is encoded and added as the "dest" parameter of the new url. """ from r2.lib.template_helpers import add_sr params = dict(dest=cls.format_output_url(request.fullurl)) if c.extension == "widget" and request.GET.get("callback"): params['callback'] = request.GET.get("callback") path = add_sr(cls.format_output_url(form_path) + query_string(params)) abort(302, location=path)
def intermediate_redirect(cls, form_path, sr_path=True, fullpath=None): """ Generates a /login or /over18 redirect from the specified or current fullpath, after having properly reformated the path via format_output_url. The reformatted original url is encoded and added as the "dest" parameter of the new url. """ from r2.lib.template_helpers import add_sr params = dict(dest=cls.format_output_url(fullpath or request.fullurl)) if c.extension == "widget" and request.GET.get("callback"): params['callback'] = request.GET.get("callback") path = add_sr(cls.format_output_url(form_path) + query_string(params), sr_path=sr_path) abort(302, location=path)
def intermediate_redirect(cls, form_path): """ Generates a /login or /over18 redirect from the current fullpath, after having properly reformated the path via format_output_url. The reformatted original url is encoded and added as the "dest" parameter of the new url. """ from r2.lib.template_helpers import add_sr params = dict(dest=cls.format_output_url(request.fullpath)) if c.extension == "widget" and request.GET.get("callback"): params["callback"] = request.GET.get("callback") path = add_sr(cls.format_output_url(form_path) + query_string(params)) return cls.redirect(path)
def GET_urloid(self, urloid): # they got here from "/http://..." path = demangle_url(request.fullpath) if not path: # malformed URL self.abort404() redir_path = add_sr("/s/" + path) force_html() # Redirect to http://reddit.com/s/http://google.com # rather than http://reddit.com/s/http:/google.com redir_path = self.slash_fixer.sub(r'\1///', redir_path, 1) # ^^^ # 3=2 when it comes to self.redirect() return self.redirect(redir_path)
def url_links_builder(url, exclude=None, num=None, after=None, reverse=None, count=None, public_srs_only=False): from r2.lib.template_helpers import add_sr from r2.models import IDBuilder, Link, NotFound, Subreddit from operator import attrgetter if url.startswith("/"): url = add_sr(url, force_hostname=True) try: links = Link._by_url(url, None) except NotFound: links = [] links = [link for link in links if link._fullname != exclude] if public_srs_only and not c.user_is_admin: subreddits = Subreddit._byID([link.sr_id for link in links], data=True) links = [link for link in links if subreddits[link.sr_id].type != "private"] links.sort(key=attrgetter("num_comments"), reverse=True) # don't show removed links in duplicates unless admin or mod # or unless it's your own post def include_link(link): return not link._spam or ( c.user_is_loggedin and (link.author_id == c.user._id or c.user_is_admin or link.subreddit.is_moderator(c.user)) ) builder = IDBuilder( [link._fullname for link in links], skip=True, keep_fn=include_link, num=num, after=after, reverse=reverse, count=count, ) return builder
def _absolute_url(path): return add_sr(path, force_https=True, sr_path=False)
def GET_listing(self, **env): if request.params.get('sort') == 'rising': return self.redirect(add_sr('/rising')) return ListingController.GET_listing(self, **env)
def GET_goto(self, link1, link2): """Support old /goto?id= urls. deprecated""" link = link2 if link2 else link1 if link: return self.redirect(add_sr("/tb/" + link._id36)) return self.abort404()
def add_ext_to_link(link): url = UrlParser(link.get('href')) if url.is_reddit_url(): link['href'] = add_sr(link.get('href'), sr_path=False)
def GET_linkoid(self, link): if not link: return self.abort404() return self.redirect(add_sr("/tb/" + link._id36))
def make_post_login_url(): return add_sr("/f2p/steam/postlogin")
def update_creative(link, az_advertiser, triggered_by=None): """Add/update a reddit link as an Adzerk Creative""" if getattr(link, 'external_creative_id', None) is not None: az_creative = adzerk_api.Creative.get(link.external_creative_id) else: az_creative = None title = link._fullname url = add_sr(link.url, sr_path=False) if link.is_self else link.url # protocols are case sensitive (lower) in adzerk. # can cause double protocols: # http://Http://www.example.com url = re.sub(r"^(https?)", lambda m: m.group(0).lower(), url, flags=re.I) # as long as there are no 3rd party trackers for the link # it's DNT compliant. DNT_compliant = (link.third_party_tracking is None and link.third_party_tracking_2 is None and not link.moat_tracking and not getattr(link, "moat_engagement_tracking", False)) d = { 'Body': title, 'ScriptBody': render_link(link), 'AdTypeId': LEADERBOARD_AD_TYPE, 'Alt': '', 'Url': url, 'IsHTMLJS': True, 'IsSync': False, 'IsDeleted': False, 'IsActive': not link._deleted, 'IsNoTrack': DNT_compliant, } request_error = None if az_creative: try: changed = update_changed(az_creative, **d) except adzerk_api.AdzerkError as e: request_error = e finally: g.ad_events.adzerk_api_request( request_type="update_creative", thing=link, request_body=d, triggered_by=triggered_by, request_error=request_error, ) if request_error: raise request_error change_strs = make_change_strings(changed) if change_strs: log_text = 'updated %s: ' % az_creative + ', '.join(change_strs) else: log_text = None else: d.update({ 'AdvertiserId': az_advertiser.Id, 'Title': title, }) try: az_creative = adzerk_api.Creative.create(**d) except adzerk_api.AdzerkError as e: request_error = e finally: g.ad_events.adzerk_api_request( request_type="create_creative", thing=link, request_body=d, triggered_by=triggered_by, request_error=request_error, ) if request_error: raise request_error link.external_creative_id = az_creative.Id link._commit() log_text = 'created %s' % az_creative if log_text: PromotionLog.add(link, log_text) g.log.info(log_text) return az_creative
def make_event_url(event_id): return add_sr("/live/%s" % event_id, sr_path=False, force_hostname=True)
def pre(self): record_timings = g.admin_cookie in request.cookies or g.debug admin_bar_eligible = response.content_type == 'text/html' if admin_bar_eligible and record_timings: g.stats.start_logging_timings() # set up stuff needed in base templates at error time here. c.js_preload = JSPreload() MinimalController.pre(self) set_cnameframe() # populate c.cookies unless we're on the unsafe media_domain if request.host != g.media_domain or g.media_domain == g.domain: cookie_counts = collections.Counter() try: for k, v in request.cookies.iteritems(): # minimalcontroller can still set cookies if k not in c.cookies: # we can unquote even if it's not quoted c.cookies[k] = Cookie(value=unquote(v), dirty=False) cookie_counts[Cookie.classify(k)] += 1 except CookieError: #pylons or one of the associated retarded libraries #can't handle broken cookies request.environ['HTTP_COOKIE'] = '' for cookietype, count in cookie_counts.iteritems(): g.stats.simple_event("cookie.%s" % cookietype, count) delete_obsolete_cookies() # the user could have been logged in via one of the feeds maybe_admin = False is_otpcookie_valid = False # no logins for RSS feed unless valid_feed has already been called if not c.user: if c.extension != "rss": authenticate_user() admin_cookie = c.cookies.get(g.admin_cookie) if c.user_is_loggedin and admin_cookie: maybe_admin, first_login = valid_admin_cookie(admin_cookie.value) if maybe_admin: self.enable_admin_mode(c.user, first_login=first_login) else: self.disable_admin_mode(c.user) otp_cookie = read_user_cookie(g.otp_cookie) if c.user_is_loggedin and otp_cookie: is_otpcookie_valid = valid_otp_cookie(otp_cookie) if not c.user: c.user = UnloggedUser(get_browser_langs()) # patch for fixing mangled language preferences if (not isinstance(c.user.pref_lang, basestring) or not all(isinstance(x, basestring) for x in c.user.pref_content_langs)): c.user.pref_lang = g.lang c.user.pref_content_langs = [g.lang] c.user._commit() if c.user_is_loggedin: if not c.user._loaded: c.user._load() c.modhash = c.user.modhash() if hasattr(c.user, 'msgtime') and c.user.msgtime: c.have_messages = c.user.msgtime c.show_mod_mail = Subreddit.reverse_moderator_ids(c.user) c.have_mod_messages = getattr(c.user, "modmsgtime", False) c.user_is_admin = maybe_admin and c.user.name in g.admins c.user_is_admin = c.user.name in g.admins c.user_special_distinguish = c.user.special_distinguish() c.user_is_sponsor = c.user_is_admin or c.user.name in g.sponsors c.otp_cached = is_otpcookie_valid if not isinstance(c.site, FakeSubreddit) and not g.disallow_db_writes: c.user.update_sr_activity(c.site) c.over18 = over18() set_obey_over18() #set_browser_langs() set_host_lang() set_iface_lang() set_content_lang() set_recent_clicks() # used for HTML-lite templates set_colors() # set some environmental variables in case we hit an abort if not isinstance(c.site, FakeSubreddit): request.environ['REDDIT_NAME'] = c.site.name # random reddit trickery -- have to do this after the content lang is set if c.site == Random: c.site = Subreddit.random_reddit(user=c.user) redirect_to("/" + c.site.path.strip('/') + request.path) elif c.site == RandomSubscription: if c.user.gold: c.site = Subreddit.random_subscription(c.user) redirect_to('/' + c.site.path.strip('/') + request.path) else: redirect_to('/gold/about') elif c.site == RandomNSFW: c.site = Subreddit.random_reddit(over18=True, user=c.user) redirect_to("/" + c.site.path.strip('/') + request.path) if not request.path.startswith("/api/login/"): # is the subreddit banned? if c.site.spammy() and not c.user_is_admin and not c.error_page: ban_info = getattr(c.site, "ban_info", {}) if "message" in ban_info: message = ban_info['message'] else: sitelink = url_escape(add_sr("/")) subject = ("/r/%s has been incorrectly banned" % c.site.name) link = ("/r/redditrequest/submit?url=%s&title=%s" % (sitelink, subject)) message = strings.banned_subreddit_message % dict( link=link) errpage = pages.RedditError(strings.banned_subreddit_title, message, image="subreddit-banned.png") request.environ['usable_error_content'] = errpage.render() self.abort404() # check if the user has access to this subreddit if not c.site.can_view(c.user) and not c.error_page: public_description = c.site.public_description errpage = pages.RedditError(strings.private_subreddit_title, strings.private_subreddit_message, image="subreddit-private.png", sr_description=public_description) request.environ['usable_error_content'] = errpage.render() self.abort403() #check over 18 if (c.site.over_18 and not c.over18 and request.path not in ("/frame", "/over18") and c.render_style == 'html'): return self.intermediate_redirect("/over18") #check whether to allow custom styles c.allow_styles = True c.can_apply_styles = self.allow_stylesheets if g.css_killswitch: c.can_apply_styles = False #if the preference is set and we're not at a cname elif not c.user.pref_show_stylesheets and not c.cname: c.can_apply_styles = False #if the site has a cname, but we're not using it elif c.site.domain and c.site.css_on_cname and not c.cname: c.can_apply_styles = False c.show_admin_bar = admin_bar_eligible and (c.user_is_admin or g.debug) if not c.show_admin_bar: g.stats.end_logging_timings() hooks.get_hook("reddit.request.begin").call() c.request_timer.intermediate("base-pre")
def GET_listing(self, **env): if request.params.get("sort") == "rising": return self.redirect(add_sr("/rising")) return ListingController.GET_listing(self, **env)
def pre(self): c.response_wrappers = [] MinimalController.pre(self) set_cnameframe() # populate c.cookies unless we're on the unsafe media_domain if request.host != g.media_domain or g.media_domain == g.domain: try: for k,v in request.cookies.iteritems(): # minimalcontroller can still set cookies if k not in c.cookies: # we can unquote even if it's not quoted c.cookies[k] = Cookie(value=unquote(v), dirty=False) except CookieError: #pylons or one of the associated retarded libraries #can't handle broken cookies request.environ['HTTP_COOKIE'] = '' c.firsttime = firsttime() # the user could have been logged in via one of the feeds maybe_admin = False # no logins for RSS feed unless valid_feed has already been called if not c.user: if c.extension != "rss": session_cookie = c.cookies.get(g.login_cookie) if session_cookie: c.user = valid_cookie(session_cookie.value) if c.user: c.user_is_loggedin = True admin_cookie = c.cookies.get(g.admin_cookie) if c.user_is_loggedin and admin_cookie: maybe_admin, first_login = valid_admin_cookie(admin_cookie.value) if maybe_admin: self.enable_admin_mode(c.user, first_login=first_login) else: self.disable_admin_mode(c.user) if not c.user: c.user = UnloggedUser(get_browser_langs()) # patch for fixing mangled language preferences if (not isinstance(c.user.pref_lang, basestring) or not all(isinstance(x, basestring) for x in c.user.pref_content_langs)): c.user.pref_lang = g.lang c.user.pref_content_langs = [g.lang] c.user._commit() if c.user_is_loggedin: if not c.user._loaded: c.user._load() c.modhash = c.user.modhash() if request.method.upper() == 'GET': read_mod_cookie() if hasattr(c.user, 'msgtime') and c.user.msgtime: c.have_messages = c.user.msgtime c.show_mod_mail = Subreddit.reverse_moderator_ids(c.user) c.have_mod_messages = getattr(c.user, "modmsgtime", False) c.user_is_admin = maybe_admin and c.user.name in g.admins c.user_special_distinguish = c.user.special_distinguish() c.user_is_sponsor = c.user_is_admin or c.user.name in g.sponsors if request.path != '/validuser' and not g.disallow_db_writes: c.user.update_last_visit(c.start_time) c.over18 = over18() #set_browser_langs() set_host_lang() set_iface_lang() set_content_lang() set_recent_clicks() # used for HTML-lite templates set_colors() # set some environmental variables in case we hit an abort if not isinstance(c.site, FakeSubreddit): request.environ['REDDIT_NAME'] = c.site.name # random reddit trickery -- have to do this after the content lang is set if c.site == Random: c.site = Subreddit.random_reddit() redirect_to("/" + c.site.path.strip('/') + request.path) elif c.site == RandomNSFW: c.site = Subreddit.random_reddit(over18 = True) redirect_to("/" + c.site.path.strip('/') + request.path) if not request.path.startswith("/api/login/"): # is the subreddit banned? if c.site.spammy() and not c.user_is_admin and not c.error_page: ban_info = getattr(c.site, "ban_info", {}) if "message" in ban_info: message = ban_info['message'] else: sitelink = url_escape(add_sr("/")) subject = ("/r/%s has been incorrectly banned" % c.site.name) link = ("/r/redditrequest/submit?url=%s&title=%s" % (sitelink, subject)) message = strings.banned_subreddit_message % dict( link=link) errpage = pages.RedditError(strings.banned_subreddit_title, message, image="subreddit-banned.png") request.environ['usable_error_content'] = errpage.render() self.abort404() # check if the user has access to this subreddit if not c.site.can_view(c.user) and not c.error_page: errpage = pages.RedditError(strings.private_subreddit_title, strings.private_subreddit_message, image="subreddit-private.png") request.environ['usable_error_content'] = errpage.render() self.abort403() #check over 18 if (c.site.over_18 and not c.over18 and request.path not in ("/frame", "/over18") and c.render_style == 'html'): return self.intermediate_redirect("/over18") #check whether to allow custom styles c.allow_styles = True c.can_apply_styles = self.allow_stylesheets if g.css_killswitch: c.can_apply_styles = False #if the preference is set and we're not at a cname elif not c.user.pref_show_stylesheets and not c.cname: c.can_apply_styles = False #if the site has a cname, but we're not using it elif c.site.domain and c.site.css_on_cname and not c.cname: c.can_apply_styles = False
def add_ext_to_link(link): url = UrlParser(link.get("href")) if url.is_reddit_url(): link["href"] = add_sr(link.get("href"), sr_path=False)
def send_modmail_email(message): if not message.sr_id: return sr = Subreddit._byID(message.sr_id, data=True) forwarding_email = g.live_config['modmail_forwarding_email'].get(sr.name) if not forwarding_email: return sender = Account._byID(message.author_id, data=True) if sender.name in g.admins: distinguish = "[A]" elif sr.is_moderator(sender): distinguish = "[M]" else: distinguish = None if distinguish: from_address = "u/{username} {distinguish} <{sender_email}>".format( username=sender.name, distinguish=distinguish, sender_email=g.modmail_sender_email) else: from_address = "u/{username} <{sender_email}>".format( username=sender.name, sender_email=g.modmail_sender_email) reply_to = get_reply_to_address(message) parent_email_id, other_email_ids = get_email_ids(message) subject = get_message_subject(message) if message.from_sr and not message.first_message: # this is a message from the subreddit to a user. add some text that # shows the recipient recipient = Account._byID(message.to_id, data=True) sender_text = ("This message was sent from r/{subreddit} to " "u/{user}").format(subreddit=sr.name, user=recipient.name) else: userlink = add_sr("/u/{name}".format(name=sender.name), sr_path=False) sender_text = "This message was sent by {userlink}".format( userlink=userlink, ) reply_footer = ("\n\n-\n{sender_text}\n\n" "Reply to this email directly or view it on reddit: {link}") reply_footer = reply_footer.format( sender_text=sender_text, link=message.make_permalink(force_domain=True), ) message_text = message.body + reply_footer email_id = g.email_provider.send_email( to_address=forwarding_email, from_address=from_address, subject=subject, text=message_text, reply_to=reply_to, parent_email_id=parent_email_id, other_email_ids=other_email_ids, ) if email_id: g.log.info("sent %s as %s", message._id36, email_id) message.email_id = email_id message._commit() g.stats.simple_event("modmail_email.outgoing_email")
def pre(self): c.response_wrappers = [] MinimalController.pre(self) set_cnameframe() # populate c.cookies unless we're on the unsafe media_domain if request.host != g.media_domain or g.media_domain == g.domain: try: for k, v in request.cookies.iteritems(): # minimalcontroller can still set cookies if k not in c.cookies: # we can unquote even if it's not quoted c.cookies[k] = Cookie(value=unquote(v), dirty=False) except CookieError: #pylons or one of the associated retarded libraries #can't handle broken cookies request.environ['HTTP_COOKIE'] = '' c.firsttime = firsttime() # the user could have been logged in via one of the feeds maybe_admin = False # no logins for RSS feed unless valid_feed has already been called if not c.user: if c.extension != "rss": session_cookie = c.cookies.get(g.login_cookie) if session_cookie: c.user = valid_cookie(session_cookie.value) if c.user: c.user_is_loggedin = True admin_cookie = c.cookies.get(g.admin_cookie) if c.user_is_loggedin and admin_cookie: maybe_admin, first_login = valid_admin_cookie( admin_cookie.value) if maybe_admin: self.enable_admin_mode(c.user, first_login=first_login) else: self.disable_admin_mode(c.user) if not c.user: c.user = UnloggedUser(get_browser_langs()) # patch for fixing mangled language preferences if (not isinstance(c.user.pref_lang, basestring) or not all( isinstance(x, basestring) for x in c.user.pref_content_langs)): c.user.pref_lang = g.lang c.user.pref_content_langs = [g.lang] c.user._commit() if c.user_is_loggedin: if not c.user._loaded: c.user._load() c.modhash = c.user.modhash() if request.method.upper() == 'GET': read_mod_cookie() if hasattr(c.user, 'msgtime') and c.user.msgtime: c.have_messages = c.user.msgtime c.show_mod_mail = Subreddit.reverse_moderator_ids(c.user) c.have_mod_messages = getattr(c.user, "modmsgtime", False) c.user_is_admin = maybe_admin and c.user.name in g.admins c.user_special_distinguish = c.user.special_distinguish() c.user_is_sponsor = c.user_is_admin or c.user.name in g.sponsors if request.path != '/validuser' and not g.disallow_db_writes: c.user.update_last_visit(c.start_time) c.over18 = over18() #set_browser_langs() set_host_lang() set_iface_lang() set_content_lang() set_recent_clicks() # used for HTML-lite templates set_colors() # set some environmental variables in case we hit an abort if not isinstance(c.site, FakeSubreddit): request.environ['REDDIT_NAME'] = c.site.name # random reddit trickery -- have to do this after the content lang is set if c.site == Random: c.site = Subreddit.random_reddit() redirect_to("/" + c.site.path.strip('/') + request.path) elif c.site == RandomNSFW: c.site = Subreddit.random_reddit(over18=True) redirect_to("/" + c.site.path.strip('/') + request.path) if not request.path.startswith("/api/login/"): # is the subreddit banned? if c.site.spammy() and not c.user_is_admin and not c.error_page: ban_info = getattr(c.site, "ban_info", {}) if "message" in ban_info: message = ban_info['message'] else: sitelink = url_escape(add_sr("/")) subject = ("/r/%s has been incorrectly banned" % c.site.name) link = ("/r/redditrequest/submit?url=%s&title=%s" % (sitelink, subject)) message = strings.banned_subreddit_message % dict( link=link) errpage = pages.RedditError(strings.banned_subreddit_title, message, image="subreddit-banned.png") request.environ['usable_error_content'] = errpage.render() self.abort404() # check if the user has access to this subreddit if not c.site.can_view(c.user) and not c.error_page: errpage = pages.RedditError(strings.private_subreddit_title, strings.private_subreddit_message, image="subreddit-private.png") request.environ['usable_error_content'] = errpage.render() self.abort403() #check over 18 if (c.site.over_18 and not c.over18 and request.path not in ("/frame", "/over18") and c.render_style == 'html'): return self.intermediate_redirect("/over18") #check whether to allow custom styles c.allow_styles = True c.can_apply_styles = self.allow_stylesheets if g.css_killswitch: c.can_apply_styles = False #if the preference is set and we're not at a cname elif not c.user.pref_show_stylesheets and not c.cname: c.can_apply_styles = False #if the site has a cname, but we're not using it elif c.site.domain and c.site.css_on_cname and not c.cname: c.can_apply_styles = False
def make_event_url(event_id): return add_sr("/live/%s/" % event_id, sr_path=False, force_hostname=True)
def send_modmail_email(message): if not message.sr_id: return sr = Subreddit._byID(message.sr_id, data=True) forwarding_email = g.live_config['modmail_forwarding_email'].get(sr.name) if not forwarding_email: return sender = Account._byID(message.author_id, data=True) if sender.name in g.admins: distinguish = "[A]" elif sr.is_moderator(sender): distinguish = "[M]" else: distinguish = None if distinguish: from_address = "u/{username} {distinguish} <{sender_email}>".format( username=sender.name, distinguish=distinguish, sender_email=g.modmail_sender_email) else: from_address = "u/{username} <{sender_email}>".format( username=sender.name, sender_email=g.modmail_sender_email) reply_to = get_reply_to_address(message) parent_email_id, other_email_ids = get_email_ids(message) subject = get_message_subject(message) if message.from_sr and not message.first_message: # this is a message from the subreddit to a user. add some text that # shows the recipient recipient = Account._byID(message.to_id, data=True) sender_text = ("This message was sent from {brander_community_abbr}/{subreddit} to " "u/{user}").format(subreddit=sr.name, user=recipient.name, brander_community_abbr=g.brander_community_abbr) else: userlink = add_sr("/u/{name}".format(name=sender.name), sr_path=False) sender_text = "This message was sent by {userlink}".format( userlink=userlink, ) reply_footer = ("\n\n-\n{sender_text}\n\n" "Reply to this email directly or view it on reddit: {link}") reply_footer = reply_footer.format( sender_text=sender_text, link=message.make_permalink(force_domain=True), ) message_text = message.body + reply_footer email_id = g.email_provider.send_email( to_address=forwarding_email, from_address=from_address, subject=subject, text=message_text, reply_to=reply_to, parent_email_id=parent_email_id, other_email_ids=other_email_ids, ) if email_id: g.log.info("sent %s as %s", message._id36, email_id) message.email_id = email_id message._commit() g.stats.simple_event("modmail_email.outgoing_email")
def pre(self): record_timings = g.admin_cookie in request.cookies or g.debug admin_bar_eligible = response.content_type == 'text/html' if admin_bar_eligible and record_timings: g.stats.start_logging_timings() # set up stuff needed in base templates at error time here. c.js_preload = JSPreload() MinimalController.pre(self) set_cnameframe() # populate c.cookies unless we're on the unsafe media_domain if request.host != g.media_domain or g.media_domain == g.domain: cookie_counts = collections.Counter() try: for k, v in request.cookies.iteritems(): # minimalcontroller can still set cookies if k not in c.cookies: # we can unquote even if it's not quoted c.cookies[k] = Cookie(value=unquote(v), dirty=False) cookie_counts[Cookie.classify(k)] += 1 except CookieError: #pylons or one of the associated retarded libraries #can't handle broken cookies request.environ['HTTP_COOKIE'] = '' for cookietype, count in cookie_counts.iteritems(): g.stats.simple_event("cookie.%s" % cookietype, count) delete_obsolete_cookies() # the user could have been logged in via one of the feeds maybe_admin = False is_otpcookie_valid = False # no logins for RSS feed unless valid_feed has already been called if not c.user: if c.extension != "rss": authenticate_user() admin_cookie = c.cookies.get(g.admin_cookie) if c.user_is_loggedin and admin_cookie: maybe_admin, first_login = valid_admin_cookie( admin_cookie.value) if maybe_admin: self.enable_admin_mode(c.user, first_login=first_login) else: self.disable_admin_mode(c.user) otp_cookie = read_user_cookie(g.otp_cookie) if c.user_is_loggedin and otp_cookie: is_otpcookie_valid = valid_otp_cookie(otp_cookie) if not c.user: c.user = UnloggedUser(get_browser_langs()) # patch for fixing mangled language preferences if (not isinstance(c.user.pref_lang, basestring) or not all( isinstance(x, basestring) for x in c.user.pref_content_langs)): c.user.pref_lang = g.lang c.user.pref_content_langs = [g.lang] c.user._commit() if c.user_is_loggedin: if not c.user._loaded: c.user._load() c.modhash = c.user.modhash() if hasattr(c.user, 'msgtime') and c.user.msgtime: c.have_messages = c.user.msgtime c.show_mod_mail = Subreddit.reverse_moderator_ids(c.user) c.have_mod_messages = getattr(c.user, "modmsgtime", False) c.user_is_admin = maybe_admin and c.user.name in g.admins c.user_special_distinguish = c.user.special_distinguish() c.user_is_sponsor = c.user_is_admin or c.user.name in g.sponsors c.otp_cached = is_otpcookie_valid if not isinstance(c.site, FakeSubreddit) and not g.disallow_db_writes: c.user.update_sr_activity(c.site) c.over18 = over18() set_obey_over18() # looking up the multireddit requires c.user. set_multireddit() #set_browser_langs() set_host_lang() set_iface_lang() set_content_lang() set_recent_clicks() # used for HTML-lite templates set_colors() # set some environmental variables in case we hit an abort if not isinstance(c.site, FakeSubreddit): request.environ['REDDIT_NAME'] = c.site.name # random reddit trickery -- have to do this after the content lang is set if c.site == Random: c.site = Subreddit.random_reddit(user=c.user) redirect_to("/" + c.site.path.strip('/') + request.path_qs) elif c.site == RandomSubscription: if c.user.gold: c.site = Subreddit.random_subscription(c.user) redirect_to('/' + c.site.path.strip('/') + request.path_qs) else: redirect_to('/gold/about') elif c.site == RandomNSFW: c.site = Subreddit.random_reddit(over18=True, user=c.user) redirect_to("/" + c.site.path.strip('/') + request.path_qs) if not request.path.startswith("/api/login/"): # is the subreddit banned? if c.site.spammy() and not c.user_is_admin and not c.error_page: ban_info = getattr(c.site, "ban_info", {}) if "message" in ban_info: message = ban_info['message'] else: sitelink = url_escape(add_sr("/")) subject = ("/r/%s has been incorrectly banned" % c.site.name) link = ("/r/redditrequest/submit?url=%s&title=%s" % (sitelink, subject)) message = strings.banned_subreddit_message % dict( link=link) errpage = pages.RedditError(strings.banned_subreddit_title, message, image="subreddit-banned.png") request.environ['usable_error_content'] = errpage.render() self.abort404() # check if the user has access to this subreddit if not c.site.can_view(c.user) and not c.error_page: if isinstance(c.site, LabeledMulti): # do not leak the existence of multis via 403. self.abort404() else: public_description = c.site.public_description errpage = pages.RedditError( strings.private_subreddit_title, strings.private_subreddit_message, image="subreddit-private.png", sr_description=public_description, ) request.environ['usable_error_content'] = errpage.render() self.abort403() #check over 18 if (c.site.over_18 and not c.over18 and request.path not in ("/frame", "/over18") and c.render_style == 'html'): return self.intermediate_redirect("/over18") #check whether to allow custom styles c.allow_styles = True c.can_apply_styles = self.allow_stylesheets if g.css_killswitch: c.can_apply_styles = False #if the preference is set and we're not at a cname elif not c.user.pref_show_stylesheets and not c.cname: c.can_apply_styles = False #if the site has a cname, but we're not using it elif c.site.domain and c.site.css_on_cname and not c.cname: c.can_apply_styles = False c.bare_content = request.GET.pop('bare', False) c.show_admin_bar = admin_bar_eligible and (c.user_is_admin or g.debug) if not c.show_admin_bar: g.stats.end_logging_timings() hooks.get_hook("reddit.request.begin").call() c.request_timer.intermediate("base-pre")