Skip to content

Commit

Permalink
Add utm query parameters onto links for comments/messages
Browse files Browse the repository at this point in the history
Link.tracking_link adds utm query parameters onto links inside reddit
to track which button was clicked, what component type contains the button
(e.g. post listing, inbox, post listing embedded on a comments page),
what page type the user is visiting, and the page's subreddit.

This feature is enabled via feature flag and disabled by admin mode.

This commit affects programmatically-generated links to comments and messages.
  • Loading branch information
jewel-andraia committed Dec 2, 2016
1 parent b900d9b commit dd46d36
Show file tree
Hide file tree
Showing 9 changed files with 88 additions and 7 deletions.
1 change: 1 addition & 0 deletions r2/example.ini
Original file line number Diff line number Diff line change
Expand Up @@ -963,3 +963,4 @@ feature_mobile_native_targeting = {"employee": true}
feature_pause_ads = on
feature_ads_auction = {"employee": true}
feature_cpc_pricing = off
feature_utm_comment_links = off
9 changes: 7 additions & 2 deletions r2/r2/lib/pages/pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -1991,7 +1991,7 @@ def cache_key(self):
elif num > 100:
num = (num / 10) * 10

_id = make_key_id(
cache_key_args = [
self.article._fullname,
self.article.contest_mode,
self.article.locked,
Expand All @@ -2007,7 +2007,12 @@ def cache_key(self):
c.can_embed,
self.max_depth,
self.edits_visible,
)
]

if feature.is_enabled("utm_comment_links"):
cache_key_args.append("utm_comment_links")

_id = make_key_id(*cache_key_args)
key = "pane:%s" % _id
return key

Expand Down
63 changes: 63 additions & 0 deletions r2/r2/models/link.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@
Thing, Relation, NotFound, MultiRelation, CreationError)
from r2.lib.db.operators import desc
from r2.lib.errors import RedditError
from r2.lib.tracking import (
get_site,
)
from r2.lib.utils import (
base_url,
domain,
Expand Down Expand Up @@ -471,6 +474,62 @@ def markdown_link_slow(self):
title = title.replace("]", r"\]")
return "[%s](%s)" % (title, self.make_permalink_slow())

@classmethod
def tracking_link(cls,
link,
wrapped_thing=None,
element_name=None,
context=None,
site_name=None):
"""Add utm query parameters to reddit.com links to track navigation.
context => ?utm_medium (listing page, post listing on hybrid page)
site_name => ?utm_name (subreddit that user is currently browsing)
element_name => ?utm_content (what element leads to this link)
"""

if (c.user_is_admin or
not feature.is_enabled('utm_comment_links')):
return link

urlparser = UrlParser(link)
if not urlparser.path:
# `href="#some_anchor"`
return link
if urlparser.scheme == 'javascript':
return link
if not urlparser.is_reddit_url():
return link

query_params = {}

query_params["utm_source"] = "reddit"

if context is None:
if (hasattr(wrapped_thing, 'context') and
wrapped_thing.context != cls.get_default_context()):
context = wrapped_thing.context
else:
context = request.route_dict["controller"]
if context:
query_params["utm_medium"] = context

if element_name:
query_params["utm_content"] = element_name

if site_name is None:
site_name = get_site()
if site_name:
query_params["utm_name"] = site_name

query_params = {k: v for (k, v) in query_params.iteritems() if (
v is not None)}

if query_params:
urlparser.update_query(**query_params)
return urlparser.unparse()
return link

def _gild(self, user):
now = datetime.now(g.tz)

Expand Down Expand Up @@ -885,6 +944,10 @@ def add_props(cls, user, wrapped):
# Run this last
Printable.add_props(user, wrapped)

@classmethod
def get_default_context(cls):
return request.route_dict["action_name"]

@property
def post_hint(self):
"""Returns a string that suggests the content of this link.
Expand Down
1 change: 1 addition & 0 deletions r2/r2/models/subreddit.py
Original file line number Diff line number Diff line change
Expand Up @@ -1777,6 +1777,7 @@ def __init__(self):


class _DefaultSR(FakeSubreddit):
analytics_name = 'frontpage'
#notice the space before reddit.com
name = ' reddit.com'
path = '/'
Expand Down
5 changes: 4 additions & 1 deletion r2/r2/templates/comment.html
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,10 @@
</%def>

<%def name="link()" buffered="True">
<a href="${thing.link.url}" class="title"
<%
url = thing.link.tracking_link(thing.link.url, thing, "title", site_name=False)
%>
<a href="${url}" class="title"
%if thing.nofollow:
rel="nofollow"
%endif
Expand Down
3 changes: 2 additions & 1 deletion r2/r2/templates/link.html
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,11 @@
<%def name="make_link(name, css_class, tabindex=0)">
<%
media_override = thing.link_child and getattr(thing, 'media_override', False)
url = thing.tracking_link(thing.href_url, thing, name)
%>
<a class="${css_class} may-blank ${ c.user_is_loggedin and 'loggedin' or ''}
${ media_override and 'open-expando' or '' }"
href="${thing.href_url}"
href="${url}"
%if tabindex:
tabindex="${tabindex}"
%endif
Expand Down
5 changes: 4 additions & 1 deletion r2/r2/templates/morerecursion.html
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,13 @@
###############################################################################

<%inherit file="comment_skeleton.html"/>
<%!
from r2.models import Link
%>


<%def name="commentBody()">
<span class="deepthread"><a href="${thing.parent_permalink}">${_("continue this thread")}</a></span>
<span class="deepthread"><a href="${Link.tracking_link(thing.parent_permalink, thing, context='continue_thread')}">${_("continue this thread")}</a></span>
</%def>

<%def name="midcol(cls='')">
Expand Down
2 changes: 1 addition & 1 deletion r2/r2/templates/printablebuttons.html
Original file line number Diff line number Diff line change
Expand Up @@ -763,7 +763,7 @@
<% data_attrs = {"event-action": event_action} if event_action else None %>
${plain_link(
title,
link,
Link.tracking_link(link, thing, element_name=event_action),
_class=a_class,
rel="nofollow",
_sr_path=sr_path,
Expand Down
6 changes: 5 additions & 1 deletion r2/r2/templates/trendingsubredditsbar.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,18 @@
## reddit Inc. All Rights Reserved.
###############################################################################

<%!
from r2.models import Link
%>

<div class="trending-subreddits">
<div class="rank-spacer"></div>
<div class="midcol-spacer"></div>
<div class="trending-subreddits-content">
<strong>${_('trending subreddits')}</strong>
<ul>
%for i, subreddit_name in enumerate(thing.subreddit_names):
<li><a href="/r/${subreddit_name}?ref=trending_sr_${i+1}" target="_blank">/r/${subreddit_name}</a></li>
<li><a href="${Link.tracking_link('/r/%s'%subreddit_name, context='trending_subreddits_bar', element_name='trending_sr_%s'%(i+1))}" target="_blank">/r/${subreddit_name}</a></li>
%endfor
</ul>
<a href="${thing.comment_url}" class="${thing.comment_label_cls}">${thing.comment_label}</a>
Expand Down

0 comments on commit dd46d36

Please sign in to comment.