forked from reddit-archive/reddit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
executable file
·2687 lines (2312 loc) · 104 KB
/
api.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 reddit_base import RedditController, MinimalController, set_user_cookie
from reddit_base import cross_domain, paginated_listing
from pylons.i18n import _
from pylons import c, request, response
from validator import *
from r2.models import *
from r2.lib.utils import get_title, sanitize_url, timeuntil, set_last_modified
from r2.lib.utils import query_string, timefromnow, randstr
from r2.lib.utils import timeago, tup, filter_links
from r2.lib.pages import EnemyList, FriendList, ContributorList, ModList, \
BannedList, BoringPage, FormPage, CssError, UploadedImage, ClickGadget, \
UrlParser, WrappedUser, BoringPage
from r2.lib.pages import FlairList, FlairCsv, FlairTemplateEditor, \
FlairSelector
from r2.lib.utils.trial_utils import indict, end_trial, trial_info
from r2.lib.pages.things import wrap_links, default_thing_wrapper
from r2.lib.menus import CommentSortMenu
from r2.lib.captcha import get_iden
from r2.lib.strings import strings
from r2.lib.filters import _force_unicode, websafe_json, websafe, spaceCompress
from r2.lib.db import queries
from r2.lib.db.queries import changed
from r2.lib import promote
from r2.lib.media import force_thumbnail, thumbnail_url
from r2.lib.comment_tree import delete_comment
from r2.lib import tracking, cssfilter, emailer
from r2.lib.subreddit_search import search_reddits
from r2.lib.log import log_text
from r2.lib.filters import safemarkdown
from r2.lib.scraper import str_to_image
from r2.controllers.api_docs import api_doc, api_section
import csv
from collections import defaultdict
from datetime import datetime, timedelta
from md5 import md5
import urllib
import urllib2
def reject_vote(thing):
voteword = request.params.get('dir')
if voteword == '1':
voteword = 'upvote'
elif voteword == '0':
voteword = '0-vote'
elif voteword == '-1':
voteword = 'downvote'
log_text ("rejected vote", "Rejected %s from %s (%s) on %s %s via %s" %
(voteword, c.user.name, request.ip, thing.__class__.__name__,
thing._id36, request.referer), "info")
class ApiminimalController(MinimalController):
"""
Put API calls in here which don't rely on the user being logged in
"""
@validatedForm()
@api_doc(api_section.misc)
def POST_new_captcha(self, form, jquery, *a, **kw):
iden = get_iden()
jquery("body").captcha(iden)
form._send_data(iden = iden)
class ApiController(RedditController):
"""
Controller which deals with almost all AJAX site interaction.
"""
@validatedForm()
def ajax_login_redirect(self, form, jquery, dest):
form.redirect("/login" + query_string(dict(dest=dest)))
@validate(link1 = VUrl(['url']),
link2 = VByName('id'),
count = VLimit('limit'))
@api_doc(api_section.links_and_comments)
def GET_info(self, link1, link2, count):
"""
Gets a listing of links which have the provided url.
"""
links = []
if link2:
links = filter_links(tup(link2), filter_spam = False)
elif link1 and ('ALREADY_SUB', 'url') in c.errors:
links = filter_links(tup(link1), filter_spam = False)
listing = wrap_links(filter(None, links or []), num = count)
return BoringPage(_("API"), content = listing).render()
@json_validate()
@api_doc(api_section.account, extensions=["json"])
def GET_me(self, responder):
"""
Get info about the currently authenticated user.
Response includes a modhash, karma, and new mail status.
"""
if c.user_is_loggedin:
return Wrapped(c.user).render()
else:
return {}
@validatedForm(VCaptcha(),
name=VRequired('name', errors.NO_NAME),
email=ValidEmails('email', num = 1),
reason = VOneOf('reason', ('ad_inq', 'feedback', "i18n")),
message=VRequired('text', errors.NO_TEXT),
)
def POST_feedback(self, form, jquery, name, email, reason, message):
if not (form.has_errors('name', errors.NO_NAME) or
form.has_errors('email', errors.BAD_EMAILS) or
form.has_errors('text', errors.NO_TEXT) or
form.has_errors('captcha', errors.BAD_CAPTCHA)):
if reason == 'ad_inq':
emailer.ad_inq_email(email, message, name, reply_to = '')
elif reason == 'i18n':
emailer.i18n_email(email, message, name, reply_to = '')
else:
emailer.feedback_email(email, message, name, reply_to = '')
form.set_html(".status", _("thanks for your message! "
"you should hear back from us shortly."))
form.set_inputs(text = "", captcha = "")
form.find(".spacer").hide()
form.find(".btn").hide()
POST_ad_inq = POST_feedback
@validatedForm(VCaptcha(),
VUser(),
VModhash(),
ip = ValidIP(),
to = VMessageRecipient('to'),
subject = VRequired('subject', errors.NO_SUBJECT),
body = VMarkdown(['text', 'message']))
@api_doc(api_section.messages)
def POST_compose(self, form, jquery, to, subject, body, ip):
"""
handles message composition under /message/compose.
"""
if not (form.has_errors("to", errors.USER_DOESNT_EXIST,
errors.NO_USER, errors.SUBREDDIT_NOEXIST,
errors.USER_BLOCKED) or
form.has_errors("subject", errors.NO_SUBJECT) or
form.has_errors("text", errors.NO_TEXT, errors.TOO_LONG) or
form.has_errors("captcha", errors.BAD_CAPTCHA)):
m, inbox_rel = Message._new(c.user, to, subject, body, ip)
form.set_html(".status", _("your message has been delivered"))
form.set_inputs(to = "", subject = "", text = "", captcha="")
queries.new_message(m, inbox_rel)
@validatedForm(VUser(),
VCaptcha(),
VRatelimit(rate_user = True, rate_ip = True,
prefix = "rate_submit_"),
ip = ValidIP(),
sr = VSubmitSR('sr', 'kind'),
url = VUrl(['url', 'sr', 'resubmit']),
title = VTitle('title'),
save = VBoolean('save'),
selftext = VSelfText('text'),
kind = VOneOf('kind', ['link', 'self']),
then = VOneOf('then', ('tb', 'comments'),
default='comments'),
extension = VLength("extension", 20))
@api_doc(api_section.links_and_comments)
def POST_submit(self, form, jquery, url, selftext, kind, title,
save, sr, ip, then, extension):
from r2.models.admintools import is_banned_domain
if isinstance(url, (unicode, str)):
#backwards compatability
if url.lower() == 'self':
url = kind = 'self'
# VUrl may have replaced 'url' by adding 'http://'
form.set_inputs(url = url)
if not kind or form.has_errors('sr', errors.INVALID_OPTION):
# this should only happen if somebody is trying to post
# links in some automated manner outside of the regular
# submission page, and hasn't updated their script
return
if (form.has_errors('sr',
errors.SUBREDDIT_NOEXIST,
errors.SUBREDDIT_NOTALLOWED,
errors.SUBREDDIT_REQUIRED,
errors.NO_SELFS,
errors.NO_LINKS)
or not sr):
# checking to get the error set in the form, but we can't
# check for rate-limiting if there's no subreddit
return
if sr.link_type == 'link' and kind == 'self':
# this could happen if they actually typed "self" into the
# URL box and we helpfully translated it for them
c.errors.add(errors.NO_SELFS, field='sr')
# and trigger that by hand for the form
form.has_errors('sr', errors.NO_SELFS)
return
should_ratelimit = sr.should_ratelimit(c.user, 'link')
#remove the ratelimit error if the user's karma is high
if not should_ratelimit:
c.errors.remove((errors.RATELIMIT, 'ratelimit'))
banmsg = None
if kind == 'link':
check_domain = True
# check for no url, or clear that error field on return
if form.has_errors("url", errors.NO_URL, errors.BAD_URL):
pass
elif form.has_errors("url", errors.ALREADY_SUB):
check_domain = False
u = url[0].already_submitted_link
if extension:
u = UrlParser(u)
u.set_extension(extension)
u = u.unparse()
form.redirect(u)
# check for title, otherwise look it up and return it
elif form.has_errors("title", errors.NO_TEXT):
pass
if url is None:
g.log.warning("%s is trying to submit url=None (title: %r)"
% (request.ip, title))
elif check_domain:
banmsg = is_banned_domain(url, request.ip)
# Uncomment if we want to let spammers know we're on to them
# if banmsg:
# form.set_html(".field-url.BAD_URL", banmsg)
# return
else:
form.has_errors('text', errors.TOO_LONG)
if form.has_errors("title", errors.TOO_LONG, errors.NO_TEXT):
pass
if form.has_errors('ratelimit', errors.RATELIMIT):
pass
if form.has_error() or not title:
return
if should_ratelimit:
filled_quota = c.user.quota_full('link')
if filled_quota is not None:
if c.user._spam:
msg = strings.generic_quota_msg
else:
log_text ("over-quota",
"%s just went over their per-%s quota" %
(c.user.name, filled_quota), "info")
verify_link = "/verify?reason=submit"
reddiquette_link = "/help/reddiquette"
if c.user.email_verified:
msg = strings.verified_quota_msg % dict(reddiquette=reddiquette_link)
else:
msg = strings.unverified_quota_msg % dict(verify=verify_link,
reddiquette=reddiquette_link)
md = safemarkdown(msg)
form.set_html(".status", md)
c.errors.add(errors.QUOTA_FILLED)
form.set_error(errors.QUOTA_FILLED, None)
return
# well, nothing left to do but submit it
l = Link._submit(request.post.title, url if kind == 'link' else 'self',
c.user, sr, ip, spam=c.user._spam)
if banmsg:
admintools.spam(l, banner = "domain (%s)" % banmsg)
if kind == 'self':
l.url = l.make_permalink_slow()
l.is_self = True
l.selftext = selftext
l._commit()
l.set_url_cache()
queries.queue_vote(c.user, l, True, ip,
cheater = (errors.CHEATER, None) in c.errors)
if save:
r = l._save(c.user)
queries.new_savehide(r)
#set the ratelimiter
if should_ratelimit:
c.user.clog_quota('link', l)
VRatelimit.ratelimit(rate_user=True, rate_ip = True,
prefix = "rate_submit_")
#update the queries
queries.new_link(l)
changed(l)
if then == 'comments':
path = add_sr(l.make_permalink_slow())
elif then == 'tb':
form.attr('target', '_top')
path = add_sr('/tb/%s' % l._id36)
if extension:
path += ".%s" % extension
form.redirect(path)
form._send_data(url=path)
form._send_data(id=l._id36)
form._send_data(name=l._fullname)
@validatedForm(VRatelimit(rate_ip = True,
rate_user = True,
prefix = 'fetchtitle_'),
VUser(),
url = VSanitizedUrl(['url']))
def POST_fetch_title(self, form, jquery, url):
if form.has_errors('ratelimit', errors.RATELIMIT):
form.set_html(".title-status", "");
return
VRatelimit.ratelimit(rate_ip = True, rate_user = True,
prefix = 'fetchtitle_', seconds=1)
if url:
title = get_title(url)
if title:
form.set_inputs(title = title)
form.set_html(".title-status", "");
else:
form.set_html(".title-status", _("no title found"))
def _login(self, responder, user, rem = None):
"""
AJAX login handler, used by both login and register to set the
user cookie and send back a redirect.
"""
self.login(user, rem = rem)
if request.params.get("hoist") != "cookie":
responder._send_data(modhash = user.modhash())
responder._send_data(cookie = user.make_cookie())
@cross_domain(allow_credentials=True)
@api_doc(api_section.account)
def POST_login(self, *args, **kwargs):
return self._handle_login(*args, **kwargs)
@cross_domain(allow_credentials=True)
@api_doc(api_section.account)
def POST_register(self, *args, **kwargs):
return self._handle_register(*args, **kwargs)
@validatedForm(user = VThrottledLogin(['user', 'passwd']),
rem = VBoolean('rem'))
def _handle_login(self, form, responder, user, rem):
if not (responder.has_errors("vdelay", errors.RATELIMIT) or
responder.has_errors("passwd", errors.WRONG_PASSWORD)):
self._login(responder, user, rem)
@validatedForm(VCaptcha(),
VRatelimit(rate_ip = True, prefix = "rate_register_"),
name = VUname(['user']),
email = ValidEmails("email", num = 1),
password = VPassword(['passwd', 'passwd2']),
rem = VBoolean('rem'))
def _handle_register(self, form, responder, name, email,
password, rem):
bad_captcha = responder.has_errors('captcha', errors.BAD_CAPTCHA)
if not (responder.has_errors("user", errors.BAD_USERNAME,
errors.USERNAME_TAKEN_DEL,
errors.USERNAME_TAKEN) or
responder.has_errors("email", errors.BAD_EMAILS) or
responder.has_errors("passwd", errors.BAD_PASSWORD) or
responder.has_errors("passwd2", errors.BAD_PASSWORD_MATCH) or
responder.has_errors('ratelimit', errors.RATELIMIT) or
(not g.disable_captcha and bad_captcha)):
user = register(name, password)
VRatelimit.ratelimit(rate_ip = True, prefix = "rate_register_")
#anything else we know (email, languages)?
if email:
user.email = email
user.registration_ip = request.ip
user.pref_lang = c.lang
if c.content_langs == 'all':
user.pref_content_langs = 'all'
else:
langs = list(c.content_langs)
langs.sort()
user.pref_content_langs = tuple(langs)
d = c.user._dirties.copy()
user._commit()
c.user = user
self._login(responder, user, rem)
@noresponse(VUser(),
VModhash(),
container = VByName('id'))
@api_doc(api_section.moderation)
def POST_leavemoderator(self, container):
"""
Handles self-removal as moderator from a subreddit as rendered
in the subreddit sidebox on any of that subreddit's pages.
"""
if container and container.is_moderator(c.user):
container.remove_moderator(c.user)
Subreddit.special_reddits(c.user, "moderator", _update=True)
ModAction.create(container, c.user, 'removemoderator', target=c.user,
details='remove_self')
@noresponse(VUser(),
VModhash(),
container = VByName('id'))
@api_doc(api_section.moderation)
def POST_leavecontributor(self, container):
"""
same comment as for POST_leave_moderator.
"""
if container and container.is_contributor(c.user):
container.remove_contributor(c.user)
Subreddit.special_reddits(c.user, "contributor", _update=True)
@noresponse(VUser(),
VModhash(),
nuser = VExistingUname('name'),
iuser = VByName('id'),
container = nop('container'),
type = VOneOf('type', ('friend', 'enemy', 'moderator',
'contributor', 'banned')))
@api_doc(api_section.users)
def POST_unfriend(self, nuser, iuser, container, type):
"""
Handles removal of a friend (a user-user relation) or removal
of a user's privileges from a subreddit (a user-subreddit
relation). The user can either be passed in by name (nuser)
or by fullname (iuser). If type is friend or enemy, 'container'
will be the current user, otherwise the subreddit must be set.
"""
sr_types = ('moderator', 'contributor', 'banned')
if type in sr_types:
container = c.site
else:
container = VByName('container').run(container)
if not container:
return
# The user who made the request must be an admin or a moderator
# for the privilege change to succeed.
victim = iuser or nuser
if (not c.user_is_admin
and (type in sr_types and not container.is_moderator(c.user))):
abort(403, 'forbidden')
if (type == 'moderator' and not
(c.user_is_admin or container.can_demod(c.user, victim))):
abort(403, 'forbidden')
# if we are (strictly) unfriending, the container had better
# be the current user.
if type in ("friend", "enemy") and container != c.user:
abort(403, 'forbidden')
fn = getattr(container, 'remove_' + type)
new = fn(victim)
# Log this action
if new and type in sr_types:
action = dict(banned='unbanuser', moderator='removemoderator',
contributor='removecontributor').get(type, None)
ModAction.create(container, c.user, action, target=victim)
if type == "friend" and c.user.gold:
c.user.friend_rels_cache(_update=True)
if type in ("moderator", "contributor"):
Subreddit.special_reddits(victim, type, _update=True)
@validatedForm(VUser(),
VModhash(),
ip = ValidIP(),
friend = VExistingUname('name'),
container = nop('container'),
type = VOneOf('type', ('friend', 'moderator',
'contributor', 'banned')),
note = VLength('note', 300))
@api_doc(api_section.users)
def POST_friend(self, form, jquery, ip, friend,
container, type, note):
"""
Complement to POST_unfriend: handles friending as well as
privilege changes on subreddits.
"""
sr_types = ('moderator', 'contributor', 'banned')
if type in sr_types:
container = c.site
else:
container = VByName('container').run(container)
if not container:
return
fn = getattr(container, 'add_' + type)
# The user who made the request must be an admin or a moderator
# for the privilege change to succeed.
if (not c.user_is_admin
and (type in sr_types and not container.is_moderator(c.user))):
abort(403,'forbidden')
# if we are (strictly) friending, the container
# had better be the current user.
if type == "friend" and container != c.user:
abort(403,'forbidden')
elif form.has_errors("name", errors.USER_DOESNT_EXIST, errors.NO_USER):
return
new = fn(friend)
# Log this action
if new and type in sr_types:
action = dict(banned='banuser', moderator='addmoderator',
contributor='addcontributor').get(type, None)
ModAction.create(container, c.user, action, target=friend)
if type == "friend" and c.user.gold:
# Yes, the order of the next two lines is correct.
# First you recalculate the rel_ids, then you find
# the right one and update its data.
c.user.friend_rels_cache(_update=True)
c.user.add_friend_note(friend, note or '')
if type in ("moderator", "contributor"):
Subreddit.special_reddits(friend, type, _update=True)
cls = dict(friend=FriendList,
moderator=ModList,
contributor=ContributorList,
banned=BannedList).get(type)
form.set_inputs(name = "")
form.set_html(".status:first", _("added"))
if new and cls:
user_row = cls().user_row(friend)
jquery("#" + type + "-table").show(
).find("table").insert_table_rows(user_row)
if type != 'friend' and (type != 'banned' or
friend.has_interacted_with(container)):
msg = strings.msg_add_friend.get(type)
subj = strings.subj_add_friend.get(type)
if msg and subj and friend.name != c.user.name:
# fullpath with domain needed or the markdown link
# will break
if isinstance(container, Subreddit):
title = "%s: %s" % (container.path.rstrip("/"),
container.title)
else:
title = container.title
d = dict(url = container.path,
title = title)
msg = msg % d
subj = subj % d
if type == 'banned':
from_sr = True
sr = container
else:
from_sr = False
sr = None
item, inbox_rel = Message._new(c.user, friend, subj, msg,
ip, from_sr=from_sr, sr=sr)
queries.new_message(item, inbox_rel)
@validatedForm(VGold(),
friend = VExistingUname('name'),
note = VLength('note', 300))
def POST_friendnote(self, form, jquery, friend, note):
c.user.add_friend_note(friend, note)
form.set_html('.status', _("saved"))
@validatedForm(VUser('curpass', default=''),
VModhash(),
password = VPassword(['curpass', 'curpass']),
dest = VDestination())
@api_doc(api_section.account)
def POST_clear_sessions(self, form, jquery, password, dest):
"""
Clear all session cookies and update the current one.
A valid password (`curpass`) must be supplied.
"""
# password is required to proceed
if form.has_errors("curpass", errors.WRONG_PASSWORD):
return
form.set_html('.status',
_('all other sessions have been logged out'))
form.set_inputs(curpass = "")
# run the change password command to get a new salt
change_password(c.user, password)
# the password salt has changed, so the user's cookie has been
# invalidated. drop a new cookie.
self.login(c.user)
@validatedForm(VUser('curpass', default = ''),
VModhash(),
email = ValidEmails("email", num = 1),
password = VPassword(['newpass', 'verpass']),
verify = VBoolean("verify"))
@api_doc(api_section.account)
def POST_update(self, form, jquery, email, password, verify):
"""
Update account email address and password.
Called by /prefs/update on the site. For frontend form verification
purposes, `newpass` and `verpass` must be equal for a password change
to succeed.
"""
# password is required to proceed
if form.has_errors("curpass", errors.WRONG_PASSWORD):
return
# check if the email is valid. If one is given and it is
# different from the current address (or there is not one
# currently) apply it
updated = False
if (not form.has_errors("email", errors.BAD_EMAILS) and
email):
if (not hasattr(c.user,'email') or c.user.email != email):
c.user.email = email
# unverified email for now
c.user.email_verified = None
c.user._commit()
Award.take_away("verified_email", c.user)
updated = True
if verify:
# TODO: rate limit this?
emailer.verify_email(c.user, request.referer)
form.set_html('.status',
_("you should be getting a verification email shortly."))
else:
form.set_html('.status', _('your email has been updated'))
# user is removing their email
if (not email and c.user.email and
form.has_errors("email", errors.NO_EMAILS)):
c.user.email = ''
c.user.email_verified = None
c.user._commit()
Award.take_away("verified_email", c.user)
updated = True
form.set_html('.status', _('your email has been updated'))
# change password
if (password and
not (form.has_errors("newpass", errors.BAD_PASSWORD) or
form.has_errors("verpass", errors.BAD_PASSWORD_MATCH))):
change_password(c.user, password)
if updated:
form.set_html(".status",
_('your email and password have been updated'))
else:
form.set_html('.status',
_('your password has been updated'))
form.set_inputs(curpass = "", newpass = "", verpass = "")
# the password has changed, so the user's cookie has been
# invalidated. drop a new cookie.
self.login(c.user)
@validatedForm(VUser(),
VModhash(),
delete_message = VLength("delete_message", max_length=500),
username = VRequired("user", errors.NOT_USER),
user = VThrottledLogin(["user", "passwd"]),
confirm = VBoolean("confirm"))
@api_doc(api_section.account)
def POST_delete_user(self, form, jquery, delete_message, username, user, confirm):
"""
Delete an account.
A valid username/password and confirmation must be supplied. An
optional `delete_message` may be supplied to explain the reason the
account is to be deleted.
Called by /prefs/delete on the site.
"""
if username and username.lower() != c.user.name.lower():
c.errors.add(errors.NOT_USER, field="user")
if not confirm:
c.errors.add(errors.CONFIRM, field="confirm")
if not (form.has_errors('vdelay', errors.RATELIMIT) or
form.has_errors("user", errors.NOT_USER) or
form.has_errors("passwd", errors.WRONG_PASSWORD) or
form.has_errors("delete_message", errors.TOO_LONG) or
form.has_errors("confirm", errors.CONFIRM)):
c.user.delete(delete_message)
form.redirect("/?deleted=true")
@noresponse(VUser(),
VModhash(),
thing = VByNameIfAuthor('id'))
@api_doc(api_section.links_and_comments)
def POST_del(self, thing):
if not thing: return
'''for deleting all sorts of things'''
was_deleted = thing._deleted
thing._deleted = True
if (getattr(thing, "promoted", None) is not None and
not promote.is_promoted(thing)):
promote.reject_promotion(thing)
thing._commit()
# flag search indexer that something has changed
changed(thing)
#expire the item from the sr cache
if isinstance(thing, Link):
sr = thing.subreddit_slow
queries.delete_links(thing)
#comments have special delete tasks
elif isinstance(thing, Comment):
parent_id = getattr(thing, 'parent_id', None)
link_id = thing.link_id
recipient = None
if parent_id:
parent_comment = Comment._byID(parent_id, data=True)
recipient = Account._byID(parent_comment.author_id)
else:
parent_link = Link._byID(link_id, data=True)
if parent_link.is_self:
recipient = Account._byID(parent_link.author_id)
if not was_deleted:
delete_comment(thing)
if recipient:
inbox_class = Inbox.rel(Account, Comment)
d = inbox_class._fast_query(recipient, thing, ("inbox", "selfreply"))
rels = filter(None, d.values()) or None
queries.new_comment(thing, rels)
queries.delete_comments(thing)
@noresponse(VUser(),
VModhash(),
VSrCanAlter('id'),
thing = VByName('id'))
@api_doc(api_section.links_and_comments)
def POST_marknsfw(self, thing):
thing.over_18 = True
thing._commit()
if c.user._id != thing.author_id:
ModAction.create(thing.subreddit_slow, c.user, target=thing,
action='marknsfw')
# flag search indexer that something has changed
changed(thing)
@noresponse(VUser(),
VModhash(),
VSrCanAlter('id'),
thing = VByName('id'))
@api_doc(api_section.links_and_comments)
def POST_unmarknsfw(self, thing):
thing.over_18 = False
thing._commit()
if c.user._id != thing.author_id:
ModAction.create(thing.subreddit_slow, c.user, target=thing,
action='marknsfw', details='remove')
# flag search indexer that something has changed
changed(thing)
@noresponse(VUser(), VModhash(),
thing = VByName('id'))
@api_doc(api_section.links_and_comments)
def POST_report(self, thing):
'''for reporting...'''
if not thing or thing._deleted:
return
elif getattr(thing, 'promoted', False):
return
# if it is a message that is being reported, ban it.
# every user is admin over their own personal inbox
if isinstance(thing, Message):
admintools.spam(thing, False, True, c.user.name)
# auto-hide links that are reported
elif isinstance(thing, Link):
r = thing._hide(c.user)
queries.new_savehide(r)
# TODO: be nice to be able to remove comments that are reported
# from a user's inbox so they don't have to look at them.
elif isinstance(thing, Comment):
pass
if c.user._spam or c.user.ignorereports:
return
Report.new(c.user, thing)
@noresponse(VUser(), VModhash(),
thing=VByName('id'))
@api_doc(api_section.messages)
def POST_block(self, thing):
'''for blocking via inbox'''
if not thing:
return
# Users may only block someone who has
# actively harassed them (i.e., comment/link reply
# or PM). Check that 'thing' would have showed up in the
# user's inbox at some point
if isinstance(thing, Message):
if thing.to_id != c.user._id:
return
elif isinstance(thing, Comment):
parent_id = getattr(thing, 'parent_id', None)
link_id = thing.link_id
if parent_id:
parent_comment = Comment._byID(parent_id)
parent_author_id = parent_comment.author_id
else:
parent_link = Link._byID(link_id)
parent_author_id = parent_link.author_id
if parent_author_id != c.user._id:
return
block_acct = Account._byID(thing.author_id)
if block_acct.name in g.admins:
return
c.user.add_enemy(block_acct)
@noresponse(VAdmin(), VModhash(),
thing = VByName('id'))
def POST_indict(self, thing):
'''put something on trial'''
if not thing:
log_text("indict: no thing", level="warning")
indict(thing)
@validatedForm(VUser(),
VModhash(),
item = VByNameIfAuthor('thing_id'),
text = VSelfText('text'))
@api_doc(api_section.links_and_comments)
def POST_editusertext(self, form, jquery, item, text):
if (not form.has_errors("text",
errors.NO_TEXT, errors.TOO_LONG) and
not form.has_errors("thing_id", errors.NOT_AUTHOR)):
if isinstance(item, Comment):
kind = 'comment'
item.body = text
elif isinstance(item, Link):
kind = 'link'
if not getattr(item, "is_self", False):
return abort(403, "forbidden")
item.selftext = text
else:
g.log.warning("%s tried to edit usertext on %r", c.user, item)
return
if item._deleted:
return abort(403, "forbidden")
if (item._date < timeago('3 minutes')
or (item._ups + item._downs > 2)):
item.editted = c.start_time
item._commit()
changed(item)
if kind == 'link':
set_last_modified(item, 'comments')
wrapper = default_thing_wrapper(expand_children = True)
jquery(".content").replace_things(item, True, True, wrap = wrapper)
jquery(".content .link .rank").hide()
@validatedForm(VUser(),
VModhash(),
VRatelimit(rate_user = True, rate_ip = True,
prefix = "rate_comment_"),
ip = ValidIP(),
parent = VSubmitParent(['thing_id', 'parent']),
comment = VMarkdown(['text', 'comment']))
@api_doc(api_section.links_and_comments)
def POST_comment(self, commentform, jquery, parent, comment, ip):
should_ratelimit = True
#check the parent type here cause we need that for the
#ratelimit checks
if isinstance(parent, Message):
if not getattr(parent, "repliable", True):
abort(403, 'forbidden')
is_message = True
should_ratelimit = False
else:
is_message = False
is_comment = True
if isinstance(parent, Link):
link = parent
parent_comment = None
else:
link = Link._byID(parent.link_id, data = True)
parent_comment = parent
sr = parent.subreddit_slow
if ((link.is_self and link.author_id == c.user._id)
or not sr.should_ratelimit(c.user, 'comment')):
should_ratelimit = False
parent_age = c.start_time - parent._date
if parent_age.days > g.REPLY_AGE_LIMIT:
c.errors.add(errors.TOO_OLD, field = "parent")
#remove the ratelimit error if the user's karma is high
if not should_ratelimit:
c.errors.remove((errors.RATELIMIT, 'ratelimit'))
if (not commentform.has_errors("text",
errors.NO_TEXT,
errors.TOO_LONG) and
not commentform.has_errors("ratelimit",
errors.RATELIMIT) and
not commentform.has_errors("parent",
errors.DELETED_COMMENT,
errors.DELETED_LINK,
errors.TOO_OLD,
errors.USER_BLOCKED)):
if is_message:
if parent.from_sr:
to = Subreddit._byID(parent.sr_id)
else:
to = Account._byID(parent.author_id)
subject = parent.subject
re = "re: "
if not subject.startswith(re):
subject = re + subject
item, inbox_rel = Message._new(c.user, to, subject,
comment, ip, parent = parent)
item.parent_id = parent._id
else:
item, inbox_rel = Comment._new(c.user, link, parent_comment,
comment, ip)
queries.queue_vote(c.user, item, True, ip,
cheater = (errors.CHEATER, None) in c.errors)
# adding to comments-tree is done as part of
# newcomments_q, so if they refresh immediately they
# won't see their comment