-
Notifications
You must be signed in to change notification settings - Fork 7
/
board.py
1614 lines (1305 loc) · 58.4 KB
/
board.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
import os
import re
import time
import sys
import hashlib
import mimetypes
from subprocess import Popen, PIPE
import misc
import str_format
import util
import model
import staff
import staff_interface
# NOTE: I'm not sure if interboard is a good module to have here.
import interboard
import config
import strings as strings
from util import WakaError, local
from template import Template
from wakapost import WakaPost
try:
import board_config_defaults
except ImportError:
board_config_defaults = None
from sqlalchemy.sql import case, or_, and_, select, func, null
class Board(object):
def __init__(self, board):
# Correct for missing key when running under WSGI
if 'DOCUMENT_ROOT' not in local.environ:
local.environ['DOCUMENT_ROOT'] = os.getcwd()
# For WSGI mode (which does not initialize this for whatever reason).
board_path = os.path.abspath(os.path.join(\
local.environ['DOCUMENT_ROOT'],
config.BOARD_DIR,
board))
if not os.path.exists(board_path):
raise BoardNotFound()
if not os.path.exists(os.path.join(board_path, 'board_config.py')):
raise BoardNotFound('Board configuration not found.')
module = util.import2('board_config', board_path)
if board_config_defaults:
self.options = board_config_defaults.config.copy()
self.options.update(module.config)
else:
self.options = module.config
self.table = model.board(self.options['SQL_TABLE'])
# TODO likely will still need customization
self.path = board_path
url_path = os.path.join('/', os.path.relpath(\
board_path,
local.environ['DOCUMENT_ROOT']), '')
self.url = str_format.percent_encode(url_path)
self.name = board
def make_path(self, file='', dir='', dirc=None, page=None, thread=None,
ext=config.PAGE_EXT, abbr=False, hash=None, url=False,
force_http=False):
'''Builds an url or a path'''
if url:
base = self.url
if force_http:
base = 'http://' + local.environ['SERVER_NAME'] + base
else:
base = self.path
if page is not None:
if page == 0:
file = self.options['HTML_SELF']
ext = None
else:
file = str(page)
if dirc:
dir = self.options[dirc]
if thread is not None:
dir = self.options['RES_DIR']
file = str(thread)
if hash is not None:
hash = '#%s' % hash
else:
hash = ''
if file:
if abbr:
file += '_abbr'
if ext is not None:
file += '.' + ext.lstrip(".")
return os.path.join(base, dir, file) + hash
else:
return os.path.join(base, dir) + hash
def check_access(self, user):
user.check_access(self.name)
return user
def make_url(self, **kwargs):
'''Alias for make_path to build urls'''
kwargs['url'] = True
return self.make_path(**kwargs)
def _get_all_threads(self):
'''Build a list of threads from the database,
where each thread is a list of WakaPost instances'''
session = model.Session()
table = self.table
sql = table.select().order_by(table.c.stickied.desc(),
table.c.lasthit.desc(),
case({0: table.c.num}, table.c.parent, table.c.parent).asc(),
table.c.num.asc()
)
query = session.execute(sql)
threads = []
thread = []
for post in query:
if thread and not post.parent:
threads.append(thread)
thread = []
thread.append(WakaPost(post))
threads.append(thread)
return threads
def get_some_threads(self, page):
'''Grab a partial list of threads for pre-emptive pagination.'''
session = model.Session()
table = self.table
thread_dict = {}
thread_nums = []
per_page = self.options['IMAGES_PER_PAGE']
# Page is zero-indexed, so offset formula must differ.
offset = page * per_page
# Query 1: Grab all thread (OP) entries.
op_sql = table.select().where(table.c.parent == 0).order_by(
table.c.stickied.desc(),
table.c.lasthit.desc(),
table.c.num.asc()
).limit(per_page).offset(offset)
op_query = session.execute(op_sql)
for op in op_query:
thread_dict[op.num] = [WakaPost(op)]
thread_nums.append(op.num)
# Query 2: Grab all reply entries and process.
reply_sql = table.select().where(table.c.parent.in_(thread_nums))\
.order_by(table.c.stickied.desc(),
table.c.num.asc()
)
reply_query = session.execute(reply_sql)
for post in reply_query:
thread_dict[post.parent].append(WakaPost(post))
return [thread_dict[num] for num in thread_nums]
def build_cache(self):
threads = self._get_all_threads()
per_page = self.options['IMAGES_PER_PAGE']
total = get_page_count(threads, per_page)
for page in xrange(total):
pagethreads = threads[page * per_page:\
min(len(threads), (page + 1) * per_page)]
self.build_cache_page(page, total, pagethreads)
# check for and remove old pages
page = total
while os.path.exists(self.make_path(page=page)):
os.unlink(self.make_path(page=page))
page += 1
if config.ENABLE_RSS:
self.update_rss()
def rebuild_cache(self):
self.build_thread_cache_all()
self.build_cache()
def rebuild_cache_proxy(self, task_data):
task_data.user.check_access(self.name)
task_data.contents.append(self.name)
Popen([sys.executable, sys.argv[0], 'rebuild_cache', self.name],
env=util.proxy_environ())
return util.make_http_forward(
misc.make_script_url(task='mpanel', board=self.name),
config.ALTERNATE_REDIRECT)
def parse_page_threads(self, pagethreads):
threads = []
for postlist in pagethreads:
if len(postlist) == 0:
continue
elif len(postlist) > 1:
parent, replies = postlist[0], postlist[1:]
else:
parent, replies = postlist[0], []
images = [x for x in replies if x.filename]
if parent.stickied:
max_replies = config.REPLIES_PER_STICKY
else:
max_replies = self.options['REPLIES_PER_THREAD']
max_images = self.options['IMAGE_REPLIES_PER_THREAD'] \
or len(images)
thread = {}
thread['omit'] = 0
thread['omitimages'] = 0
while len(replies) > max_replies or len(images) > max_images:
post = replies.pop(0)
thread['omit'] += 1
if post.filename:
thread['omitimages'] += 1
thread['posts'] = [parent] + replies
for post in thread['posts']:
abbreviation = abbreviate_html(post.comment,
self.options['MAX_LINES_SHOWN'],
self.options['APPROX_LINE_LENGTH'])
if abbreviation:
post.abbrev = 1
post.comment = abbreviation
threads.append(thread)
return threads
def get_board_page_data(self, page, total, admin_page=''):
if page >= total:
if total:
page = total - 1
else:
page = 0
pages = []
for i in xrange(total):
p = {}
p['page'] = i
if admin_page:
# Admin mode: direct to staff interface, not board pages.
p['filename'] = misc.make_script_url(task=admin_page,
board=self.name, page=i, _amp=True)
else:
p['filename'] = self.make_url(page=i)
p['current'] = page == i
pages.append(p)
prevpage = nextpage = 'none'
key_select = 'page' if admin_page else 'filename'
if page != 0:
prevpage = pages[page - 1][key_select]
if page != total - 1 and total:
nextpage = pages[page + 1][key_select]
return (pages, prevpage, nextpage)
def build_cache_page(self, page, total, pagethreads):
'''Build $rootpath/$board/$page.html'''
# Receive contents.
threads = self.parse_page_threads(pagethreads)
# Calculate page link data.
(pages, prevpage, nextpage) = self.get_board_page_data(page, total)
# Generate filename and links to other pages.
filename = self.make_path(page=page)
Template('page_template',
pages=pages,
postform=self.options['ALLOW_TEXTONLY'] \
or self.options['ALLOW_IMAGES'],
image_inp=self.options['ALLOW_IMAGES'],
textonly_inp=(self.options['ALLOW_IMAGES'] \
and self.options['ALLOW_TEXTONLY']),
prevpage=prevpage,
nextpage=nextpage,
threads=threads,
).render_to_file(filename)
def get_thread_posts(self, threadid):
session = model.Session()
sql = self.table.select(
or_(
self.table.c.num == threadid,
self.table.c.parent == threadid
)).order_by(self.table.c.num.asc())
query = session.execute(sql)
thread = []
for post in query:
thread.append(WakaPost(post))
if not len(thread):
raise WakaError('Thread not found.')
if thread[0].parent:
raise WakaError(strings.NOTHREADERR)
return thread
def build_thread_cache(self, threadid):
'''Build $rootpath/$board/$res/$threadid.html'''
thread = self.get_thread_posts(threadid)
filename = os.path.join(self.path, self.options['RES_DIR'],
"%s%s" % (threadid, config.PAGE_EXT))
def print_thread(thread, filename, **kwargs):
'''Function to avoid duplicating code with abbreviated pages'''
Template('page_template',
threads=[{'posts': thread}],
thread=threadid,
postform=self.options['ALLOW_TEXT_REPLIES'] \
or self.options['ALLOW_IMAGE_REPLIES'],
image_inp=self.options['ALLOW_IMAGE_REPLIES'],
textonly_inp=0,
dummy=thread[-1].num,
lockedthread=thread[0].locked,
**kwargs
).render_to_file(filename)
print_thread(thread, filename)
# Determine how many posts need to be cut.
posts_to_trim = len(thread) - config.POSTS_IN_ABBREVIATED_THREAD_PAGES
# Filename for Last xx Posts Page.
abbreviated_filename = os.path.join(self.path,
self.options['RES_DIR'],
"%s_abbr%s" % (threadid, config.PAGE_EXT))
if config.ENABLE_ABBREVIATED_THREAD_PAGES and posts_to_trim > 1:
op = thread[0]
thread = thread[posts_to_trim:]
thread.insert(0, op)
if len(thread) > 1:
min_res = thread[1].num
else:
min_res = op.num
print_thread(thread, abbreviated_filename,
omit=posts_to_trim - 1, min_res=min_res)
else:
if os.path.exists(abbreviated_filename):
os.unlink(abbreviated_filename)
def delete_thread_cache(self, parent, archiving):
archive_dir = self.options['ARCHIVE_DIR']
base = os.path.join(self.path, self.options['RES_DIR'], '')
full_filename = "%s%s" % (parent, config.PAGE_EXT)
full_thread_page = base + full_filename
abbrev_thread_page = base + "%s_abbr%s" % (parent, config.PAGE_EXT)
if archiving:
archive_base = os.path.join(self.path,
self.options['ARCHIVE_DIR'],
self.options['RES_DIR'], '')
try:
os.makedirs(archive_base, 0755)
except os.error:
pass
archive_thread_page = archive_base + full_filename
with open(full_thread_page, 'r') as res_in:
with open(archive_thread_page, 'w') as res_out:
for line in res_in:
# Update thumbnail links.
line = re.sub(r'img src="(.*?)'
+ self.options['THUMB_DIR'],
r'img src="\1'
+ os.path.join(archive_dir,
self.options['THUMB_DIR'], ''),
line)
# Update image links.
line = re.sub(r'a href="(.*?)'
+ self.options['IMG_DIR'],
r'a href="\1'
+ os.path.join(archive_dir,
self.options['IMG_DIR'], ''),
line)
# Update reply links.
line = re.sub(r'a href="(.*?)'
+ os.path.join(self.path,
self.options['RES_DIR'], ''),
r'a href="\1' + os.path.join(\
self.path,
self.options['RES_DIR'], ''),
line)
res_out.write(line)
if os.path.exists(full_thread_page):
os.unlink(full_thread_page)
if os.path.exists(abbrev_thread_page):
os.unlink(abbrev_thread_page)
def build_thread_cache_all(self):
session = model.Session()
sql = select([self.table.c.num], self.table.c.parent == 0)
query = session.execute(sql)
for row in query:
self.build_thread_cache(row[0])
def _handle_post(self, wakapost, editing=None, admin_data=None):
"""Worst function ever"""
session = model.Session()
# get a timestamp for future use
timestamp = time.time()
if admin_data:
admin_data.user.check_access(self.name)
wakapost.admin_post = True
# run several post validations - raises exceptions
wakapost.validate(editing, admin_data, self.options)
# check whether the parent thread is stickied
if wakapost.parent:
self.sticky_lock_check(wakapost, admin_data)
self.sticky_lock_update(wakapost.parent, wakapost.stickied,
wakapost.locked)
ip = local.environ['REMOTE_ADDR']
numip = misc.dot_to_dec(ip)
wakapost.set_ip(numip, editing)
# set up cookies
wakapost.make_post_cookies(self.options, self.url)
# check if IP is whitelisted
whitelisted = misc.is_whitelisted(numip)
if not whitelisted and not admin_data:
# check for bans
interboard.ban_check(numip, wakapost.name,
wakapost.subject, wakapost.comment)
# check for spam matches
trap_fields = []
if self.options['SPAM_TRAP']:
trap_fields = ['name', 'link']
misc.spam_engine(trap_fields, config.SPAM_FILES)
# check for open proxies
if self.options['ENABLE_PROXY_CHECK']:
self.proxy_check(ip)
# check if thread exists, and get lasthit value
parent_res = None
if not editing:
wakapost.timestamp = timestamp
if wakapost.parent:
parent_res = self.get_parent_post(wakapost.parent)
if not parent_res:
raise WakaError(strings.NOTHREADERR)
wakapost.lasthit = parent_res.lasthit
else:
wakapost.lasthit = timestamp
# split tripcode and name
wakapost.set_tripcode(self.options['TRIPKEY'])
# clean fields
wakapost.clean_fields(editing, admin_data, self.options)
# flood protection - must happen after inputs have been cleaned up
self.flood_check(numip, timestamp, wakapost.comment,
wakapost.req_file, editing is None, False)
# generate date
wakapost.set_date(editing, self.options['DATE_STYLE'])
# generate ID code if enabled
if self.options['DISPLAY_ID']:
wakapost.date += ' ID:' + \
self.make_id_code(ip, timestamp, wakapost.email)
# copy file, do checksums, make thumbnail, etc
if wakapost.req_file:
if editing and (editing.filename or editing.thumbnail):
self.delete_file(editing.filename, editing.thumbnail)
# TODO: this process_file is just a thin wrapper around awful code
wakapost.process_file(self, editing is not None)
# choose whether we need an SQL UPDATE (editing) or INSERT (posting)
if editing:
db_update = self.table.update().where(
self.table.c.num == wakapost.num)
else:
db_update = self.table.insert()
db_update = db_update.values(**wakapost.db_values)
# finally, write to the database
result = session.execute(db_update)
if not editing:
if wakapost.parent:
self.update_bump(wakapost, parent_res)
wakapost.num = result.inserted_primary_key[0]
# remove old threads from the database
self.trim_database()
# update the cached HTML pages
self.build_cache()
# update the individual thread cache
self.build_thread_cache(wakapost.parent or wakapost.num)
return wakapost.num
def post_stuff(self, wakapost, admin_data=None):
# For use with noko, below.
parent = wakapost.parent or wakapost.num
noko = wakapost.noko
try:
post_num = self._handle_post(wakapost, admin_data=admin_data)
except util.SpamError:
forward = self.make_path(page=0, url=True)
return util.make_http_forward(forward, config.ALTERNATE_REDIRECT)
forward = ''
if not admin_data:
if not noko:
# forward back to the main page
forward = self.make_path(page=0, url=True)
else:
# ...unless we have "noko" (a la 4chan)--then forward to
# thread ("parent" contains current post number if a new
# thread was posted)
if not os.path.exists(self.make_path(thread=parent,
abbr=True)):
forward = self.make_url(thread=parent)
else:
forward = self.make_url(thread=parent, abbr=True)
else:
# forward back to the mod panel
kwargs = dict(task='mpanel', board=self.name)
if noko:
kwargs['page'] = "t%s" % parent
forward = misc.make_script_url(**kwargs)
admin_data.contents.append('/%s/%d' % (self.name, post_num))
return util.make_http_forward(forward, config.ALTERNATE_REDIRECT)
# end of this function. fuck yeah
def edit_gateway_window(self, post_num):
return self._gateway_window(post_num, 'edit')
def delete_gateway_window(self, post_num):
return self._gateway_window(post_num, 'delete')
def _gateway_window(self, post_num, task):
if not post_num.isdigit():
raise WakaError('Please enter post number.')
wakapost = self.get_post(post_num)
if not wakapost:
raise WakaError(strings.POSTNOTFOUND)
template_name = 'password' if task == 'edit' else 'delpassword'
return Template(template_name, admin_post=wakapost.admin_post, num=post_num)
def get_local_reports(self):
session = model.Session()
table = model.report
sql = table.select().where(and_(table.c.board == self.name,
table.c.resolved == 0))
query = session.execute(sql).fetchall()
reported_posts = [dict(row.items()) for row in query]
rowtype = 1
for row in reported_posts:
# Alternate between rowtypes 1 and 2.
rowtype ^= 0x3
row['rowtype'] = rowtype
return reported_posts
def delete_by_ip(self, task_data, ip, mask='255.255.255.255'):
if task_data and not task_data.contents:
task_data.contents.append(ip + ' (' + mask + ')' + ' @ ' \
+ self.name)
try:
ip = int(ip)
except ValueError:
ip = misc.dot_to_dec(ip)
try:
mask = int(mask)
except ValueError:
mask = misc.dot_to_dec(mask or '255.255.255.255')
session = model.Session()
table = self.table
sql = table.select().where(and_(
table.c.ip.op('&')(mask) == ip & mask,
table.c.timestamp > (time.time() - config.NUKE_TIME_THRESHOLD)
))
rows = session.execute(sql)
if not rows.rowcount:
return
timestamp = None
if config.POST_BACKUP:
timestamp = time.time()
for row in rows:
try:
self.delete_post(row.num, '', False, False, admin=True,
timestampofarchival=timestamp)
except WakaError:
pass
self.build_cache()
def delete_stuff(self, posts, password, file_only, archiving,
caller='user', admindelete=False,
admin_data=None, from_window=False):
if caller == 'internal':
# Internally called; force admin.
admindelete = True
timestamp = None
if config.POST_BACKUP:
timestamp = time.time()
for post in posts:
self.delete_post(post, password, file_only, archiving,
from_window=False, admin=admindelete,
timestampofarchival=timestamp,
admin_data=admin_data)
self.build_cache()
if admindelete:
forward = misc.make_script_url(task='mpanel', board=self.name)
else:
forward = self.make_path(page=0, url=True)
if caller == 'user':
return util.make_http_forward(forward, config.ALTERNATE_REDIRECT)
def delete_post(self, post, password, file_only, archiving,
admin_data=None, from_window=False, admin=False,
timestampofarchival=None, recur=False):
'''Delete a single post from the board. This method does not rebuild
index cache automatically.'''
session = model.Session()
table = self.table
row = self.get_post(post)
if row is None:
raise WakaError(strings.POSTNOTFOUND % (int(post), self.name))
if not admin:
archiving = False
if row.admin_post:
raise WakaError(strings.MODDELETEONLY)
if password != row.password:
raise WakaError("Post #%s: %s" % (post, strings.BADDELPASS))
if config.POST_BACKUP and not archiving:
if not timestampofarchival:
timestampofarchival = time.time()
sql = model.backup.insert().values(board_name=self.name,
postnum=row.num,
parent=row.parent,
timestamp=row.timestamp,
lasthit=row.lasthit,
ip=row.ip,
date=row.date,
name=row.name,
trip=row.trip,
email=row.email,
subject=row.subject,
password=row.password,
comment=row.comment,
image=row.filename,
size=row.size,
md5=row.md5,
width=row.width,
height=row.height,
thumbnail=row.thumbnail,
tn_width=row.tn_width,
tn_height=row.tn_height,
lastedit=row.lastedit,
lastedit_ip=row.lastedit_ip,
admin_post=row.admin_post,
stickied=row.stickied,
locked=row.locked,
timestampofarchival=\
timestampofarchival)
session.execute(sql)
if file_only:
# remove just the image and update the database
select_post_image = select([table.c.image, table.c.thumbnail],
or_(table.c.num == post))
baleet_me = session.execute(select_post_image).fetchone()
if baleet_me.image and baleet_me.thumbnail:
self.delete_file(baleet_me.image, baleet_me.thumbnail,
archiving=archiving)
postupdate = table.update().where(table.c.num == post).values(
size=0, md5=null(), thumbnail=null())
session.execute(postupdate)
else:
if config.POST_BACKUP and not archiving:
select_thread_images \
= select([table.c.image, table.c.thumbnail],
table.c.num == post)
else:
select_thread_images \
= select([table.c.image, table.c.thumbnail],
or_(table.c.num == post, table.c.parent == post))
images_to_baleet = session.execute(select_thread_images)
for i in images_to_baleet:
if i.image and i.thumbnail:
self.delete_file(i.image, i.thumbnail, archiving=archiving)
if config.POST_BACKUP and not archiving:
delete_query = table.delete(table.c.num == post)
else:
delete_query = table.delete(or_(
table.c.num == post, table.c.parent == post))
session.execute(delete_query)
# Also back-up child posts.
if config.POST_BACKUP and not archiving:
sql = select([table.c.num], table.c.parent == post)
sel_posts = session.execute(sql).fetchall()
for i in [p[0] for p in sel_posts]:
self.delete_post(i, '', False, False,
from_window=from_window, admin=True,
recur=True)
# Cache building
if not row.parent:
if file_only:
# removing parent (OP) image
self.build_thread_cache(post)
else:
# removing an entire thread
self.delete_thread_cache(post, archiving)
elif not recur:
# removing a reply, or a reply's image
self.build_thread_cache(row.parent)
if admin_data:
admin_data.contents.append('/%s/%d' % (self.name, int(post)))
def delete_file(self, relative_file_path, relative_thumb_path,
archiving=False):
full_file_path = os.path.join(self.path, relative_file_path)
full_thumb_path = os.path.join(self.path, relative_thumb_path)
archive_base = os.path.join(self.path,
self.options['ARCHIVE_DIR'], '')
backup_base = os.path.join(archive_base, self.options['BACKUP_DIR'])
if config.POST_BACKUP:
try:
os.makedirs(backup_base, 0755)
except os.error:
pass
full_archive_path = os.path.join(archive_base,
relative_file_path)
full_tarchive_path = os.path.join(archive_base,
relative_thumb_path)
full_backup_path = os.path.join(backup_base,
os.path.basename(relative_file_path))
full_tbackup_path = os.path.join(backup_base,
os.path.basename(relative_thumb_path))
if os.path.exists(full_file_path):
if archiving:
os.renames(full_file_path, full_archive_path)
os.chmod(full_archive_path, 0644)
elif config.POST_BACKUP:
os.renames(full_file_path, full_backup_path)
os.chmod(full_backup_path, 0644)
else:
os.unlink(full_file_path)
if os.path.exists(full_thumb_path) \
and re.match(self.options['THUMB_DIR'], relative_file_path):
if archiving:
os.renames(full_thumb_path, full_tarchive_path)
os.chmod(full_tarchive_path, 0644)
elif config.POST_BACKUP:
os.renames(full_thumb_path, full_tbackup_path)
os.chmod(full_tbackup_path, 0644)
else:
os.unlink(full_thumb_path)
def remove_backup_stuff(self, admin_data, posts, restore=False):
user = admin_data.user
user.check_access(self.name)
if restore:
admin_data.action = 'backup_restore'
for post in posts:
self.remove_backup_post(admin_data, post, restore=restore)
# Log.
admin_data.contents.append('/%s/%d' % (self.name, int(post)))
# Board pages need refereshing.
self.build_cache()
return staff_interface.StaffInterface(user.login_data.cookie,
board=self,
dest=staff_interface.TRASH_PANEL)
def remove_backup_post(self, task_data, post, restore=False, child=False):
session = model.Session()
table = model.backup
sql = table.select().where(and_(table.c.postnum == post,
table.c.board_name == self.name))
row = session.execute(sql).fetchone()
if not row:
raise WakaError('Backup record not found for post %s.' % (post))
arch_dir = os.path.join(self.path,
self.options['ARCHIVE_DIR'],
self.options['BACKUP_DIR'], '')
if row.image:
arch_image = os.path.join(arch_dir, os.path.basename(row.image))
else:
arch_image = None
if row.thumbnail:
arch_thumb = os.path.join(arch_dir, os.path.basename(row.thumbnail))
else:
arch_thumb = None
if restore:
my_table = self.table
if row.parent and not child:
sql = my_table.select().where(my_table.c.num == row.parent)
parent = session.execute(sql).fetchone()
if not parent:
raise WakaError('Cannot restore post %s: '
'Parent thread deleted.' % (post))
stickied = parent.stickied
locked = parent.locked
lasthit = parent.lasthit
else:
stickied = row.stickied
locked = row.locked
lasthit = row.lasthit
# Perform insertion.
sql = my_table.insert().values(num=row.postnum,
parent=row.parent,
timestamp=row.timestamp,
lasthit=lasthit,
ip=row.ip,
date=row.date,
name=row.name,
trip=row.trip,
email=row.email,
subject=row.subject,
password=row.password,
comment=row.comment,
image=row.image,
size=row.size,
md5=row.md5,
width=row.width,
height=row.height,
thumbnail=row.thumbnail,
tn_width=row.tn_width,
tn_height=row.tn_height,
lastedit=row.lastedit,
lastedit_ip=row.lastedit_ip,
admin_post=row.admin_post,
stickied=stickied,
locked=locked)
session.execute(sql)
# Move file/thumb.
if arch_image and os.path.exists(arch_image):
orig_path = os.path.join(self.path, row.image)
os.renames(arch_image, os.path.join(self.path, row.image))
os.chmod(orig_path, 0644)
if arch_thumb \
and re.match(self.options['THUMB_DIR'],
row.thumbnail) \
and os.path.exists(arch_thumb):
os.renames(arch_thumb, os.path.join(self.path, row.thumb))
if not child:
if row.parent:
self.build_thread_cache(row.parent)
else:
self.build_thread_cache(row.postnum)
else:
# Delete file/thumb.
if arch_image and os.path.exists(arch_image):
os.unlink(os.path.join(arch_image))
if arch_thumb \
and re.match(self.options['THUMB_DIR'],
row.thumbnail) \
and os.path.exists(arch_thumb):
os.unlink(arch_thumb)
# Remove (and restore if appropriate) all thread backups made at the
# point of archival.
if not row.parent:
sql = table.select(and_(table.c.parent == row.postnum,
table.c.board_name == self.name,
table.c.timestampofarchival\
== row.timestampofarchival))\
.order_by(table.c.num.asc())
for row in session.execute(sql):
self.remove_backup_post(None, row.postnum, restore=restore,
child=True)
sql = table.delete().where(and_(table.c.postnum == post,
table.c.board_name == self.name))
session.execute(sql)
def make_report_post_window(self, posts, from_window=False):
if len(posts) == 0:
raise WakaError('No posts selected.')
if len(posts) > 10:
raise WakaError('Too many posts. Try reporting the thread ' \
+ 'or a single post in the case of floods.')
num_parsed = ', '.join(posts)
referer = ''
if not from_window:
referer = self.url
return Template('post_report_window', num=num_parsed, referer=referer)
def report_posts(self, comment, referer, posts):
numip = misc.dot_to_dec(local.environ['REMOTE_ADDR'])
# Sanity checks.
if not comment:
raise WakaError('Please input a comment.')
if len(comment) > config.REPORT_COMMENT_MAX_LENGTH:
raise WakaError('Comment is too long.')
if len(comment) < 3:
raise WakaError('Comment is too short.')
if len(posts) > 10:
raise WakaError('Too many posts. Try reporting the thread or a '\
+ 'single post in the case of floods.')