This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
/
front.py
1812 lines (1558 loc) · 70.6 KB
/
front.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# The contents of this file are subject to the Common Public Attribution
# License Version 1.0. (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://code.reddit.com/LICENSE. The License is based on the Mozilla Public
# License Version 1.1, but Sections 14 and 15 have been added to cover use of
# software over a computer network and provide for limited attribution for the
# Original Developer. In addition, Exhibit A has been modified to be consistent
# with Exhibit B.
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
# the specific language governing rights and limitations under the License.
#
# The Original Code is reddit.
#
# The Original Developer is the Initial Developer. The Initial Developer of
# the Original Code is reddit Inc.
#
# All portions of the code written by reddit are Copyright (c) 2006-2015 reddit
# Inc. All Rights Reserved.
###############################################################################
from pylons.i18n import _, ungettext
from r2.controllers.reddit_base import (
base_listing,
disable_subreddit_css,
hsts_modify_redirect,
hsts_eligible,
pagecache_policy,
PAGECACHE_POLICY,
paginated_listing,
RedditController,
require_https,
)
from r2 import config
from r2.models import *
from r2.models.recommend import ExploreSettings
from r2.config import feature
from r2.config.extensions import is_api, API_TYPES, RSS_TYPES
from r2.lib import hooks, recommender, embeds, pages
from r2.lib.pages import *
from r2.lib.pages.things import hot_links_by_url_listing
from r2.lib.pages import trafficpages
from r2.lib.menus import *
from r2.lib.admin_utils import check_cheating
from r2.lib.csrf import csrf_exempt
from r2.lib.utils import to36, sanitize_url, title_to_url
from r2.lib.utils import query_string, UrlParser, url_links_builder
from r2.lib.template_helpers import get_domain
from r2.lib.filters import unsafe, _force_unicode, _force_utf8
from r2.lib.emailer import Email, generate_notification_email_unsubscribe_token
from r2.lib.db.operators import desc
from r2.lib.db import queries
from r2.lib.db.tdb_cassandra import MultiColumnQuery
from r2.lib.strings import strings
from r2.lib.search import (SearchQuery, SubredditSearchQuery, SearchException,
InvalidQuery)
from r2.lib.validator import *
from r2.lib import jsontemplates
from r2.lib import sup
import r2.lib.db.thing as thing
from r2.lib.errors import errors, ForbiddenError
from listingcontroller import ListingController
from oauth2 import require_oauth2_scope
from api_docs import api_doc, api_section
from pylons import c, request
from r2.models.token import EmailVerificationToken
from r2.controllers.ipn import generate_blob, validate_blob, GoldException
from operator import attrgetter
import string
import random as rand
import re, socket
import time as time_module
from urllib import quote_plus
class FrontController(RedditController):
allow_stylesheets = True
@validate(article=VLink('article'),
comment=VCommentID('comment'))
def GET_oldinfo(self, article, type, dest, rest=None, comment=''):
"""Legacy: supporting permalink pages from '06,
and non-search-engine-friendly links"""
if not (dest in ('comments','related','details')):
dest = 'comments'
if type == 'ancient':
#this could go in config, but it should never change
max_link_id = 10000000
new_id = max_link_id - int(article._id)
return self.redirect('/info/' + to36(new_id) + '/' + rest)
if type == 'old':
if not article.subreddit_slow.can_view(c.user):
self.abort403()
new_url = "/%s/%s/%s" % \
(dest, article._id36,
quote_plus(title_to_url(article.title).encode('utf-8')))
if not c.default_sr:
new_url = "/r/%s%s" % (c.site.name, new_url)
if comment:
new_url = new_url + "/%s" % comment._id36
if c.extension:
new_url = new_url + "/.%s" % c.extension
new_url = new_url + query_string(request.GET)
# redirect should be smarter and handle extensions, etc.
return self.redirect(new_url, code=301)
@require_oauth2_scope("read")
@api_doc(api_section.listings, uses_site=True)
def GET_random(self):
"""The Serendipity button"""
sort = rand.choice(('new','hot'))
q = c.site.get_links(sort, 'all')
if isinstance(q, thing.Query):
q._limit = g.num_serendipity
names = [link._fullname for link in q]
else:
names = list(q)[:g.num_serendipity]
rand.shuffle(names)
def keep_fn(item):
return item.fresh and item.keep_item(item)
builder = IDBuilder(names, skip=True, keep_fn=keep_fn, num=1)
links, first, last, before, after = builder.get_items()
if links:
return self.redirect(add_sr("/tb/" + links[0]._id36))
else:
return self.redirect(add_sr('/'))
@disable_subreddit_css()
@validate(
VAdmin(),
thing=VByName('article'),
oldid36=nop('article'),
after=nop('after'),
before=nop('before'),
count=VCount('count'),
listing_only=VBoolean('listing_only'),
)
def GET_details(self, thing, oldid36, after, before, count, listing_only):
"""The (now deprecated) details page. Content on this page
has been subsubmed by the presence of the LinkInfoBar on the
rightbox, so it is only useful for Admin-only wizardry."""
if not thing:
try:
link = Link._byID36(oldid36)
return self.redirect('/details/' + link._fullname)
except (NotFound, ValueError):
abort(404)
kw = {
'count': count,
'listing_only': listing_only,
}
if before:
kw['after'] = before
kw['reverse'] = True
else:
kw['after'] = after
kw['reverse'] = False
c.referrer_policy = "always"
page = DetailsPage(thing=thing, expand_children=False, **kw)
if listing_only:
return page.details.listing.listing().render()
return page.render()
@validate(VUser())
def GET_explore(self):
settings = ExploreSettings.for_user(c.user)
recs = recommender.get_recommended_content_for_user(c.user,
settings,
record_views=True)
content = ExploreItemListing(recs, settings)
return BoringPage(_("explore"),
show_sidebar=True,
show_chooser=True,
page_classes=['explore-page'],
content=content).render()
@validate(article=VLink('article'))
def GET_shirt(self, article):
if not can_view_link_comments(article):
abort(403, 'forbidden')
return self.abort404()
@require_oauth2_scope("read")
@validate(article=VLink('article',
docs={"article": "ID36 of a link"}),
comment=VCommentID('comment',
docs={"comment": "(optional) ID36 of a comment"}),
context=VInt('context', min=0, max=8),
sort=VTransitionaryMenu('controller'),
limit=VInt('limit',
docs={"limit": "(optional) an integer"}),
depth=VInt('depth',
docs={"depth": "(optional) an integer"}),
showedits=VBoolean("showedits", default=True),
showmore=VBoolean("showmore", default=True),
)
@api_doc(api_section.listings,
uri='/comments/{article}',
uses_site=True,
supports_rss=True)
def GET_comments(
self, article, comment, context, sort, limit, depth,
showedits=True, showmore=True):
"""Get the comment tree for a given Link `article`.
If supplied, `comment` is the ID36 of a comment in the comment tree for
`article`. This comment will be the (highlighted) focal point of the
returned view and `context` will be the number of parents shown.
`depth` is the maximum depth of subtrees in the thread.
`limit` is the maximum number of comments to return.
See also: [/api/morechildren](#GET_api_morechildren) and
[/api/comment](#POST_api_comment).
"""
if not sort:
sort = c.user.pref_default_comment_sort
if comment and comment.link_id != article._id:
return self.abort404()
sr = Subreddit._byID(article.sr_id, True)
if sr.name == g.takedown_sr:
request.environ['REDDIT_TAKEDOWN'] = article._fullname
return self.abort404()
if not c.default_sr and c.site._id != sr._id:
return self.abort404()
if not can_view_link_comments(article):
abort(403, 'forbidden')
# check over 18
if article.is_nsfw and not c.over18 and c.render_style == 'html':
return self.intermediate_redirect("/over18", sr_path=False)
# Determine if we should show the embed link for comments
c.can_embed = feature.is_enabled("comment_embeds") and bool(comment)
is_embed = embeds.prepare_embed_request(sr)
# check for 304
self.check_modified(article, 'comments')
if is_embed:
embeds.set_up_embed(sr, comment, showedits=showedits)
# Temporary hook until IAMA app "OP filter" is moved from partners
# Not to be open-sourced
page = hooks.get_hook("comments_page.override").call_until_return(
controller=self,
article=article,
limit=limit,
)
if page:
return page
# If there is a focal comment, communicate down to
# comment_skeleton.html who that will be. Also, skip
# comment_visits check
previous_visits = None
if comment:
c.focal_comment = comment._id36
elif (c.user_is_loggedin and
(c.user.gold or sr.is_moderator(c.user)) and
c.user.pref_highlight_new_comments):
timer = g.stats.get_timer("gold.comment_visits")
timer.start()
previous_visits = CommentVisitsByUser.get_and_update(
c.user, article, c.start_time)
timer.stop()
# check if we just came from the submit page
infotext = None
if request.GET.get('already_submitted'):
submit_url = request.GET.get('submit_url') or article.url
resubmit_url = Link.resubmit_link(submit_url)
sr_resubmit_url = add_sr(resubmit_url)
infotext = strings.already_submitted % sr_resubmit_url
check_cheating('comments')
if not c.user.pref_num_comments:
num = g.num_comments
elif c.user_is_loggedin and (c.user.gold or sr.is_moderator(c.user)):
num = min(c.user.pref_num_comments, g.max_comments_gold)
else:
num = min(c.user.pref_num_comments, g.max_comments)
kw = {}
# allow depth to be reset (I suspect I'll turn the VInt into a
# validator on my next pass of .compact)
if depth is not None and 0 < depth < MAX_RECURSION:
kw['max_depth'] = depth
elif c.render_style == "compact":
kw['max_depth'] = 5
kw["edits_visible"] = showedits
kw["load_more"] = kw["continue_this_thread"] = showmore
kw["show_deleted"] = embeds.is_embed()
displayPane = PaneStack()
# allow the user's total count preferences to be overwritten
# (think of .embed as the use case together with depth=1)
if limit and limit > 0:
num = limit
if c.user_is_loggedin and (c.user.gold or sr.is_moderator(c.user)):
if num > g.max_comments_gold:
displayPane.append(InfoBar(message =
strings.over_comment_limit_gold
% max(0, g.max_comments_gold)))
num = g.max_comments_gold
elif num > g.max_comments:
if limit:
displayPane.append(InfoBar(message =
strings.over_comment_limit
% dict(max=max(0, g.max_comments),
goldmax=max(0,
g.max_comments_gold))))
num = g.max_comments
# if permalink page, add that message first to the content
if comment:
displayPane.append(PermalinkMessage(article.make_permalink_slow()))
displayPane.append(LinkCommentSep())
# insert reply box only for logged in user
if c.user_is_loggedin and can_comment_link(article) and not is_api():
#no comment box for permalinks
display = False
if not comment and article._age < sr.archive_age:
display = True
if article.promoted:
geotargeted, city_target = promote.is_geotargeted_promo(article)
if geotargeted:
displayPane.append(GeotargetNotice(city_target=city_target))
displayPane.append(UserText(item=article, creating=True,
post_form='comment',
display=display,
cloneable=True))
if previous_visits:
displayPane.append(CommentVisitsBox(previous_visits))
if c.site.allows_referrers:
c.referrer_policy = "always"
suggested_sort_active = False
suggested_sort = article.sort_if_suggested() if feature.is_enabled('default_sort') else None
if article.contest_mode:
if c.user_is_loggedin and sr.is_moderator(c.user):
# Default to top for contest mode to make determining winners
# easier, but allow them to override it for moderation
# purposes.
if 'sort' not in request.params:
sort = "top"
else:
sort = "random"
elif suggested_sort and 'sort' not in request.params:
sort = suggested_sort
suggested_sort_active = True
# finally add the comment listing
displayPane.append(CommentPane(article, CommentSortMenu.operator(sort),
comment, context, num, **kw))
subtitle_buttons = []
if c.focal_comment or context is not None:
subtitle = None
elif article.num_comments == 0:
subtitle = _("no comments (yet)")
elif article.num_comments <= num:
subtitle = _("all %d comments") % article.num_comments
else:
subtitle = _("top %d comments") % num
if g.max_comments > num:
self._add_show_comments_link(subtitle_buttons, article, num,
g.max_comments, gold=False)
if (c.user_is_loggedin and
(c.user.gold or sr.is_moderator(c.user)) and
article.num_comments > g.max_comments):
self._add_show_comments_link(subtitle_buttons, article, num,
g.max_comments_gold, gold=True)
sort_menu = CommentSortMenu(
default=sort,
css_class='suggested' if suggested_sort_active else '',
suggested_sort=suggested_sort,
)
link_settings = LinkCommentsSettings(
article,
sort=sort,
suggested_sort=suggested_sort,
)
res = LinkInfoPage(link=article, comment=comment,
content=displayPane,
page_classes=['comments-page'],
subtitle=subtitle,
subtitle_buttons=subtitle_buttons,
nav_menus=[sort_menu, link_settings],
infotext=infotext).render()
return res
def _add_show_comments_link(self, array, article, num, max_comm, gold=False):
if num == max_comm:
return
elif article.num_comments <= max_comm:
link_text = _("show all %d") % article.num_comments
else:
link_text = _("show %d") % max_comm
limit_param = "?limit=%d" % max_comm
if gold:
link_class = "gold"
else:
link_class = ""
more_link = article.make_permalink_slow() + limit_param
array.append( (link_text, more_link, link_class) )
@validate(VUser(),
name=nop('name'))
def GET_newreddit(self, name):
"""Create a subreddit form"""
title = _('create a subreddit')
captcha = Captcha() if c.user.needs_captcha() else None
content = CreateSubreddit(name=name or '', captcha=captcha)
res = FormPage(_("create a subreddit"),
content=content,
captcha=captcha,
).render()
return res
@pagecache_policy(PAGECACHE_POLICY.LOGGEDIN_AND_LOGGEDOUT)
@require_oauth2_scope("modconfig")
@api_doc(api_section.moderation, uses_site=True)
def GET_stylesheet(self):
"""Redirect to the subreddit's stylesheet if one exists.
See also: [/api/subreddit_stylesheet](#POST_api_subreddit_stylesheet).
"""
# de-stale the subreddit object so we don't poison downstream caches
if not isinstance(c.site, FakeSubreddit):
c.site = Subreddit._byID(c.site._id, data=True, stale=False)
url = Reddit.get_subreddit_stylesheet_url(c.site)
if url:
return self.redirect(url)
else:
self.abort404()
def _make_moderationlog(self, srs, num, after, reverse, count, mod=None, action=None):
query = Subreddit.get_modactions(srs, mod=mod, action=action)
builder = ModActionBuilder(
query, num=num, after=after, count=count, reverse=reverse,
wrap=default_thing_wrapper())
listing = ModActionListing(builder)
pane = listing.listing()
return pane
modname_splitter = re.compile('[ ,]+')
@require_oauth2_scope("modlog")
@disable_subreddit_css()
@paginated_listing(max_page_size=500, backend='cassandra')
@validate(
mod=nop('mod', docs={"mod": "(optional) a moderator filter"}),
action=VOneOf('type', ModAction.actions),
)
@api_doc(api_section.moderation, uses_site=True,
uri="/about/log", supports_rss=True)
def GET_moderationlog(self, num, after, reverse, count, mod, action):
"""Get a list of recent moderation actions.
Moderator actions taken within a subreddit are logged. This listing is
a view of that log with various filters to aid in analyzing the
information.
The optional `mod` parameter can be a comma-delimited list of moderator
names to restrict the results to, or the string `a` to restrict the
results to admin actions taken within the subreddit.
The `type` parameter is optional and if sent limits the log entries
returned to only those of the type specified.
"""
if not c.user_is_loggedin or not (c.user_is_admin or
c.site.is_moderator(c.user)):
return self.abort404()
if mod:
if mod == 'a':
modnames = g.admins
else:
modnames = self.modname_splitter.split(mod)
mod = []
for name in modnames:
try:
mod.append(Account._by_name(name, allow_deleted=True))
except NotFound:
continue
mod = mod or None
if isinstance(c.site, (MultiReddit, ModSR)):
srs = Subreddit._byID(c.site.sr_ids, return_dict=False)
# grab all moderators
mod_ids = set(Subreddit.get_all_mod_ids(srs))
mods = Account._byID(mod_ids, data=True)
pane = self._make_moderationlog(srs, num, after, reverse, count,
mod=mod, action=action)
elif isinstance(c.site, FakeSubreddit):
return self.abort404()
else:
mod_ids = c.site.moderators
mods = Account._byID(mod_ids, data=True)
pane = self._make_moderationlog(c.site, num, after, reverse, count,
mod=mod, action=action)
panes = PaneStack()
panes.append(pane)
action_buttons = [QueryButton(_('all'), None, query_param='type',
css_class='primary')]
for a in ModAction.actions:
button = QueryButton(ModAction._menu[a], a, query_param='type')
action_buttons.append(button)
mod_buttons = [QueryButton(_('all'), None, query_param='mod',
css_class='primary')]
for mod_id in mod_ids:
mod = mods[mod_id]
mod_buttons.append(QueryButton(mod.name, mod.name,
query_param='mod'))
# add a choice for the automoderator account if it's not a mod
if (g.automoderator_account and
all(mod.name != g.automoderator_account
for mod in mods.values())):
automod_button = QueryButton(
g.automoderator_account,
g.automoderator_account,
query_param="mod",
)
mod_buttons.append(automod_button)
mod_buttons.append(QueryButton(_('admins*'), 'a', query_param='mod'))
base_path = request.path
menus = [NavMenu(action_buttons, base_path=base_path,
title=_('filter by action'), type='lightdrop', css_class='modaction-drop'),
NavMenu(mod_buttons, base_path=base_path,
title=_('filter by moderator'), type='lightdrop')]
extension_handling = "private" if c.user.pref_private_feeds else False
return EditReddit(content=panes,
nav_menus=menus,
location="log",
extension_handling=extension_handling).render()
def _make_spamlisting(self, location, only, num, after, reverse, count):
include_links, include_comments = True, True
if only == 'links':
include_comments = False
elif only == 'comments':
include_links = False
if location == 'reports':
query = c.site.get_reported(include_links=include_links,
include_comments=include_comments)
elif location == 'spam':
query = c.site.get_spam(include_links=include_links,
include_comments=include_comments)
elif location == 'modqueue':
query = c.site.get_modqueue(include_links=include_links,
include_comments=include_comments)
elif location == 'unmoderated':
query = c.site.get_unmoderated()
elif location == 'edited':
query = c.site.get_edited(include_links=include_links,
include_comments=include_comments)
else:
raise ValueError
if isinstance(query, thing.Query):
builder_cls = QueryBuilder
elif isinstance (query, list):
builder_cls = QueryBuilder
else:
builder_cls = IDBuilder
def keep_fn(x):
# no need to bother mods with banned users, or deleted content
if x._deleted:
return False
if getattr(x,'author',None) == c.user and c.user._spam:
return False
if location == "reports":
return x.reported > 0 and not x._spam
elif location == "spam":
return x._spam
elif location == "modqueue":
if x.reported > 0 and not x._spam:
return True # reported but not banned
if x.author._spam and x.subreddit.exclude_banned_modqueue:
# banned user, don't show if subreddit pref excludes
return False
verdict = getattr(x, "verdict", None)
if verdict is None:
return True # anything without a verdict
if x._spam and verdict != 'mod-removed':
return True # spam, unless banned by a moderator
return False
elif location == "unmoderated":
# banned user, don't show if subreddit pref excludes
if x.author._spam and x.subreddit.exclude_banned_modqueue:
return False
return not getattr(x, 'verdict', None)
elif location == "edited":
return bool(getattr(x, "editted", False))
else:
raise ValueError
builder = builder_cls(query,
skip=True,
num=num, after=after,
keep_fn=keep_fn,
count=count, reverse=reverse,
wrap=ListingController.builder_wrapper,
spam_listing=True)
listing = LinkListing(builder)
pane = listing.listing()
# Indicate that the comment tree wasn't built for comments
for i in pane.things:
if hasattr(i, 'body'):
i.child = None
return pane
def _edit_normal_reddit(self, location, created):
if (location == 'edit' and
c.user_is_loggedin and
(c.user_is_admin or c.site.is_moderator_with_perms(c.user, 'config'))):
pane = PaneStack()
if created == 'true':
pane.append(InfoBar(message=strings.sr_created))
c.allow_styles = True
c.site = Subreddit._byID(c.site._id, data=True, stale=False)
pane.append(CreateSubreddit(site=c.site))
elif (location == 'stylesheet'
and c.site.can_change_stylesheet(c.user)
and not g.css_killswitch):
stylesheet_contents = c.site.fetch_stylesheet_source()
c.allow_styles = True
pane = SubredditStylesheet(site=c.site,
stylesheet_contents=stylesheet_contents)
elif (location == 'stylesheet'
and c.site.can_view(c.user)
and not g.css_killswitch):
stylesheet = c.site.fetch_stylesheet_source()
pane = SubredditStylesheetSource(stylesheet_contents=stylesheet)
elif (location == 'traffic' and
(c.site.public_traffic or
(c.user_is_loggedin and
(c.site.is_moderator(c.user) or c.user.employee)))):
pane = trafficpages.SubredditTraffic()
elif (location == "about") and is_api():
return self.redirect(add_sr('about.json'), code=301)
else:
return self.abort404()
return EditReddit(content=pane,
location=location,
extension_handling=False).render()
@require_oauth2_scope("read")
@base_listing
@disable_subreddit_css()
@validate(VSrModerator(perms='posts'),
location=nop('location'),
only=VOneOf('only', ('links', 'comments')))
@api_doc(
api_section.moderation,
uses_site=True,
uri='/about/{location}',
uri_variants=['/about/' + loc for loc in
('reports', 'spam', 'modqueue', 'unmoderated', 'edited')],
)
def GET_spamlisting(self, location, only, num, after, reverse, count):
"""Return a listing of posts relevant to moderators.
* reports: Things that have been reported.
* spam: Things that have been marked as spam or otherwise removed.
* modqueue: Things requiring moderator review, such as reported things
and items caught by the spam filter.
* unmoderated: Things that have yet to be approved/removed by a mod.
* edited: Things that have been edited recently.
Requires the "posts" moderator permission for the subreddit.
"""
c.allow_styles = True
c.profilepage = True
panes = PaneStack()
# We clone and modify this when a user clicks 'reply' on a comment.
replyBox = UserText(item=None, display=False, cloneable=True,
creating=True, post_form='comment')
panes.append(replyBox)
spamlisting = self._make_spamlisting(location, only, num, after,
reverse, count)
panes.append(spamlisting)
extension_handling = "private" if c.user.pref_private_feeds else False
if location in ('reports', 'spam', 'modqueue', 'edited'):
buttons = [
QueryButton(_('links and comments'), None, query_param='only'),
QueryButton(_('links'), 'links', query_param='only'),
QueryButton(_('comments'), 'comments', query_param='only'),
]
menus = [NavMenu(buttons, base_path=request.path, title=_('show'),
type='lightdrop')]
else:
menus = None
return EditReddit(content=panes,
location=location,
nav_menus=menus,
extension_handling=extension_handling).render()
@base_listing
@disable_subreddit_css()
@validate(VSrModerator(perms='flair'),
name=nop('name'))
def GET_flairlisting(self, num, after, reverse, count, name):
user = None
if name:
try:
user = Account._by_name(name)
except NotFound:
c.errors.add(errors.USER_DOESNT_EXIST, field='name')
c.allow_styles = True
pane = FlairPane(num, after, reverse, name, user)
return EditReddit(content=pane, location='flair').render()
@require_oauth2_scope("modconfig")
@disable_subreddit_css()
@validate(location=nop('location'),
created=VOneOf('created', ('true','false'),
default='false'))
@api_doc(api_section.subreddits, uri="/r/{subreddit}/about/edit")
def GET_editreddit(self, location, created):
"""Get the current settings of a subreddit.
In the API, this returns the current settings of the subreddit as used
by [/api/site_admin](#POST_api_site_admin). On the HTML site, it will
display a form for editing the subreddit.
"""
c.profilepage = True
if isinstance(c.site, FakeSubreddit):
return self.abort404()
else:
return self._edit_normal_reddit(location, created)
@require_oauth2_scope("read")
@api_doc(api_section.subreddits, uri='/r/{subreddit}/about')
def GET_about(self):
"""Return information about the subreddit.
Data includes the subscriber count, description, and header image."""
if not is_api() or isinstance(c.site, FakeSubreddit):
return self.abort404()
return Reddit(content=Wrapped(c.site)).render()
@require_oauth2_scope("read")
@api_doc(api_section.subreddits, uses_site=True)
def GET_sidebar(self):
"""Get the sidebar for the current subreddit"""
usertext = UserText(c.site, c.site.description)
return Reddit(content=usertext).render()
@require_oauth2_scope("read")
@api_doc(api_section.subreddits, uses_site=True)
def GET_sticky(self):
"""Get the post stickied to the current subreddit
Will 404 if there is not currently a sticky post in this subreddit
"""
if c.site.sticky_fullname:
sticky = Link._by_fullname(c.site.sticky_fullname, data=True)
self.redirect(sticky.make_permalink_slow())
else:
abort(404)
def GET_awards(self):
"""The awards page."""
return BoringPage(_("awards"), content=UserAwards()).render()
# filter for removing punctuation which could be interpreted as search syntax
related_replace_regex = re.compile(r'[?\\&|!{}+~^()"\':*-]+')
related_replace_with = ' '
@base_listing
@require_oauth2_scope("read")
@validate(article=VLink('article'))
@api_doc(api_section.listings, uri="/related/{article}")
def GET_related(self, num, article, after, reverse, count):
"""Related page: performs a search using title of article as
the search query.
"""
if not can_view_link_comments(article):
abort(403, 'forbidden')
query = self.related_replace_regex.sub(self.related_replace_with,
article.title)
query = _force_unicode(query)
query = query[:1024]
query = u"|".join(query.split())
query = u"title:'%s'" % query
rel_range = timedelta(days=3)
start = int(time_module.mktime((article._date - rel_range).utctimetuple()))
end = int(time_module.mktime((article._date + rel_range).utctimetuple()))
nsfw = u"nsfw:0" if not article.is_nsfw else u""
query = u"(and %s timestamp:%s..%s %s)" % (query, start, end, nsfw)
q = SearchQuery(query, raw_sort="-text_relevance", faceting={},
syntax="cloudsearch")
content = self._search(q, num=num, after=after, reverse=reverse,
count=count)
return LinkInfoPage(link=article, content=content,
page_classes=['related-page'],
subtitle=_('related')).render()
@base_listing
@require_oauth2_scope("read")
@validate(article=VLink('article'))
@api_doc(
api_section.listings,
uri="/duplicates/{article}",
supports_rss=True,
)
def GET_duplicates(self, article, num, after, reverse, count):
"""Return a list of other submissions of the same URL"""
if not can_view_link_comments(article):
abort(403, 'forbidden')
builder = url_links_builder(article.url, exclude=article._fullname,
num=num, after=after, reverse=reverse,
count=count)
if after and not builder.valid_after(after):
g.stats.event_count("listing.invalid_after", "duplicates")
self.abort403()
num_duplicates = len(builder.get_items()[0])
listing = LinkListing(builder).listing()
res = LinkInfoPage(link=article,
comment=None,
num_duplicates=num_duplicates,
content=listing,
page_classes=['other-discussions-page'],
subtitle=_('other discussions')).render()
return res
@base_listing
@require_oauth2_scope("read")
@validate(query=nop('q', docs={"q": "a search query"}))
@api_doc(api_section.subreddits, uri='/subreddits/search', supports_rss=True)
def GET_search_reddits(self, query, reverse, after, count, num):
"""Search subreddits by title and description."""
# do not officially expose sort api yet
vsort = VMenu('sort', SubredditSearchSortMenu, remember=False)
sort = vsort.run(request.GET.get('sort'), '')
# show NSFW to API and RSS users unless obey_over18=true
is_api_or_rss = (c.render_style in API_TYPES
or c.render_style in RSS_TYPES)
if is_api_or_rss:
include_over18 = not c.obey_over18 or c.over18
elif feature.is_enabled('safe_search'):
include_over18 = c.over18
else:
include_over18 = True
if feature.is_enabled('subreddit_relevancy') and sort == 'relevance':
sort = 'rel1'
q = SubredditSearchQuery(query, sort=sort, faceting={},
include_over18=include_over18)
content = self._search(q, num=num, reverse=reverse,
after=after, count=count,
skip_deleted_authors=False)
res = SubredditsPage(content=content,
prev_search=query,
elapsed_time=etime,
page_classes=['subreddits-page'],
# update if we ever add sorts
search_params={},
title=_("search results"),
simple=True).render()
return res
search_help_page = "/wiki/search"
verify_langs_regex = re.compile(r"\A[a-z][a-z](,[a-z][a-z])*\Z")
@base_listing
@require_oauth2_scope("read")
@validate(query=VLength('q', max_length=512),
sort=VMenu('sort', SearchSortMenu, remember=False),
recent=VMenu('t', TimeMenu, remember=False),
restrict_sr=VBoolean('restrict_sr', default=False),
include_facets=VBoolean('include_facets', default=False),
syntax=VOneOf('syntax', options=SearchQuery.known_syntaxes))
@api_doc(api_section.search, supports_rss=True, uses_site=True)
def GET_search(self, query, num, reverse, after, count, sort, recent,
restrict_sr, include_facets, syntax):
"""Search links page."""
if query and '.' in query:
url = sanitize_url(query, require_scheme=True)
if url:
return self.redirect("/submit" + query_string({'url':url}))
if not restrict_sr:
site = DefaultSR()
else:
site = c.site
if not syntax:
syntax = SearchQuery.default_syntax
# show NSFW to API and RSS users unless obey_over18=true
is_api_or_rss = (c.render_style in API_TYPES
or c.render_style in RSS_TYPES)
if is_api_or_rss:
include_over18 = not c.obey_over18 or c.over18
elif feature.is_enabled('safe_search'):
include_over18 = c.over18
else:
include_over18 = True
# do not request facets for api requests, unless specifically requested
if is_api():
faceting = None if include_facets else {}
else:
faceting = None
result_type = request.GET.get('type')
sr_num = 0
# combined results on first page only, html site only
if c.render_style == 'html' and feature.is_enabled('subreddit_search'):
if after is None and not restrict_sr and not result_type:
# hardcoded to 5 subreddits (or fewer)
sr_num = min(5, int(num / 5))
num = num - sr_num
elif result_type == 'sr':
sr_num = num
num = 0
restrict_sr = False
content = None
subreddits = None
cleanup_message = None
converted_data = None
subreddit_facets = None
if num > 0:
try: