Skip to content

Commit dd46d36

Browse files
committed
Add utm query parameters onto links for comments/messages
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.
1 parent b900d9b commit dd46d36

9 files changed

+88
-7
lines changed

r2/example.ini

+1
Original file line numberDiff line numberDiff line change
@@ -963,3 +963,4 @@ feature_mobile_native_targeting = {"employee": true}
963963
feature_pause_ads = on
964964
feature_ads_auction = {"employee": true}
965965
feature_cpc_pricing = off
966+
feature_utm_comment_links = off

r2/r2/lib/pages/pages.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -1991,7 +1991,7 @@ def cache_key(self):
19911991
elif num > 100:
19921992
num = (num / 10) * 10
19931993

1994-
_id = make_key_id(
1994+
cache_key_args = [
19951995
self.article._fullname,
19961996
self.article.contest_mode,
19971997
self.article.locked,
@@ -2007,7 +2007,12 @@ def cache_key(self):
20072007
c.can_embed,
20082008
self.max_depth,
20092009
self.edits_visible,
2010-
)
2010+
]
2011+
2012+
if feature.is_enabled("utm_comment_links"):
2013+
cache_key_args.append("utm_comment_links")
2014+
2015+
_id = make_key_id(*cache_key_args)
20112016
key = "pane:%s" % _id
20122017
return key
20132018

r2/r2/models/link.py

+63
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@
2828
Thing, Relation, NotFound, MultiRelation, CreationError)
2929
from r2.lib.db.operators import desc
3030
from r2.lib.errors import RedditError
31+
from r2.lib.tracking import (
32+
get_site,
33+
)
3134
from r2.lib.utils import (
3235
base_url,
3336
domain,
@@ -471,6 +474,62 @@ def markdown_link_slow(self):
471474
title = title.replace("]", r"\]")
472475
return "[%s](%s)" % (title, self.make_permalink_slow())
473476

477+
@classmethod
478+
def tracking_link(cls,
479+
link,
480+
wrapped_thing=None,
481+
element_name=None,
482+
context=None,
483+
site_name=None):
484+
"""Add utm query parameters to reddit.com links to track navigation.
485+
486+
context => ?utm_medium (listing page, post listing on hybrid page)
487+
site_name => ?utm_name (subreddit that user is currently browsing)
488+
element_name => ?utm_content (what element leads to this link)
489+
"""
490+
491+
if (c.user_is_admin or
492+
not feature.is_enabled('utm_comment_links')):
493+
return link
494+
495+
urlparser = UrlParser(link)
496+
if not urlparser.path:
497+
# `href="#some_anchor"`
498+
return link
499+
if urlparser.scheme == 'javascript':
500+
return link
501+
if not urlparser.is_reddit_url():
502+
return link
503+
504+
query_params = {}
505+
506+
query_params["utm_source"] = "reddit"
507+
508+
if context is None:
509+
if (hasattr(wrapped_thing, 'context') and
510+
wrapped_thing.context != cls.get_default_context()):
511+
context = wrapped_thing.context
512+
else:
513+
context = request.route_dict["controller"]
514+
if context:
515+
query_params["utm_medium"] = context
516+
517+
if element_name:
518+
query_params["utm_content"] = element_name
519+
520+
if site_name is None:
521+
site_name = get_site()
522+
if site_name:
523+
query_params["utm_name"] = site_name
524+
525+
query_params = {k: v for (k, v) in query_params.iteritems() if (
526+
v is not None)}
527+
528+
if query_params:
529+
urlparser.update_query(**query_params)
530+
return urlparser.unparse()
531+
return link
532+
474533
def _gild(self, user):
475534
now = datetime.now(g.tz)
476535

@@ -885,6 +944,10 @@ def add_props(cls, user, wrapped):
885944
# Run this last
886945
Printable.add_props(user, wrapped)
887946

947+
@classmethod
948+
def get_default_context(cls):
949+
return request.route_dict["action_name"]
950+
888951
@property
889952
def post_hint(self):
890953
"""Returns a string that suggests the content of this link.

r2/r2/models/subreddit.py

+1
Original file line numberDiff line numberDiff line change
@@ -1777,6 +1777,7 @@ def __init__(self):
17771777

17781778

17791779
class _DefaultSR(FakeSubreddit):
1780+
analytics_name = 'frontpage'
17801781
#notice the space before reddit.com
17811782
name = ' reddit.com'
17821783
path = '/'

r2/r2/templates/comment.html

+4-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,10 @@
4444
</%def>
4545

4646
<%def name="link()" buffered="True">
47-
<a href="${thing.link.url}" class="title"
47+
<%
48+
url = thing.link.tracking_link(thing.link.url, thing, "title", site_name=False)
49+
%>
50+
<a href="${url}" class="title"
4851
%if thing.nofollow:
4952
rel="nofollow"
5053
%endif

r2/r2/templates/link.html

+2-1
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,11 @@
4949
<%def name="make_link(name, css_class, tabindex=0)">
5050
<%
5151
media_override = thing.link_child and getattr(thing, 'media_override', False)
52+
url = thing.tracking_link(thing.href_url, thing, name)
5253
%>
5354
<a class="${css_class} may-blank ${ c.user_is_loggedin and 'loggedin' or ''}
5455
${ media_override and 'open-expando' or '' }"
55-
href="${thing.href_url}"
56+
href="${url}"
5657
%if tabindex:
5758
tabindex="${tabindex}"
5859
%endif

r2/r2/templates/morerecursion.html

+4-1
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,13 @@
2121
###############################################################################
2222

2323
<%inherit file="comment_skeleton.html"/>
24+
<%!
25+
from r2.models import Link
26+
%>
2427

2528

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

3033
<%def name="midcol(cls='')">

r2/r2/templates/printablebuttons.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -763,7 +763,7 @@
763763
<% data_attrs = {"event-action": event_action} if event_action else None %>
764764
${plain_link(
765765
title,
766-
link,
766+
Link.tracking_link(link, thing, element_name=event_action),
767767
_class=a_class,
768768
rel="nofollow",
769769
_sr_path=sr_path,

r2/r2/templates/trendingsubredditsbar.html

+5-1
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,18 @@
2020
## reddit Inc. All Rights Reserved.
2121
###############################################################################
2222

23+
<%!
24+
from r2.models import Link
25+
%>
26+
2327
<div class="trending-subreddits">
2428
<div class="rank-spacer"></div>
2529
<div class="midcol-spacer"></div>
2630
<div class="trending-subreddits-content">
2731
<strong>${_('trending subreddits')}</strong>
2832
<ul>
2933
%for i, subreddit_name in enumerate(thing.subreddit_names):
30-
<li><a href="/r/${subreddit_name}?ref=trending_sr_${i+1}" target="_blank">/r/${subreddit_name}</a></li>
34+
<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>
3135
%endfor
3236
</ul>
3337
<a href="${thing.comment_url}" class="${thing.comment_label_cls}">${thing.comment_label}</a>

0 commit comments

Comments
 (0)