This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
/
pages.py
3569 lines (2960 loc) · 135 KB
/
pages.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 CondeNet, Inc.
#
# All portions of the code written by CondeNet are Copyright (c) 2006-2010
# CondeNet, Inc. All Rights Reserved.
################################################################################
from r2.lib.wrapped import Wrapped, Templated, CachedTemplate
from r2.models import Account, FakeAccount, DefaultSR, make_feedurl
from r2.models import FakeSubreddit, Subreddit, Ad, AdSR
from r2.models import Friends, All, Sub, NotFound, DomainSR, Random, Mod, RandomNSFW, MultiReddit
from r2.models import Link, Printable, Trophy, bidding, PromotionWeights, Comment, Flair
from r2.config import cache
from r2.lib.tracking import AdframeInfo
from r2.lib.jsonresponse import json_respond
from r2.lib.jsontemplates import is_api
from pylons.i18n import _, ungettext
from pylons import c, request, g
from pylons.controllers.util import abort
from r2.lib import promote
from r2.lib.traffic import load_traffic, load_summary
from r2.lib.captcha import get_iden
from r2.lib.contrib.markdown import markdown
from r2.lib.filters import spaceCompress, _force_unicode, _force_utf8
from r2.lib.filters import unsafe, websafe, SC_ON, SC_OFF, websafe_json
from r2.lib.menus import NavButton, NamedButton, NavMenu, PageNameNav, JsButton
from r2.lib.menus import SubredditButton, SubredditMenu, ModeratorMailButton
from r2.lib.menus import OffsiteButton, menu, JsNavMenu
from r2.lib.strings import plurals, rand_strings, strings, Score
from r2.lib.utils import title_to_url, query_string, UrlParser, to_js, vote_hash
from r2.lib.utils import link_duplicates, make_offset_date, to_csv, median, to36
from r2.lib.utils import trunc_time, timesince, timeuntil
from r2.lib.template_helpers import add_sr, get_domain
from r2.lib.subreddit_search import popular_searches
from r2.lib.scraper import get_media_embed
from r2.lib.log import log_text
from r2.lib.memoize import memoize
from r2.lib.utils import trunc_string as _truncate
import sys, random, datetime, locale, calendar, simplejson, re, time
import graph, pycountry, time
from itertools import chain
from urllib import quote
from things import wrap_links, default_thing_wrapper
datefmt = _force_utf8(_('%d %b %Y'))
MAX_DESCRIPTION_LENGTH = 150
def get_captcha():
if not c.user_is_loggedin or c.user.needs_captcha():
return get_iden()
def responsive(res, space_compress = False):
"""
Use in places where the template is returned as the result of the
controller so that it becomes compatible with the page cache.
"""
if is_api():
res = json_respond(res)
if c.allowed_callback:
res = "%s(%s)" % (websafe_json(c.allowed_callback), res)
elif space_compress:
res = spaceCompress(res)
c.response.content = res
return c.response
class Reddit(Templated):
'''Base class for rendering a page on reddit. Handles toolbar creation,
content of the footers, and content of the corner buttons.
Constructor arguments:
space_compress -- run r2.lib.filters.spaceCompress on render
loginbox -- enable/disable rendering of the small login box in the right margin
(only if no user is logged in; login box will be disabled for a logged in user)
show_sidebar -- enable/disable content in the right margin
infotext -- text to display in a <p class="infotext"> above the content
nav_menus -- list of Menu objects to be shown in the area below the header
content -- renderable object to fill the main content well in the page.
settings determined at class-declaration time
create_reddit_box -- enable/disable display of the "Create a reddit" box
submit_box -- enable/disable display of the "Submit" box
searchbox -- enable/disable the "search" box in the header
extension_handling -- enable/disable rendering using non-html templates
(e.g. js, xml for rss, etc.)
'''
create_reddit_box = True
submit_box = True
footer = True
searchbox = True
extension_handling = True
enable_login_cover = True
site_tracking = True
show_firsttext = True
additional_css = None
def __init__(self, space_compress = True, nav_menus = None, loginbox = True,
infotext = '', content = None, short_description='', title = '', robots = None,
show_sidebar = True, footer = True, srbar = True,
**context):
Templated.__init__(self, **context)
self.title = title
self.short_description = short_description
self.robots = robots
self.infotext = infotext
self.loginbox = True
self.show_sidebar = show_sidebar
self.space_compress = space_compress and not g.template_debug
# instantiate a footer
self.footer = RedditFooter() if footer else None
#put the sort menus at the top
self.nav_menu = MenuArea(menus = nav_menus) if nav_menus else None
#add the infobar
self.infobar = None
# generate a canonical link for google
self.canonical_link = request.fullpath
if c.render_style != "html":
u = UrlParser(request.fullpath)
u.set_extension("")
u.hostname = g.domain
if g.domain_prefix:
u.hostname = "%s.%s" % (g.domain_prefix, u.hostname)
self.canonical_link = u.unparse()
if self.show_firsttext and not infotext:
if g.heavy_load_mode:
# heavy load mode message overrides read only
infotext = strings.heavy_load_msg
elif g.read_only_mode:
infotext = strings.read_only_msg
elif (c.firsttime == 'mobile_suggest' and
c.render_style != 'compact'):
infotext = strings.iphone_first
elif c.firsttime and c.site.firsttext:
infotext = c.site.firsttext
if infotext:
self.infobar = InfoBar(message = infotext)
self.srtopbar = None
if srbar and not c.cname and not is_api():
self.srtopbar = SubredditTopBar()
if c.user_is_loggedin and self.show_sidebar and not is_api():
self._content = PaneStack([ShareLink(), content])
else:
self._content = content
self.toolbars = self.build_toolbars()
def sr_admin_menu(self):
buttons = [NavButton(menu.community_settings, css_class = 'reddit-edit',
dest = "edit"),
NamedButton('modmail', dest = "message/inbox",
css_class = 'moderator-mail'),
NamedButton('moderators', css_class = 'reddit-moderators')]
if c.site.type != 'public':
buttons.append(NamedButton('contributors',
css_class = 'reddit-contributors'))
elif (c.user_is_loggedin and
(c.site.is_moderator(c.user) or c.user_is_admin)):
buttons.append(NavButton(menu.contributors, "contributors",
css_class = 'reddit-contributors'))
buttons.extend([
NamedButton('traffic', css_class = 'reddit-traffic'),
NamedButton('reports', css_class = 'reddit-reported'),
NamedButton('spam', css_class = 'reddit-spam'),
NamedButton('banned', css_class = 'reddit-ban'),
NamedButton('flair', css_class = 'reddit-flair'),
])
return [NavMenu(buttons, type = "flat_vert", base_path = "/about/",
css_class = "icon-menu", separator = '')]
def sr_moderators(self, limit = 10):
accounts = Account._byID([uid
for uid in c.site.moderators[:limit]],
data=True, return_dict=False)
return [WrappedUser(a) for a in accounts if not a._deleted]
def rightbox(self):
"""generates content in <div class="rightbox">"""
ps = PaneStack(css_class='spacer')
if self.searchbox:
ps.append(SearchForm())
if not c.user_is_loggedin and self.loginbox and not g.read_only_mode:
ps.append(LoginFormWide())
if c.user.pref_show_sponsorships or not c.user.gold:
ps.append(SponsorshipBox())
no_ads_yet = True
if isinstance(c.site, MultiReddit) and c.user_is_loggedin:
srs = Subreddit._byID(c.site.sr_ids,data=True,
return_dict=False)
if srs:
ps.append(SideContentBox(_('these reddits'),[SubscriptionBox(srs=srs)]))
if not isinstance(c.site, FakeSubreddit) and not c.cname:
#don't show the subreddit info bar on cnames
ps.append(SubredditInfoBar())
if (c.user.pref_show_adbox or not c.user.gold) and not g.disable_ads:
ps.append(Ads())
no_ads_yet = False
if self.submit_box and (c.user_is_loggedin or not g.read_only_mode):
ps.append(SideBox(_('Submit a link'),
'/submit', 'submit',
sr_path = (isinstance(c.site,DefaultSR)
or not isinstance(c.site, FakeSubreddit)),
subtitles = [strings.submit_box_text],
show_cover = True))
if self.create_reddit_box and c.user_is_loggedin:
delta = datetime.datetime.now(g.tz) - c.user._date
if delta.days >= g.min_membership_create_community:
ps.append(SideBox(_('Create your own community'),
'/reddits/create', 'create',
subtitles = rand_strings.get("create_reddit", 2),
show_cover = True, nocname=True))
if False and self.submit_box:
ps.append(SideBox(_('reddit gold creddits: now for sale!'),
'http://www.reddit.com/tb/efpn0',
'gold',
sr_path = False,
subtitles = ["check it out: you can now give gold",
"subscriptions to deserving redditors"],
show_cover = False, nocname = True))
if not isinstance(c.site, FakeSubreddit) and not c.cname:
moderators = self.sr_moderators()
if moderators:
total = len(c.site.moderators)
more_text = mod_href = ""
if total > len(moderators):
more_text = "...and %d more" % (total - len(moderators))
mod_href = "http://%s/about/moderators" % get_domain()
helplink = ("/message/compose?to=%%23%s" % c.site.name,
"message the moderators")
ps.append(SideContentBox(_('moderators'), moderators,
helplink = helplink,
more_href = mod_href,
more_text = more_text))
if (c.user_is_loggedin and
(c.site.is_moderator(c.user) or c.user_is_admin)):
ps.append(SideContentBox(_('admin box'), self.sr_admin_menu()))
if no_ads_yet and not g.disable_ads:
if c.user.pref_show_adbox or not c.user.gold:
ps.append(Ads())
if c.user_is_admin:
ps.append(Admin_Rightbox())
if c.user.pref_clickgadget and c.recent_clicks:
ps.append(SideContentBox(_("Recently viewed links"),
[ClickGadget(c.recent_clicks)]))
return ps
def render(self, *a, **kw):
"""Overrides default Templated.render with two additions
* support for rendering API requests with proper wrapping
* support for space compression of the result
In adition, unlike Templated.render, the result is in the form of a pylons
Response object with it's content set.
"""
res = Templated.render(self, *a, **kw)
return responsive(res, self.space_compress)
def corner_buttons(self):
"""set up for buttons in upper right corner of main page."""
buttons = []
if c.user_is_loggedin:
if c.user.name in g.admins:
if c.user_is_admin:
buttons += [NamedButton("adminoff", False,
nocname=not c.authorized_cname,
target = "_self")]
else:
buttons += [NamedButton("adminon", False,
nocname=not c.authorized_cname,
target = "_self")]
buttons += [NamedButton("prefs", False,
css_class = "pref-lang")]
else:
lang = c.lang.split('-')[0] if c.lang else ''
buttons += [JsButton(g.lang_name.get(lang, lang),
onclick = "return showlang();",
css_class = "pref-lang")]
return NavMenu(buttons, base_path = "/", type = "flatlist")
def build_toolbars(self):
"""Sets the layout of the navigation topbar on a Reddit. The result
is a list of menus which will be rendered in order and
displayed at the top of the Reddit."""
if c.site == Friends:
main_buttons = [NamedButton('new', dest='', aliases=['/hot']),
NamedButton('comments')]
else:
main_buttons = [NamedButton('hot', dest='', aliases=['/hot']),
NamedButton('new'),
NamedButton('controversial'),
NamedButton('top'),
]
if c.user_is_loggedin or not g.read_only_mode:
main_buttons.append(NamedButton('saved', False))
more_buttons = []
if c.user_is_loggedin:
if c.user_is_admin:
more_buttons.append(NamedButton('admin', False))
more_buttons.append(NamedButton('traffic', False))
if c.user.pref_show_promote or c.user_is_sponsor:
more_buttons.append(NavButton(menu.promote, 'promoted', False))
#if there's only one button in the dropdown, get rid of the dropdown
if len(more_buttons) == 1:
main_buttons.append(more_buttons[0])
more_buttons = []
toolbar = [NavMenu(main_buttons, type='tabmenu')]
if more_buttons:
toolbar.append(NavMenu(more_buttons, title=menu.more, type='tabdrop'))
if not isinstance(c.site, DefaultSR) and not c.cname:
toolbar.insert(0, PageNameNav('subreddit'))
return toolbar
def __repr__(self):
return "<Reddit>"
@staticmethod
def content_stack(panes, css_class = None):
"""Helper method for reordering the content stack."""
return PaneStack(filter(None, panes), css_class = css_class)
def content(self):
"""returns a Wrapped (or renderable) item for the main content div."""
return self.content_stack((self.infobar, self.nav_menu, self._content))
class RedditHeader(Templated):
def __init__(self):
pass
class RedditFooter(CachedTemplate):
def cachable_attrs(self):
return [('path', request.path),
('buttons', [[(x.title, x.path) for x in y] for y in self.nav])]
def __init__(self):
self.nav = [NavMenu([
OffsiteButton("mobile",
"/static/reddit_mobile/index.htm"),
OffsiteButton("rss", dest = '/.rss'),
NamedButton("store", False, nocname=True),
NamedButton("awards", False, nocname=True),
NamedButton('random', False, nocname=False),
],
title = _('site links'), type = 'flat_vert',
separator = ''),
NavMenu([NamedButton("help", False, nocname=True),
OffsiteButton(_("FAQ"), dest = '/help/faq',
nocname=True),
OffsiteButton(_("reddiquette"), nocname=True,
dest = '/help/reddiquette'),
NamedButton("feedback", False),
NamedButton("i18n", False),
],
title = _('help'), type = 'flat_vert',
separator = ''),
NavMenu([NamedButton("bookmarklets", False),
NamedButton("buttons", True),
NamedButton("code", False, nocname=True),
NamedButton("socialite", False),
NamedButton("widget", True)],
title = _('reddit tools'), type = 'flat_vert',
separator = ''),
NavMenu([
NamedButton("blog", False, nocname=True),
NamedButton("gold", False, nocname=True,
dest = '/help/gold', css_class = "buygold"),
NamedButton("promote", False, nocname=True,
dest = '/promoted', css_class = "red"),
NamedButton("ad_inq", False, nocname=True)],
title = _('about us'), type = 'flat_vert',
separator = ''),
NavMenu([OffsiteButton('BaconBuzz',
"http://www.baconbuzz.com"),
OffsiteButton('Destructoid reddit',
"http://reddit.destructoid.com"),
OffsiteButton('TheCuteList',
"http://www.thecutelist.com"),
OffsiteButton('The Independent reddit',
"http://reddit.independent.co.uk"),
OffsiteButton('redditGadgetGuide',
"http://www.redditgadgetguide.com"),
OffsiteButton('WeHeartGossip',
"http://www.weheartgossip.com"),
OffsiteButton('idealistNews',
"http://www.idealistnews.com"),],
title = _('brothers'), type = 'flat_vert',
separator = ''),
NavMenu([OffsiteButton('Wired.com',
"http://www.wired.com"),
OffsiteButton('Ars Technica',
"http://www.arstechnica.com"),
OffsiteButton('Style.com',
"http://www.style.com"),
OffsiteButton('Epicurious.com',
"http://www.epicurious.com"),
OffsiteButton('Concierge.com',
"http://www.concierge.com")],
title = _('sisters'), type = 'flat_vert',
separator = '')
]
CachedTemplate.__init__(self)
class ClickGadget(Templated):
def __init__(self, links, *a, **kw):
self.links = links
self.content = ''
if c.user_is_loggedin and self.links:
self.content = self.make_content()
Templated.__init__(self, *a, **kw)
def make_content(self):
#this will disable the hardcoded widget styles
request.get.style = "off"
wrapper = default_thing_wrapper(embed_voting_style = 'votable',
style = "htmllite")
content = wrap_links(self.links, wrapper = wrapper)
return content.render(style = "htmllite")
class RedditMin(Reddit):
"""a version of Reddit that has no sidebar, toolbar, footer,
etc"""
footer = False
show_sidebar = False
show_firsttext = False
class LoginFormWide(CachedTemplate):
"""generates a login form suitable for the 300px rightbox."""
def __init__(self):
self.cname = c.cname
self.auth_cname = not c.frameless_cname or c.authorized_cname
CachedTemplate.__init__(self)
class SubredditInfoBar(CachedTemplate):
"""When not on Default, renders a sidebox which gives info about
the current reddit, including links to the moderator and
contributor pages, as well as links to the banning page if the
current user is a moderator."""
def __init__(self, site = None):
site = site or c.site
# hackity hack. do i need to add all the others props?
self.sr = list(wrap_links(site))[0]
# we want to cache on the number of subscribers
self.subscribers = self.sr._ups
# so the menus cache properly
self.path = request.path
# if user has flair, then it will be displayed in this bar
self.flair_user = None
if c.user_is_loggedin:
wrapped_user = WrappedUser(c.user, subreddit=self.sr,
force_show_flair=True)
if wrapped_user.has_flair:
self.flair_user = wrapped_user
CachedTemplate.__init__(self)
def nav(self):
buttons = [NavButton(plurals.moderators, 'moderators')]
if self.type != 'public':
buttons.append(NavButton(getattr(plurals, "approved submitters"), 'contributors'))
if self.is_moderator or self.is_admin:
buttons.extend([
NamedButton('spam'),
NamedButton('reports'),
NavButton(menu.banusers, 'banned'),
NamedButton('traffic'),
NavButton(menu.community_settings, 'edit'),
NavButton(menu.flair, 'flair'),
])
return [NavMenu(buttons, type = "flat_vert", base_path = "/about/",
separator = '')]
class SponsorshipBox(Templated):
pass
class SideContentBox(Templated):
def __init__(self, title, content, helplink=None, extra_class=None,
more_href = None, more_text = "more"):
Templated.__init__(self, title=title, helplink = helplink,
content=content, extra_class=extra_class,
more_href = more_href,
more_text = more_text)
class SideBox(CachedTemplate):
"""
Generic sidebox used to generate the 'submit' and 'create a reddit' boxes.
"""
def __init__(self, title, link, css_class='', subtitles = [],
show_cover = False, nocname=False, sr_path = False):
CachedTemplate.__init__(self, link = link, target = '_top',
title = title, css_class = css_class,
sr_path = sr_path, subtitles = subtitles,
show_cover = show_cover, nocname=nocname)
class PrefsPage(Reddit):
"""container for pages accessible via /prefs. No extension handling."""
extension_handling = False
def __init__(self, show_sidebar = False, *a, **kw):
Reddit.__init__(self, show_sidebar = show_sidebar,
title = "%s (%s)" %(_("preferences"),
c.site.name.strip(' ')),
*a, **kw)
def build_toolbars(self):
buttons = [NavButton(menu.options, '')]
if c.user.pref_private_feeds:
buttons.append(NamedButton('feeds'))
buttons.extend([NamedButton('friends'),
NamedButton('update')])
#if CustomerID.get_id(user):
# buttons += [NamedButton('payment')]
buttons += [NamedButton('delete')]
return [PageNameNav('nomenu', title = _("preferences")),
NavMenu(buttons, base_path = "/prefs", type="tabmenu")]
class PrefOptions(Templated):
"""Preference form for updating language and display options"""
def __init__(self, done = False):
Templated.__init__(self, done = done)
class PrefFeeds(Templated):
pass
class PrefUpdate(Templated):
"""Preference form for updating email address and passwords"""
def __init__(self, email = True, password = True, verify = False):
self.email = email
self.password = password
self.verify = verify
Templated.__init__(self)
class PrefDelete(Templated):
"""preference form for deleting a user's own account."""
pass
class MessagePage(Reddit):
"""Defines the content for /message/*"""
def __init__(self, *a, **kw):
if not kw.has_key('show_sidebar'):
kw['show_sidebar'] = False
Reddit.__init__(self, *a, **kw)
if is_api():
self.replybox = None
else:
self.replybox = UserText(item = None, creating = True,
post_form = 'comment', display = False,
cloneable = True)
def content(self):
return self.content_stack((self.replybox,
self.infobar,
self.nav_menu,
self._content))
def build_toolbars(self):
buttons = [NamedButton('compose', sr_path = False),
NamedButton('inbox', aliases = ["/message/comments",
"/message/uread",
"/message/messages",
"/message/selfreply"],
sr_path = False),
NamedButton('sent', sr_path = False)]
if c.show_mod_mail:
buttons.append(ModeratorMailButton(menu.modmail, "moderator",
sr_path = False))
if not c.default_sr:
buttons.append(ModeratorMailButton(
_("%(site)s mail") % {'site': c.site.name}, "moderator",
aliases = ["/about/message/inbox",
"/about/message/unread"]))
return [PageNameNav('nomenu', title = _("message")),
NavMenu(buttons, base_path = "/message", type="tabmenu")]
class MessageCompose(Templated):
"""Compose message form."""
def __init__(self,to='', subject='', message='', success='',
captcha = None):
from r2.models.admintools import admintools
Templated.__init__(self, to = to, subject = subject,
message = message, success = success,
captcha = captcha,
admins = admintools.admin_list())
class BoringPage(Reddit):
"""parent class For rendering all sorts of uninteresting,
sortless, navless form-centric pages. The top navmenu is
populated only with the text provided with pagename and the page
title is 'reddit.com: pagename'"""
extension_handling= False
def __init__(self, pagename, **context):
self.pagename = pagename
name = c.site.name or g.default_sr
if "title" not in context:
context['title'] = "%s: %s" % (name, pagename)
Reddit.__init__(self, **context)
def build_toolbars(self):
return [PageNameNav('nomenu', title = self.pagename)]
class HelpPage(BoringPage):
def build_toolbars(self):
return [PageNameNav('help', title = self.pagename)]
class FormPage(BoringPage):
create_reddit_box = False
submit_box = False
"""intended for rendering forms with no rightbox needed or wanted"""
def __init__(self, pagename, show_sidebar = False, *a, **kw):
BoringPage.__init__(self, pagename, show_sidebar = show_sidebar,
*a, **kw)
class LoginPage(BoringPage):
enable_login_cover = False
short_title = "login"
"""a boring page which provides the Login/register form"""
def __init__(self, **context):
self.dest = context.get('dest', '')
context['loginbox'] = False
context['show_sidebar'] = False
if c.render_style == "compact":
title = self.short_title
else:
title = _("login or register")
BoringPage.__init__(self, title, **context)
def content(self):
kw = {}
for x in ('user_login', 'user_reg'):
kw[x] = getattr(self, x) if hasattr(self, x) else ''
return self.login_template(dest = self.dest, **kw)
@classmethod
def login_template(cls, **kw):
return Login(**kw)
class RegisterPage(LoginPage):
short_title = "register"
@classmethod
def login_template(cls, **kw):
return Register(**kw)
class Login(Templated):
"""The two-unit login and register form."""
def __init__(self, user_reg = '', user_login = '', dest=''):
Templated.__init__(self, user_reg = user_reg, user_login = user_login,
dest = dest, captcha = Captcha())
class Register(Login):
pass
class SearchPage(BoringPage):
"""Search results page"""
searchbox = False
def __init__(self, pagename, prev_search, elapsed_time,
num_results, search_params = {},
simple=False, restrict_sr = False, site=None,
*a, **kw):
self.searchbar = SearchBar(prev_search = prev_search,
elapsed_time = elapsed_time,
num_results = num_results,
search_params = search_params,
show_feedback = True, site=site,
simple=simple, restrict_sr=restrict_sr)
BoringPage.__init__(self, pagename, robots='noindex', *a, **kw)
def content(self):
return self.content_stack((self.searchbar, self.infobar,
self.nav_menu, self._content))
class TakedownPage(BoringPage):
def __init__(self, link):
BoringPage.__init__(self, getattr(link, "takedown_title", _("bummer")),
content = TakedownPane(link))
def render(self, *a, **kw):
response = BoringPage.render(self, *a, **kw)
return response
class TakedownPane(Templated):
def __init__(self, link, *a, **kw):
self.link = link
self.explanation = getattr(self.link, "explanation",
_("this page is no longer available due to a copyright claim."))
Templated.__init__(self, *a, **kw)
class CommentsPanel(Templated):
"""the side-panel on the reddit toolbar frame that shows the top
comments of a link"""
def __init__(self, link = None, listing = None, expanded = False, *a, **kw):
self.link = link
self.listing = listing
self.expanded = expanded
Templated.__init__(self, *a, **kw)
class CommentVisitsBox(Templated):
def __init__(self, visits, *a, **kw):
self.visits = []
for visit in visits:
pretty = timesince(visit, precision=60)
self.visits.append(pretty)
Templated.__init__(self, *a, **kw)
class LinkInfoPage(Reddit):
"""Renders the varied /info pages for a link. The Link object is
passed via the link argument and the content passed to this class
will be rendered after a one-element listing consisting of that
link object.
In addition, the rendering is reordered so that any nav_menus
passed to this class will also be rendered underneath the rendered
Link.
"""
create_reddit_box = False
def __init__(self, link = None, comment = None,
link_title = '', subtitle = None, duplicates = None,
*a, **kw):
c.permalink_page = True
expand_children = kw.get("expand_children", not bool(comment))
wrapper = default_thing_wrapper(expand_children=expand_children)
# link_listing will be the one-element listing at the top
self.link_listing = wrap_links(link, wrapper = wrapper)
# link is a wrapped Link object
self.link = self.link_listing.things[0]
link_title = ((self.link.title) if hasattr(self.link, 'title') else '')
# defaults whether or not there is a comment
params = {'title':_force_unicode(link_title), 'site' : c.site.name}
title = strings.link_info_title % params
short_description = None
if link and link.selftext:
short_description = _truncate(link.selftext.strip(), MAX_DESCRIPTION_LENGTH)
# only modify the title if the comment/author are neither deleted nor spam
if comment and not comment._deleted and not comment._spam:
author = Account._byID(comment.author_id, data=True)
if not author._deleted and not author._spam:
params = {'author' : author.name, 'title' : _force_unicode(link_title)}
title = strings.permalink_title % params
short_description = _truncate(comment.body.strip(), MAX_DESCRIPTION_LENGTH) if comment.body else None
self.subtitle = subtitle
if hasattr(self.link, "shortlink"):
self.shortlink = self.link.shortlink
# if we're already looking at the 'duplicates' page, we can
# avoid doing this lookup twice
if duplicates is None:
self.duplicates = link_duplicates(self.link)
else:
self.duplicates = duplicates
Reddit.__init__(self, title = title, short_description=short_description, *a, **kw)
def build_toolbars(self):
base_path = "/%s/%s/" % (self.link._id36, title_to_url(self.link.title))
base_path = _force_utf8(base_path)
def info_button(name, **fmt_args):
return NamedButton(name, dest = '/%s%s' % (name, base_path),
aliases = ['/%s/%s' % (name, self.link._id36)],
fmt_args = fmt_args)
buttons = []
if not getattr(self.link, "disable_comments", False):
buttons.extend([info_button('comments'),
info_button('related')])
if not self.link.is_self and self.duplicates:
buttons.append(info_button('duplicates',
num = len(self.duplicates)))
if c.user_is_admin:
buttons += [info_button('details')]
# should we show a traffic tab (promoted and author or sponsor)
if (self.link.promoted is not None and
(c.user_is_sponsor or
(c.user_is_loggedin and c.user._id == self.link.author_id))):
buttons += [info_button('traffic')]
toolbar = [NavMenu(buttons, base_path = "", type="tabmenu")]
if not isinstance(c.site, DefaultSR) and not c.cname:
toolbar.insert(0, PageNameNav('subreddit'))
return toolbar
def content(self):
title_buttons = getattr(self, "subtitle_buttons", [])
return self.content_stack((self.infobar, self.link_listing,
PaneStack([PaneStack((self.nav_menu,
self._content))],
title = self.subtitle,
title_buttons = title_buttons,
css_class = "commentarea")))
def rightbox(self):
rb = Reddit.rightbox(self)
if not (self.link.promoted and not c.user_is_sponsor):
rb.insert(1, LinkInfoBar(a = self.link))
return rb
class LinkCommentSep(Templated):
pass
class CommentPane(Templated):
def cache_key(self):
num = self.article.num_comments
# bit of triage: we don't care about 10% changes in comment
# trees once they get to a certain length. The cache is only a few
# min long anyway.
if num > 1000:
num = (num / 100) * 100
elif num > 100:
num = (num / 10) * 10
return "_".join(map(str, ["commentpane", self.article._fullname,
num, self.sort, self.num, c.lang,
self.can_reply, c.render_style]))
def __init__(self, article, sort, comment, context, num, **kw):
# keys: lang, num, can_reply, render_style
# disable: admin
from r2.models import CommentBuilder, NestedListing
from r2.controllers.reddit_base import UnloggedUser
self.sort = sort
self.num = num
self.article = article
# don't cache on permalinks or contexts, and keep it to html
try_cache = not comment and not context and (c.render_style == "html")
self.can_reply = False
if c.user_is_admin:
try_cache = False
if try_cache and c.user_is_loggedin:
sr = article.subreddit_slow
c.can_reply = self.can_reply = sr.can_comment(c.user)
# don't cache if the current user can ban comments in the listing
try_cache = not sr.can_ban(c.user)
# don't cache for users with custom hide threshholds
try_cache &= (c.user.pref_min_comment_score ==
Account._defaults["pref_min_comment_score"])
def renderer():
builder = CommentBuilder(article, sort, comment, context, **kw)
listing = NestedListing(builder, num = num,
parent_name = article._fullname)
return listing.listing()
# generate the listing we would make for this user if caching is disabled.
my_listing = renderer()
# for now, disable the cache if the user happens to be an author of anything.
if try_cache:
for t in self.listing_iter(my_listing):
if getattr(t, "is_author", False):
try_cache = False
break
if try_cache:
# try to fetch the comment tree from the cache
key = self.cache_key()
self.rendered = g.cache.get(key)
if not self.rendered:
# spoof an unlogged in user
user = c.user
logged_in = c.user_is_loggedin
try:
c.user = UnloggedUser([c.lang])
c.user_is_loggedin = False
# render as if not logged in (but possibly with reply buttons)
self.rendered = renderer().render()
g.cache.set(key, self.rendered, time = 120)
finally:
# undo the spoofing
c.user = user
c.user_is_loggedin = logged_in
# figure out what needs to be updated on the listing
likes = []
dislikes = []
is_friend = set()
for t in self.listing_iter(my_listing):
if not hasattr(t, "likes"):
# this is for MoreComments and MoreRecursion
continue
if getattr(t, "friend", False) and not t.author._deleted:
is_friend.add(t.author._fullname)
if t.likes:
likes.append(t._fullname)
if t.likes is False:
dislikes.append(t._fullname)
self.rendered += ThingUpdater(likes = likes,
dislikes = dislikes,
is_friend = is_friend).render()
g.log.debug("using comment page cache")
else:
self.rendered = my_listing.render()
def listing_iter(self, l):
for t in l:
yield t
for x in self.listing_iter(getattr(t, "child", [])):
yield x
def render(self, *a, **kw):
return self.rendered
class ThingUpdater(Templated):
pass
class LinkInfoBar(Templated):
"""Right box for providing info about a link."""
def __init__(self, a = None):