-
Notifications
You must be signed in to change notification settings - Fork 2
/
post.py
1238 lines (1022 loc) · 43.2 KB
/
post.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
# coding=utf-8
import math
import os
import shutil
import time
import threading
import Queue
import _mysql
import formatting
from database import *
from template import *
from settings import Settings
from framework import *
class Post(object):
def __init__(self, boardid=0):
self.post = {
"boardid": boardid,
"parentid": 0,
"name": "",
"tripcode": "",
"email": "",
"subject": "",
"message": "",
"password": "",
"file": "",
"file_hex": "",
"file_size": 0,
"thumb": "",
"image_width": 0,
"image_height": 0,
"thumb_width": 0,
"thumb_height": 0,
"ip": "",
"timestamp_formatted": "",
"timestamp": 0,
"bumped": 0,
"locked": 0,
}
def __getitem__(self, key):
return self.post[key]
def __setitem__(self, key, value):
self.post[key] = value
def __iter__(self):
return self.post
def insert(self):
logTime("Insertando Post")
post_values = [_mysql.escape_string(str(value)) for key, value in self.post.iteritems()]
return InsertDb("INSERT INTO `posts` (`%s`) VALUES ('%s')" % (
"`, `".join(self.post.keys()),
"', '".join(post_values)
))
class RegenerateThread(threading.Thread):
def __init__(self, threadid, request_queue):
threading.Thread.__init__(self, name="RegenerateThread-%d" % (threadid,))
self.request_queue = request_queue
self.board = Settings._.BOARD
def run(self):
Settings._.BOARD = self.board
while 1:
action = self.request_queue.get()
if action is None:
break
if action == "front":
regenerateFrontPages()
else:
regenerateThreadPage(action)
def threadNumReplies(post):
"""
Get how many replies a thread has
"""
board = Settings._.BOARD
num = FetchOne("SELECT COUNT(1) FROM `posts` WHERE `parentid` = '%s' AND `boardid` = '%s'" % (post, board['id']), 0)
return int(num[0])+1
def get_parent_post(post_id, board_id):
post = FetchOne("SELECT `id`, `email`, `message`, `locked`, `subject`, `timestamp`, `bumped`, `last` FROM `posts` WHERE `id` = %s AND `parentid` = 0 AND `IS_DELETED` = 0 AND `boardid` = %s LIMIT 1" % (post_id, board_id))
if post:
return post
else:
raise UserError, _("The ID of the parent post is invalid.")
def getThread(postid=0, mobile=False, timestamp=0):
board = Settings._.BOARD
total_bytes = 0
database_lock.acquire()
try:
if timestamp:
cond = "`timestamp` = %s" % str(timestamp)
else:
cond = "`id` = %s" % str(postid)
op_post = FetchOne("SELECT IS_DELETED, email, file, file_size, id, image_height, image_width, ip, message, name, subject, thumb, thumb_height, thumb_width, timestamp_formatted, tripcode, parentid, locked, expires, expires_alert, expires_formatted, timestamp FROM `posts` WHERE %s AND `boardid` = %s AND parentid = 0 LIMIT 1" % (cond, board["id"]))
if op_post:
op_post['num'] = 1
if Settings._.MODBROWSE:
op_post['ip'] = inet_ntoa(long(op_post['ip']))
if mobile:
op_post['timestamp_formatted'] = re.compile(r"\(.{1,3}\)", re.DOTALL | re.IGNORECASE).sub(" ", op_post['timestamp_formatted'])
thread = {"id": op_post["id"], "posts": [op_post], "omitted": 0}
#thread = {"id": op_post["id"], "posts": [op_post], "omitted": 0, "omitted_img": 0}
total_bytes += len(op_post["message"])+80
replies = FetchAll("SELECT IS_DELETED, email, file, file_size, id, image_height, image_width, ip, message, name, subject, thumb, thumb_height, thumb_width, timestamp_formatted, tripcode, parentid, locked, expires, expires_alert, expires_formatted, timestamp FROM `posts` WHERE `parentid` = %s AND `boardid` = %s ORDER BY `id` ASC" % (op_post["id"], board["id"]))
thread["length"] = 1
if replies:
for reply in replies:
thread["length"] += 1
reply['num'] = thread["length"]
if Settings._.MODBROWSE:
reply['ip'] = inet_ntoa(long(reply['ip']))
if mobile:
reply['message'] = formatting.fixMobileLinks(reply['message'])
reply['timestamp_formatted'] = re.compile(r"\(.{1,3}\)", re.DOTALL | re.IGNORECASE).sub(" ", reply['timestamp_formatted'])
thread["posts"].append(reply)
total_bytes += len(reply["message"])+57
# An imageboard needs subject
if board["board_type"] in ['1', '5']:
thread["timestamp"] = op_post["timestamp"]
thread["subject"] = op_post["subject"]
thread["message"] = op_post["message"]
thread["locked"] = op_post["locked"]
thread["size"] = "%d KB" % int(total_bytes / 1000)
#threads = [thread]
else:
return None
finally:
database_lock.release()
return thread
def getID(threadid, postnum):
board = Settings._.BOARD
database_lock.acquire()
try:
posts = FetchAll("SELECT id FROM `posts` WHERE `parentid`=%s AND `boardid`=%s ORDER BY `id` ASC" % (thread["id"], board["id"]))
if posts:
post = posts[int(postnum)-1]
postid = post["id"]
else:
return None
finally:
database_lock.release()
return postid
def shortenMsg(message, elid='0', elboard='0'):
"""
Intenta acortar el mensaje si es necesario
Algoritmo traducido desde KusabaX
"""
# 100 chars (ancho) * numline (largo)
#limit = 2250
#return False, message
board = Settings._.BOARD
limit = 100 * int(board['numline'])
message_exploded = message.split('<br />')
if len(message) > limit or len(message_exploded) > int(board['numline']):
message_shortened = ''
for i in range(int(board['numline'])):
if i >= len(message_exploded):
break
message_shortened += message_exploded[i] + '<br />'
#try:
message_shortened = message_shortened.decode('utf-8', 'replace')
#except:
if len(message_shortened) > limit:
message_shortened = message_shortened[:limit]
#try:
message_shortened = formatting.close_html(message_shortened)
#except Exception, message:
return True, message_shortened
else:
return False, message
def threadUpdated(postid):
"""
Shortcut to update front pages and thread page by passing a thread ID. Uses
the simple threading module to do both regenerateFrontPages() and
regenerateThreadPage() asynchronously
"""
# Use queues only if multithreading is enabled
if Settings.USE_MULTITHREADING:
request_queue = Queue.Queue()
threads = [RegenerateThread(i, request_queue) for i in range(2)]
for t in threads:
t.start()
request_queue.put("front")
request_queue.put(postid)
for i in range(2):
request_queue.put(None)
for t in threads:
t.join
else:
regenerateFrontPages()
regenerateThreadPage(postid)
def regenerateFrontPages():
"""
Regenerates index.html and #.html for each page after that according to the number
of live threads in the database
"""
board = Settings._.BOARD
threads = []
if board['board_type'] == '1':
threads_to_fetch = int(board['numthreads'])
threads_to_limit = threads_to_fetch + 50
else:
if board['dir'] == 'o':
threads_to_fetch = threads_to_limit = 210
else:
threads_to_fetch = threads_to_limit = Settings.THREADS_SHOWN_ON_FRONT
database_lock.acquire()
try:
# fetch necessary threads and calculate how many posts we need
allthreads_query = "SELECT id, timestamp, subject, locked, length FROM `posts` WHERE `boardid` = '%s' AND parentid = 0 AND IS_DELETED = 0 ORDER BY `bumped` DESC, `id` ASC LIMIT %d" % \
(board["id"], threads_to_limit)
allthreads = FetchAll(allthreads_query)
posts_to_fetch = 0
for t in allthreads[:threads_to_fetch]:
posts_to_fetch += int(t["length"])
more_threads = allthreads[threads_to_fetch:50]
# get the needed posts for the front page and order them
posts_query = "SELECT * FROM `posts` WHERE `boardid` = '%s' ORDER BY `bumped` DESC, CASE parentid WHEN 0 THEN id ELSE parentid END ASC, `id` ASC LIMIT %d" % \
(board["id"], posts_to_fetch)
posts = FetchAll(posts_query)
threads = []
if posts:
thread = None
post_num = 0
for post in posts:
if post["parentid"] == '0':
skipThread = False
if post["IS_DELETED"] == '0':
# OP; Make new thread
if thread is not None:
thread["length"] = post_num
threads.append(thread)
post_num = post["num"] = 1
thread = {"id": post["id"], "timestamp": post["timestamp"], "subject": post["subject"], "locked": post["locked"], "posts": [post]}
else:
skipThread = True
else:
if not skipThread:
post_num += 1
post["num"] = post_num
thread["posts"].append(post)
if post_num:
thread["length"] = post_num
threads.append(thread)
finally:
database_lock.release()
pages = []
is_omitted = False
if len(threads) > 0:
# Todo : Make this better
if board['board_type'] == '1':
page_count = 1 # Front page only
threads_per_page = int(board['numthreads'])
else:
if board['dir'] == 'o':
front_limit = 210
else:
front_limit = Settings.THREADS_SHOWN_ON_FRONT
if len(threads) > front_limit:
is_omitted = True
page_count = int(math.ceil(float(len(threads)) / float(int(board['numthreads']))))
threads_per_page = int(board['numthreads'])
for i in xrange(page_count):
pages.append([])
start = i * threads_per_page
end = start + threads_per_page
for thread in threads[start:end]:
pages[i].append(thread)
else:
page_count = 0
is_omitted = False
pages.append({})
page_num = 0
for pagethreads in pages:
regeneratePage(page_num, page_count, pagethreads, is_omitted, more_threads)
page_num += 1
def regeneratePage(page_num, page_count, threads, is_omitted=False, more_threads=[]):
"""
Regenerates a single page and writes it to .html
"""
board = Settings._.BOARD
for thread in threads:
replylimit = int(board['numcont'])
# Create reply list
parent = thread["posts"].pop(0)
replies = thread["posts"]
thread["omitted"] = 0
#thread["omitted_img"] = 0
# Omit posts
while(len(replies) > replylimit):
post = replies.pop(0)
thread["omitted"] += 1
#if post["file"]:
# thread["omitted_img"] += 1
# Remake thread with necessary replies only
replies.insert(0, parent)
thread["posts"] = replies
# Shorten messages
for post in thread["posts"]:
post["shortened"], post["message"] = shortenMsg(post["message"])
# Build page according to page number
if page_num == 0:
file_name = "index"
else:
file_name = str(page_num)
if board['board_type'] == '1':
templatename = "txt_board.html"
else:
templatename = "board.html"
page_rendered = renderTemplate(templatename, {"threads": threads, "page_navigator": pageNavigator(page_num, page_count, is_omitted), "more_threads": more_threads})
f = open(Settings.ROOT_DIR + board["dir"] + "/" + file_name + ".html", "w")
try:
f.write(page_rendered)
finally:
f.close()
def threadList(mode=0, sort=''):
board = Settings._.BOARD
if mode == 1:
mobile = True
maxthreads = 20
cutFactor = 100
elif mode == 2:
mobile = True
maxthreads = 1000
cutFactor = 50
elif mode == 3:
mobile = True
maxthreads = 1000 # Settings.MAX_THREADS
cutFactor = 100
else:
mobile = False
maxthreads = 1000 # Settings.MAX_THREADS
cutFactor = 70
q_sort = '`bumped` DESC'
if sort:
if sort == '1':
q_sort = '`timestamp` DESC'
elif sort == '2':
q_sort = '`timestamp` ASC'
elif sort == '3':
q_sort = '`length` DESC'
elif sort == '4':
q_sort = '`length` ASC'
if board['board_type'] == '1':
filename = "txt_threadlist.html"
full_threads = FetchAll("SELECT id, timestamp, timestamp_formatted, subject, length, last FROM `posts` WHERE parentid = 0 AND boardid = %(board)s AND IS_DELETED = 0 ORDER BY %(sort)s LIMIT %(limit)s" \
% {'board': board["id"], 'sort': q_sort, 'limit': maxthreads})
else:
filename = "threadlist.html"
full_threads = FetchAll("SELECT p.*, coalesce(x.count,1) AS length, coalesce(x.t,p.timestamp) AS last FROM `posts` AS p LEFT JOIN (SELECT parentid, count(1)+1 as count, max(timestamp) as t FROM `posts` " +\
"WHERE boardid = %(board)s GROUP BY parentid) AS x ON p.id=x.parentid WHERE p.parentid = 0 AND p.boardid = %(board)s AND p.IS_DELETED = 0 ORDER BY %(sort)s LIMIT %(limit)s" \
% {'board': board["id"], 'sort': q_sort, 'limit': maxthreads})
# Generate threadlist
timestamps = []
for thread in full_threads:
if board['board_type'] == '1':
thread["timestamp_formatted"] = thread["timestamp_formatted"].split(" ")[0]
timestamps.append([thread["last"], formatTimestamp(thread["last"])])
if mobile:
timestamps[-1][1] = re.compile(r"\(.{1,3}\)", re.DOTALL | re.IGNORECASE).sub(" ", timestamps[-1][1])
else:
if len(thread['message']) > cutFactor:
thread['shortened'] = True
else:
thread['shortened'] = False
thread['message'] = thread['message'].replace('<br />', ' ')
thread['message'] = thread['message'].split("<hr />")[0]
thread['message'] = re.compile(r"<[^>]*?>", re.DOTALL | re.IGNORECASE).sub('', thread['message'])
thread['message'] = thread['message'].decode('utf-8')[:cutFactor].encode('utf-8')
thread['message'] = re.compile(r"&(.(?!;))*$", re.DOTALL | re.IGNORECASE).sub('', thread['message']) # Removes incomplete HTML entities
thread['timestamp_formatted'] = re.compile(r"\(.{1,3}\)", re.DOTALL | re.IGNORECASE).sub(" ", thread['timestamp_formatted'])
# Get last reply if in mobile mode
if mode == 1:
thread['timestamp_formatted'] = re.compile(r"\(.{1,3}\)", re.DOTALL | re.IGNORECASE).sub(" ", thread['timestamp_formatted'])
lastreply = FetchOne("SELECT * FROM `posts` WHERE parentid = %s AND boardid = %s AND IS_DELETED = 0 ORDER BY `timestamp` DESC LIMIT 1" % (thread['id'], board['id']))
if lastreply:
if len(lastreply['message']) > 60:
lastreply['shortened'] = True
else:
lastreply['shortened'] = False
lastreply['message'] = lastreply['message'].replace('<br />', ' ')
lastreply['message'] = lastreply['message'].split("<hr />")[0]
lastreply['message'] = re.compile(r"<[^>]*?>", re.DOTALL | re.IGNORECASE).sub('', lastreply['message'])
lastreply['message'] = lastreply['message'].decode('utf-8')[:60].encode('utf-8')
lastreply['message'] = re.compile(r"&(.(?!;))*$", re.DOTALL | re.IGNORECASE).sub('', lastreply['message']) # Removes incomplete HTML entities
lastreply['timestamp_formatted'] = re.compile(r"\(.{1,3}\)", re.DOTALL | re.IGNORECASE).sub(" ", lastreply['timestamp_formatted'])
thread["lastreply"] = lastreply
else:
thread["lastreply"] = None
elif mode == 2:
lastreply = FetchOne("SELECT timestamp_formatted FROM `posts` WHERE parentid = %s AND boardid = %s AND IS_DELETED = 0 ORDER BY `timestamp` DESC LIMIT 1" % (thread['id'], board['id']))
if lastreply:
lastreply['timestamp_formatted'] = re.compile(r"\(.{1,3}\)", re.DOTALL | re.IGNORECASE).sub(" ", lastreply['timestamp_formatted'])
thread["lastreply"] = lastreply
return renderTemplate(filename, {"more_threads": full_threads, "timestamps": timestamps, "mode": mode, "i_sort": sort}, mobile)
def catalog(sort=''):
board = Settings._.BOARD
if board['board_type'] != '0':
raise UserError, "No hay catálogo disponible para esta sección."
cutFactor = 500
q_sort = '`bumped` DESC, `id` ASC'
if sort:
if sort == '1':
q_sort = '`timestamp` DESC'
elif sort == '2':
q_sort = '`timestamp` ASC'
elif sort == '3':
q_sort = '`length` DESC'
elif sort == '4':
q_sort = '`length` ASC'
threads = FetchAll("SELECT id, subject, message, length, thumb, expires_formatted FROM `posts` " +\
"WHERE parentid = 0 AND boardid = %(board)s AND IS_DELETED = 0 ORDER BY %(sort)s" \
% {'board': board["id"], 'sort': q_sort})
for thread in threads:
if len(thread['message']) > cutFactor:
thread['shortened'] = True
else:
thread['shortened'] = False
thread['message'] = thread['message'].replace('<br />', ' ')
thread['message'] = thread['message'].split("<hr />")[0]
thread['message'] = re.compile(r"<[^>]*?>", re.DOTALL | re.IGNORECASE).sub('', thread['message'])
thread['message'] = thread['message'].decode('utf-8')[:cutFactor].encode('utf-8')
thread['message'] = re.compile(r"&(.(?!;))*$", re.DOTALL | re.IGNORECASE).sub('', thread['message']) # Removes incomplete HTML entities
return renderTemplate("catalog.html", {"threads": threads, "i_sort": sort})
def regenerateThreadPage(postid):
"""
Regenerates /res/#.html for supplied thread id
"""
board = Settings._.BOARD
thread = getThread(postid)
if board['board_type'] in ['1', '5']:
template_filename = "txt_thread.html"
outname = Settings.ROOT_DIR + board["dir"] + "/read/" + str(thread["timestamp"]) + ".html"
title_matome = thread['subject']
post_preview = cut_home_msg(thread['posts'][0]['message'], 0)
else:
template_filename = "board.html"
outname = Settings.ROOT_DIR + board["dir"] + "/res/" + str(postid) + ".html"
post_preview = cut_home_msg(thread['posts'][0]['message'], len(board['name']))
if thread['posts'][0]['subject'] != board['subject']:
title_matome = thread['posts'][0]['subject']
else:
title_matome = post_preview
page = renderTemplate(template_filename, {"threads": [thread], "replythread": postid, "matome": title_matome, "preview": post_preview}, False)
f = open(outname, "w")
try:
f.write(page)
finally:
f.close()
def threadPage(postid, mobile=False, timestamp=0):
board = Settings._.BOARD
# TODO : Encontrar mejor forma para transformar el IP a string sólo cuando se usa Modbrowse
if board['board_type'] in ['1', '5']:
template_filename = "txt_thread.html"
else:
template_filename = "board.html"
threads = [getThread(postid, mobile, timestamp)]
return renderTemplate(template_filename, {"threads": threads, "replythread": postid}, mobile)
def dynamicRead(parentid, ranges, mobile=False):
import re
board = Settings._.BOARD
if board['board_type'] != '1':
raise UserError, "Esta sección no es un BBS y como tal no soporta lectura dinámica."
# get entire thread
template_fname = "txt_thread.html"
thread = getThread(timestamp=parentid, mobile=mobile)
if not thread:
# Try the archive
fname = Settings.ROOT_DIR + board["dir"] + "/kako/" + str(parentid) + ".json"
if os.path.isfile(fname):
import json
with open(fname) as f:
thread = json.load(f)
thread['posts'] = [dict(zip(thread['keys'], row)) for row in thread['posts']]
template_fname = "txt_archive.html"
else:
raise UserError, 'El hilo no existe.'
filtered_thread = {
"id": thread['id'],
"timestamp": thread['timestamp'],
"length": thread['length'],
"subject": thread['subject'],
"locked": thread['locked'],
"posts": [],
}
if 'size' in thread:
filtered_thread['size'] = thread['size']
no_op = False
if ranges.endswith('n'):
no_op = True
ranges = ranges[:-1]
# get thread length
total = thread["length"]
# compile regex
__multiple_ex = re.compile("^([0-9]*)-([0-9]*)$")
__single_ex = re.compile("^([0-9]+)$")
__last_ex = re.compile("^l([0-9]+)$")
start = 0
end = 0
# separate by commas (,)
for range in ranges.split(','):
# single post (#)
range_match = __single_ex.match(range)
if range_match:
postid = int(range_match.group(1))
if postid > 0 and postid <= total:
filtered_thread["posts"].append(thread["posts"][postid-1])
# go to next range
continue
# post range (#-#)
range_match = __multiple_ex.match(range)
if range_match:
start = int(range_match.group(1) or 1)
end = int(range_match.group(2) or total)
if start > total:
start = total
if end > total:
end = total
if start < end:
filtered_thread["posts"].extend(thread["posts"][start-1:end])
else:
list = thread["posts"][end-1:start]
list.reverse()
filtered_thread["posts"].extend(list)
# go to next range
continue
# last posts (l#)
range_match = __last_ex.match(range)
if range_match:
length = int(range_match.group(1))
start = total - length + 1
end = total
if start < 1:
start = 1
filtered_thread["posts"].extend(thread["posts"][start-1:])
continue
# calculate previous and next ranges
prevrange = None
nextrange = None
if __multiple_ex.match(ranges) or __last_ex.match(ranges):
if mobile:
range_n = 50
else:
range_n = 100
prev_start = start-range_n
prev_end = start-1
next_start = end+1
next_end = end+range_n
if prev_start < 1:
prev_start = 1
if next_end > total:
next_end = total
if start > 1:
prevrange = '%d-%d' % (prev_start, prev_end)
if end < total:
nextrange = '%d-%d' % (next_start, next_end)
if not no_op and start > 1 and end > 1:
filtered_thread["posts"].insert(0, thread["posts"][0])
if not filtered_thread["posts"]:
raise UserError, "No hay posts que mostrar."
post_preview = cut_home_msg(filtered_thread["posts"][0]["message"], 0)
# render page
return renderTemplate(template_fname, {"threads": [filtered_thread], "replythread": parentid, "prevrange": prevrange, "nextrange": nextrange, "preview": post_preview}, mobile, noindex=True)
def regenerateBoard(everything=False):
"""
Update front pages and every thread res HTML page
"""
board = Settings._.BOARD
op_posts = []
if everything:
op_posts = FetchAll("SELECT `id` FROM `posts` WHERE `boardid` = %s AND `parentid` = 0 AND IS_DELETED = 0" % board["id"])
# Use queues only if multithreading is enabled
if Settings.USE_MULTITHREADING:
request_queue = Queue.Queue()
threads = [RegenerateThread(i, request_queue) for i in range(Settings.MAX_PROGRAM_THREADS)]
for t in threads:
t.start()
request_queue.put("front")
for post in op_posts:
request_queue.put(post["id"])
for i in range(Settings.MAX_PROGRAM_THREADS):
request_queue.put(None)
for t in threads:
t.join()
else:
regenerateFrontPages()
for post in op_posts:
regenerateThreadPage(post["id"])
def deletePost(postid, password, deltype='0', imageonly=False, quick=False):
"""
Remove post from database and unlink file (if present), along with all replies
if supplied post is a thread
"""
board = Settings._.BOARD
# make sure postid is numeric
postid = int(postid)
# get post
post = FetchOne("SELECT `id`, `timestamp`, `parentid`, `file`, `thumb`, `password`, `length` FROM `posts` WHERE `boardid` = %s AND `id` = %s LIMIT 1" % (board["id"], str(postid)))
# abort if the post doesn't exist
if not post:
raise UserError, _("There isn't a post with this ID. It was probably deleted.")
if password:
if password != post['password']:
raise UserError, "No tienes permiso para eliminar este mensaje."
if post["parentid"] == '0' and int(post["length"]) >= Settings.DELETE_FORBID_LENGTH:
raise UserError, "No puedes eliminar un hilo con tantas respuestas."
#if (int(time.time()) - int(post["timestamp"])) > 3600:
# raise UserError, "No puedes eliminar un post tan viejo."
# just update the DB if we're deleting only the image
# otherwise delete the whole post
if imageonly:
if post["file"]:
deleteFile(post)
UpdateDb("UPDATE `posts` SET `file` = '', `file_hex` = '', `thumb` = '', `thumb_width` = 0, `thumb_height` = 0 WHERE `boardid` = %s AND `id` = %s LIMIT 1" % (board["id"], str(post['id'])))
else:
if int(post["parentid"]) == 0:
deleteReplies(post)
logTime("Deleting post " + str(postid))
if deltype != '0' and post["parentid"] != '0':
# Soft delete (recycle bin)
UpdateDb("UPDATE `posts` SET `IS_DELETED` = %s WHERE `boardid` = %s AND `id` = %s LIMIT 1" % (deltype, board["id"], post["id"]))
else:
# Hard delete
if post["file"]:
deleteFile(post)
UpdateDb("DELETE FROM `posts` WHERE `boardid` = %s AND `id` = %s LIMIT 1" % (board["id"], post["id"]))
if post['parentid'] != '0':
UpdateDb("UPDATE `posts` SET length = %d WHERE `id` = '%s' AND `boardid` = '%s'" % (threadNumReplies(post["parentid"]), post["parentid"], board["id"]))
if post['parentid'] == '0':
if board['board_type'] == '1':
os.unlink(Settings.ROOT_DIR + board["dir"] + "/read/" + post["timestamp"] + ".html")
else:
os.unlink(Settings.ROOT_DIR + board["dir"] + "/res/" + post["id"] + ".html")
regenerateHome()
# rebuild thread and fronts if reply; rebuild only fronts if not
if post["parentid"] != '0':
threadUpdated(post["parentid"])
else:
regenerateFrontPages()
def deleteReplies(thread):
board = Settings._.BOARD
# delete files first
replies = FetchAll("SELECT `parentid`, `file`, `thumb` FROM `posts` WHERE `boardid` = %s AND `parentid` = %s AND `file` != ''" % (board["id"], thread["id"]))
for post in replies:
deleteFile(post)
# delete all replies from DB
UpdateDb("DELETE FROM `posts` WHERE `boardid` = %s AND `parentid` = %s" % (board["id"], thread["id"]))
def deleteFile(post):
"""
Unlink file and thumb of supplied post
"""
board = Settings._.BOARD
try:
os.unlink(Settings.IMAGES_DIR + board["dir"] + "/src/" + post["file"])
except:
pass
# we don't want to delete mime thumbnails
if post["thumb"].startswith("mime"):
return
try:
os.unlink(Settings.IMAGES_DIR + board["dir"] + "/thumb/" + post["thumb"])
except:
pass
try:
os.unlink(Settings.IMAGES_DIR + board["dir"] + "/mobile/" + post["thumb"])
except:
pass
if int(post["parentid"]) == 0:
try:
os.unlink(Settings.IMAGES_DIR + board["dir"] + "/cat/" + post["thumb"])
except:
pass
def trimThreads():
"""
Delete any threads which have passed the MAX_THREADS setting
"""
logTime("Trimming threads")
board = Settings._.BOARD
archived = False
# Use limit of the board type
if board['board_type'] == '1':
limit = Settings.TXT_MAX_THREADS
else:
limit = Settings.MAX_THREADS
# trim expiring threads first
if board['maxage'] != '0':
t = time.time()
alert_time = int(round(int(board['maxage']) * Settings.MAX_AGE_ALERT))
time_limit = t + (alert_time * 86400)
old_ops = FetchAll("SELECT `id`, `timestamp`, `expires`, `expires_alert`, `length` FROM `posts` WHERE `boardid` = %s AND `parentid` = 0 AND IS_DELETED = 0 AND `expires` > 0 AND `expires` < %s LIMIT 50" % (board['id'], time_limit))
for op in old_ops:
if t >= int(op['expires']):
# Trim old threads
if board['archive'] == '1' and int(op["length"]) >= Settings.ARCHIVE_MIN_LENGTH:
archiveThread(op["id"])
archived = True
deletePost(op["id"], None)
else:
# Add alert to threads approaching deletion
UpdateDb("UPDATE `posts` SET expires_alert = 1 WHERE `boardid` = %s AND `id` = %s" % (board['id'], op['id']))
# trim inactive threads next
if board['maxinactive'] != '0':
t = time.time()
oldest_last = t - (int(board['maxinactive']) * 86400)
old_ops = FetchAll("SELECT `id`, `length` FROM `posts` WHERE `boardid` = %s AND `parentid` = 0 AND IS_DELETED = 0 AND `last` < %d LIMIT 50" % (board['id'], oldest_last))
for op in old_ops:
if board['archive'] == '1' and int(op["length"]) >= Settings.ARCHIVE_MIN_LENGTH:
archiveThread(op["id"])
archived = True
deletePost(op["id"], None)
# select trim type by board
if board['board_type'] == '1':
trim_method = Settings.TXT_TRIM_METHOD
else:
trim_method = Settings.TRIM_METHOD
# select order by trim
if trim_method == 1:
order = 'last DESC'
elif trim_method == 2:
order = 'bumped DESC'
else:
order = 'timestamp DESC'
# Trim the last thread
op_posts = FetchAll("SELECT `id`, `length` FROM `posts` WHERE `boardid` = %s AND `parentid` = 0 AND IS_DELETED = 0 ORDER BY %s" % (board["id"], order))
if len(op_posts) > limit:
posts = op_posts[limit:]
for post in posts:
if board['archive'] == '1' and int(op["length"]) >= Settings.ARCHIVE_MIN_LENGTH:
archiveThread(post["id"])
archived = True
deletePost(post["id"], None)
pass
if archived:
regenerateKako()
def autoclose_thread(parentid, t, replies):
"""
If the thread is crossing the reply limit, close it with a message.
"""
board = Settings._.BOARD
# decide the replylimit
if board['board_type'] == '1' and Settings.TXT_CLOSE_THREAD_ON_REPLIES > 0:
replylimit = Settings.TXT_CLOSE_THREAD_ON_REPLIES
elif Settings.CLOSE_THREAD_ON_REPLIES > 0:
replylimit = Settings.CLOSE_THREAD_ON_REPLIES
else:
return # do nothing
# close it if passing replylimit
if replies >= replylimit:
notice_post = Post(board["id"])
notice_post["parentid"] = parentid
notice_post["name"] = "Sistema"
notice_post["message"] = "El hilo ha llegado al límite de respuestas.<br />Si quieres continuarlo, por favor crea otro."
notice_post["timestamp"] = notice_post["bumped"] = t+1
notice_post["timestamp_formatted"] = str(replylimit) + " mensajes"
#notice_post["nameblock"] = formatting.nameBlock(notice_post["name"], "", "", notice_post["timestamp_formatted"], 0, "")
notice_post.insert()
UpdateDb("UPDATE `posts` SET `locked` = 1 WHERE `boardid` = '%s' AND `id` = '%s' LIMIT 1" % (board["id"], _mysql.escape_string(parentid)))
def pageNavigator(page_num, page_count, is_omitted=False):
"""
Create page navigator in the format of [0], [1], [2]...
"""
board = Settings._.BOARD
# No threads?
if page_count == 0:
return ''
# TODO nijigen HACK
first_str = "Primera página"
last_str = "Última página"
previous_str = _("Previous")
next_str = _("Next")
omitted_str = "Resto omitido"
page_navigator = "<td>"
if page_num == 0:
page_navigator += first_str
else:
previous = str(page_num - 1)
if previous == "0":
previous = ""
else:
previous = previous + ".html"
page_navigator += '<form method="get" action="' + Settings.BOARDS_URL + board["dir"] + '/' + previous + '"><input value="'+previous_str+'" type="submit" class="psei" /></form>'
page_navigator += "</td><td>"
for i in xrange(page_count):
if i == page_num:
page_navigator += "[<strong>%d</strong>]" % i
else:
if i == 0:
page_navigator += '[<a href="%s%s/">%d</a>]' % (Settings.BOARDS_URL, board['dir'], i)
else:
page_navigator += '[<a href="%s%s/%d.html">%d</a>]' % (Settings.BOARDS_URL, board['dir'], i, i)
if i > 0 and (i % 10) == 0 and not is_omitted:
page_navigator += '<br />'
elif i < 10:
page_navigator += ' '
if is_omitted:
page_navigator += "[" + omitted_str + "]"
page_navigator += "</td><td>"
next = (page_num + 1)
if next == page_count:
page_navigator += last_str + "</td>"
else:
page_navigator += '<form method="get" action="' + Settings.BOARDS_URL + board["dir"] + '/' + str(next) + '.html"><input value="'+next_str+'" type="submit" class="psei" /></form></td>'
return page_navigator
def flood_check(t,post,boardid):
board = Settings._.BOARD
if not post["parentid"]:
maxtime = t - int(board['threadsecs'])
#lastpost = FetchOne("SELECT COUNT(*) FROM `posts` WHERE `ip` = '%s' and `parentid` = 0 and `boardid` = '%s' and IS_DELETED = 0 AND timestamp > %d" % (str(post["ip"]), boardid, maxtime), 0)
# NO MATTER THE IP
lastpost = FetchOne("SELECT COUNT(*) FROM `posts` WHERE `parentid` = 0 and `boardid` = '%s' and IS_DELETED = 0 AND timestamp > %d" % (boardid, maxtime), 0)
pass
else:
maxtime = t - int(board['postsecs'])
lastpost = FetchOne("SELECT COUNT(*) FROM `posts` WHERE `ip` = '%s' and `parentid` != 0 and `boardid` = '%s' and IS_DELETED = 0 AND timestamp > %d" % (str(post["ip"]), boardid, maxtime), 0)
if int(lastpost[0]):
if post["parentid"]:
raise UserError, _("Flood detected. Please wait a moment before posting again.")
else:
lastpost = FetchOne("SELECT `timestamp` FROM `posts` WHERE `parentid`=0 and `boardid`='%s' and IS_DELETED = 0 ORDER BY `timestamp` DESC" % (boardid), 0)
wait = int(int(board['threadsecs']) - (t - int(lastpost[0])))
raise UserError, "Por favor espera " + str(wait) + " segundos antes de crear otro hilo."
def cut_home_msg(message, boardlength=0):
short_message = message.replace("<br />", " ")
short_message = short_message.split("<hr />")[0]
short_message = re.compile(r"<[^>]*?>", re.DOTALL | re.IGNORECASE).sub("", short_message) # Removes HTML tags
limit = Settings.HOME_LASTPOSTS_LENGTH - boardlength
if len(short_message) > limit:
if isinstance(short_message, unicode):
short_message = short_message[:limit].encode('utf-8') + "…"
else:
short_message = short_message.decode('utf-8')[:limit].encode('utf-8') + "…"
short_message = re.compile(r"&(.(?!;))*$", re.DOTALL | re.IGNORECASE).sub("", short_message) # Removes incomplete HTML entities
return short_message