aboutsummaryrefslogtreecommitdiff
path: root/cgi/manage.py
blob: 40be3b2e74dc76e183566863f142ff0c8c584090 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
# coding=utf-8
import os
import cgi
import html
import shutil
import datetime
import logging

from database import *
from settings import Settings
from framework import *
from formatting import *
from template import *
from post import *


def manage(self, path_split):
    page = ''
    validated = False
    administrator = False
    moderator = True
    skiptemplate = False
    staff_account = None

    if 'username' in self.formdata and 'password' in self.formdata:
        # If no admin accounts available, create admin:admin
        first_admin = FetchOne("SELECT 1 FROM `staff` WHERE `rights` = 0 LIMIT 1")
        if not first_admin:
            InsertDb("INSERT INTO `staff` (`username`, `password`, `added`, `rights`) VALUES ('admin', %s, 0, 0)", (genPasswdHash("admin"),))

        staff_account = verifyPasswd(self.formdata['username'], self.formdata['password'])
        if staff_account:
            session_uuid = newSession(staff_account['id'])
            setCookie(self, 'weabot_manage', session_uuid)
            UpdateDb("DELETE FROM `logs` WHERE `timestamp` < %s", (timestamp() - Settings.MANAGE_LOG_TIME,))
        else:
            page += _('Incorrect username/password.')
            logAction('', 'Failed log-in. U:'+_mysql.escape_string(self.formdata['username'])+' IP logged.')
            logging.warn("Failed log-in. U:{} IP:{}".format(self.formdata['username'], self.environ["REMOTE_ADDR"]))
    else:
        # Validate existing session
        manage_cookie = getCookie(self, 'weabot_manage')
        if manage_cookie:
            staff_account = validateSession(manage_cookie)
            if not staff_account:
                page += "La sesión ha expirado. Por favor ingresa tus credenciales nuevamente."
                deleteCookie(self, 'weabot_manage')

    if staff_account:
        validated = True
        if 'session_id' in staff_account:
            renewSession(staff_account['session_id'])

        if staff_account['rights'] in [0, 1, 2]:
            administrator = True
        if staff_account['rights'] == 2:
            moderator = False
        UpdateDb('UPDATE `staff` SET `lastactive` = %s WHERE `id` = %s LIMIT 1',
                (timestamp(), staff_account['id']))

    if not validated:
        template_filename = "login.html"
        template_values = {}
    else:
        if len(path_split) > 2:
            if path_split[2] == 'rebuild':
                if not administrator:
                    return

                try:
                    board_dir = path_split[3]
                except:
                    board_dir = ''

                if board_dir == '':
                    template_filename = "rebuild.html"
                    template_values = {'boards': boardlist()}
                else:
                    everything = ("everything" in self.formdata)
                    if board_dir == '!ALL':
                        t1 = time.time()
                        boards = FetchAll(
                            'SELECT `dir` FROM `boards` WHERE secret = 0')
                        for board in boards:
                            board = setBoard(board['dir'])
                            regenerateBoard(everything)

                        message = _('Rebuilt %(board)s in %(time)s seconds.') % {
                            'board': _('all boards'), 'time': timeTaken(t1, time.time())}
                        logAction(staff_account['username'], _(
                            'Rebuilt %s') % _('all boards'))
                    elif board_dir == '!BBS':
                        t1 = time.time()
                        boards = FetchAll(
                            'SELECT `dir` FROM `boards` WHERE `board_type` = 1')
                        for board in boards:
                            board = setBoard(board['dir'])
                            regenerateBoard(everything)

                        message = _('Rebuilt %(board)s in %(time)s seconds.') % {
                            'board': _('all boards'), 'time': timeTaken(t1, time.time())}
                        logAction(staff_account['username'], _(
                            'Rebuilt %s') % _('all boards'))
                    elif board_dir == '!IB':
                        t1 = time.time()
                        boards = FetchAll(
                            'SELECT `dir` FROM `boards` WHERE `board_type` = 1')
                        for board in boards:
                            board = setBoard(board['dir'])
                            regenerateBoard(everything)

                        message = _('Rebuilt %(board)s in %(time)s seconds.') % {
                            'board': _('all boards'), 'time': timeTaken(t1, time.time())}
                        logAction(staff_account['username'], _(
                            'Rebuilt %s') % _('all boards'))
                    elif board_dir == '!HOME':
                        t1 = time.time()
                        regenerateHome()
                        message = _('Rebuilt %(board)s in %(time)s seconds.') % {
                            'board': _('home'), 'time': timeTaken(t1, time.time())}
                        logAction(staff_account['username'], _(
                            'Rebuilt %s') % _('home'))
                    elif board_dir == '!NEWS':
                        t1 = time.time()
                        regenerateNews()
                        message = _('Rebuilt %(board)s in %(time)s seconds.') % {
                            'board': _('news'), 'time': timeTaken(t1, time.time())}
                        logAction(staff_account['username'], _(
                            'Rebuilt %s') % _('news'))
                    elif board_dir == '!KAKO':
                        t1 = time.time()
                        boards = FetchAll(
                            'SELECT `dir` FROM `boards` WHERE archive = 1')
                        for board in boards:
                            board = setBoard(board['dir'])
                            regenerateKako()

                        message = _('Rebuilt %(board)s in %(time)s seconds.') % {
                            'board': 'kako', 'time': timeTaken(t1, time.time())}
                        logAction(staff_account['username'], _(
                            'Rebuilt %s') % 'kako')
                    elif board_dir == '!HTACCESS':
                        t1 = time.time()
                        if regenerateAccess():
                            message = _('Rebuilt %(board)s in %(time)s seconds.') % {
                                'board': _('htaccess'), 'time': timeTaken(t1, time.time())}
                            logAction(staff_account['username'], _(
                                'Rebuilt %s') % _('htaccess'))
                        else:
                            message = _(
                                'htaccess regeneration deactivated by sysop.')
                    else:
                        t1 = time.time()
                        board = setBoard(board_dir)
                        regenerateBoard(everything)

                        message = _('Rebuilt %(board)s in %(time)s seconds.') % {
                            'board': '/' + board['dir'] + '/', 'time': timeTaken(t1, time.time())}
                        logAction(staff_account['username'],
                                  'Rebuilt /' + board['dir'] + '/')

                    template_filename = "message.html"
            elif path_split[2] == 'mod':
                if not moderator:
                    return

                try:
                    board = setBoard(path_split[3])
                except:
                    board = ""

                if not board:
                    template_filename = "mod.html"
                    template_values = {"mode": 1, 'boards': boardlist()}
                elif len(path_split) > 4:
                    parentid = int(path_split[4])
                    # make sure it's the full thread
                    check = FetchOne("SELECT `parentid` FROM `posts` WHERE `id` = %s AND `boardid` = %s LIMIT 1", (parentid, board['id']))
                    if check['parentid']:
                      parentid = int(check['parentid'])
                    
                    posts = FetchAll('SELECT id, timestamp, timestamp_formatted, name, message, file, thumb, IS_DELETED, locked, subject, length, INET6_NTOA(ip) AS ip FROM `posts` WHERE (parentid = %s OR id = %s) AND boardid = %s ORDER BY `id` ASC', (parentid, parentid, board['id']))
                    template_filename = "mod.html"
                    template_values = {"mode": 3, "dir": board["dir"], "posts": posts}
                else:
                    threads = FetchAll("SELECT * FROM `posts` WHERE boardid = %s AND parentid = 0 ORDER BY `bumped` DESC" % board["id"])
                    template_filename = "mod.html"
                    template_values = {"mode": 2, "dir": board["dir"], "threads": threads}
            elif path_split[2] == "recent":
                posts = FetchAll("SELECT posts.id, posts.subject, dir, boards.board_type, CASE parentid WHEN '0' THEN posts.id ELSE parentid END AS parentid, file, thumb, timestamp_formatted, timestamp, posts.message, INET6_NTOA(ip) AS ip, posts.name, email, tripcode, boards.name AS board_name FROM posts INNER JOIN boards ON posts.boardid = boards.id WHERE posts.timestamp > UNIX_TIMESTAMP() - 86400 ORDER BY timestamp DESC")
                template_filename = "recent.html"
                template_values = {"posts": posts}
            elif path_split[2] == 'staff':
                if staff_account['rights'] != 0:
                    return
                action_taken = False

                if len(path_split) > 3:
                    if path_split[3] == 'add' or path_split[3] == 'edit':
                        member = None
                        member_username = ''
                        member_rights = 3

                        if path_split[3] == 'edit':
                          if len(path_split) > 4:
                            member = FetchOne('SELECT * FROM `staff` WHERE `id` = %s LIMIT 1', (path_split[4],))
                            if member:
                              member_username = member['username']
                              member_rights = member['rights']
                              action = 'edit/' + str(member['id'])

                              try:
                                if self.formdata.get('user'):
                                  if self.formdata['rights'] in [0, 1, 2, 3]:
                                    action_taken = True

                                    UpdateDb("UPDATE `staff` SET `username` = %s, `rights` = %s WHERE `id` = LIMIT 1",
                                            (self.formdata['user'], self.formdata['rights'], member['id']))
                                    message = _(
                                        'Staff member updated.')
                                    logAction(staff_account['username'], _(
                                        'Updated staff account for %s') % self.formdata['user'])
                                    template_filename = "message.html"
                              except:
                                pass
                        else:
                            action = 'add'
                            try:
                                if self.formdata.get('user') and self.formdata.get('pass'):
                                    username_taken = FetchOne(
                                        'SELECT * FROM `staff` WHERE `username` = %s LIMIT 1', (self.formdata['user'],))
                                    if not username_taken:
                                        if self.formdata['rights'] in [0, 1, 2, 3]:
                                            action_taken = True
                                            pass_hash = genPasswdHash(
                                                self.formdata['pass'])

                                            InsertDb("INSERT INTO `staff` (`username`, `password`, `added`, `rights`) VALUES (%s, %s, %s, %s)",
                                                    (self.formdata['user'], pass_hash, timestamp(), self.formdata['rights']))
                                            message = _('Staff member added.')
                                            logAction(
                                                staff_account['username'], 'Added staff account for ' + self.formdata['user'])

                                            template_filename = "message.html"
                                    else:
                                        action_taken = True
                                        message = _(
                                            'That username is already in use.')
                                        template_filename = "message.html"
                            except:
                                pass

                        if not action_taken:
                            action_taken = True

                            if action == 'add':
                                submit = 'Agregar'
                            else:
                                submit = 'Editar'

                            template_filename = "staff.html"
                            template_values = {'mode': 1,
                                               'action': action,
                                               'member': member,
                                               'member_username': member_username,
                                               'member_rights': member_rights,
                                               'submit': submit}
                    elif path_split[3] == 'delete':
                        if not moderator:
                            return

                        action_taken = True
                        message = '<a href="' + Settings.CGI_URL + 'manage/staff/delete_confirmed/' + \
                          path_split[4] + '">' + _('Click here to confirm the deletion of that staff member') + '</a>'
                        template_filename = "message.html"
                    elif path_split[3] == 'delete_confirmed':
                        if not moderator:
                            return

                        try:
                            action_taken = True
                            member = FetchOne(
                                'SELECT `username` FROM `staff` WHERE `id` = ' + _mysql.escape_string(path_split[4]) + ' LIMIT 1')
                            if member:
                                UpdateDb('DELETE FROM `staff` WHERE `id` = ' +
                                         _mysql.escape_string(path_split[4]) + ' LIMIT 1')
                                message = 'Staff member deleted.'
                                template_filename = "message.html"
                                logAction(staff_account['username'], _(
                                    'Deleted staff account for %s') % member['username'])
                            else:
                                message = _(
                                    'Unable to locate a staff account with that ID.')
                                template_filename = "message.html"
                        except:
                            pass

                if not action_taken:
                    staff = FetchAll('SELECT * FROM `staff` ORDER BY `rights`')
                    for member in staff:
                        if member['rights'] == 0:
                            member['rights'] = _('Super-administrator')
                        elif member['rights'] == 1:
                            member['rights'] = _('Administrator')
                        elif member['rights'] == 2:
                            member['rights'] = _('Developer')
                        elif member['rights'] == 3:
                            member['rights'] = _('Moderator')
                        if member['lastactive']:
                            member['lastactivestamp'] = member['lastactive']
                            member['lastactive'] = formatTimestamp(
                                member['lastactive'])
                        else:
                            member['lastactive'] = _('Never')
                            member['lastactivestamp'] = 0
                    template_filename = "staff.html"
                    template_values = {'mode': 0, 'staff': staff}
            elif path_split[2] == 'delete':
                if not moderator:
                    return

                do_ban = False
                try:
                    if self.formdata['ban'] == 'true':
                        do_ban = True
                except:
                    pass

                template_filename = "delete.html"
                template_values = {'do_ban': do_ban, 'curboard': path_split[3], 'postid': path_split[4]}
            elif path_split[2] == 'delete_confirmed':
                if not moderator:
                    return

                do_ban = self.formdata.get('ban')
                permanently = self.formdata.get('perma')
                imageonly = self.formdata.get('imageonly')

                board = setBoard(path_split[3])
                postid = int(path_split[4])
                post = FetchOne('SELECT id, message, parentid, INET6_NTOA(ip) AS ip FROM posts WHERE boardid = %s AND id = %s' % (
                    board['id'], postid))

                if not permanently:
                    deletePost(path_split[4], None, '2', imageonly)
                else:
                    deletePost(path_split[4], None, '0', imageonly)
                regenerateHome()

                # Borrar denuncias
                UpdateDb("DELETE FROM `reports` WHERE `postid` = '" +
                         _mysql.escape_string(path_split[4])+"'")
                boards = FetchAll(
                    'SELECT `name`, `dir` FROM `boards` ORDER BY `dir`')

                if imageonly:
                    message = 'Archivo de post /%s/%s eliminado.' % (
                        board['dir'], post['id'])
                elif permanently or post["parentid"] == '0':
                    message = 'Post /%s/%s eliminado permanentemente.' % (
                        board['dir'], post['id'])
                else:
                    message = 'Post /%s/%s enviado a la papelera.' % (
                        board['dir'], post['id'])
                template_filename = "message.html"
                logAction(staff_account['username'], message +
                          ' Contenido: ' + post['message'] + ' IP: ' + post['ip'])

                if do_ban:
                    message = _('Redirecting to ban page...') + '<meta http-equiv="refresh" content="0;url=' + \
                        Settings.CGI_URL + 'manage/ban?ip=' + \
                        post['ip'] + '" />'
                    template_filename = "message.html"
            elif path_split[2] == 'lock':
                setLocked = 0

                # Nos vamos al board y ubicamos el post
                board = setBoard(path_split[3])
                post = FetchOne('SELECT `parentid`, `locked` FROM `posts` WHERE `boardid` = ' +
                                board['id'] + ' AND `id` = \'' + _mysql.escape_string(path_split[4]) + '\' LIMIT 1')
                if not post:
                    message = _('Unable to locate a post with that ID.')
                    template_filename = "message.html"
                else:
                    if post['parentid'] != '0':
                        message = _('Post is not a thread opener.')
                        template_filename = "message.html"
                    else:
                        if post['locked'] == '0':
                            # Cerrar si esta abierto
                            setLocked = 1
                        else:
                            # Abrir si esta cerrado
                            setLocked = 0

                        UpdateDb("UPDATE `posts` SET `locked` = %d WHERE `boardid` = '%s' AND `id` = '%s' LIMIT 1" % (
                            setLocked, board["id"], _mysql.escape_string(path_split[4])))
                        threadUpdated(path_split[4])
                    if setLocked == 1:
                        message = _('Thread successfully closed.')
                        logAction(staff_account['username'], _('Closed thread %s') % (
                            '/' + path_split[3] + '/' + path_split[4]))
                    else:
                        message = _('Thread successfully opened.')
                        logAction(staff_account['username'], _('Opened thread %s') % (
                            '/' + path_split[3] + '/' + path_split[4]))
                    template_filename = "message.html"
            elif path_split[2] == 'permasage':
                setPermasaged = 0

                # Nos vamos al board y ubicamos el post
                board = setBoard(path_split[3])
                post = FetchOne('SELECT `parentid`, `locked` FROM `posts` WHERE `boardid` = ' +
                                board['id'] + ' AND `id` = \'' + _mysql.escape_string(path_split[4]) + '\' LIMIT 1')
                if not post:
                    message = 'Unable to locate a post with that ID.'
                    template_filename = "message.html"
                elif post['locked'] == '1':
                    message = 'Solo se puede aplicar permasage en un hilo abierto.'
                    template_filename = "message.html"
                else:
                    if post['parentid'] != '0':
                        message = 'Post is not a thread opener.'
                        template_filename = "message.html"
                    else:
                        if post['locked'] == '2':
                            # Sacar permasage
                            setPermasaged = 0
                        else:
                            # Colocar permasage
                            setPermasaged = 2

                        UpdateDb("UPDATE `posts` SET `locked` = %d WHERE `boardid` = '%s' AND `id` = '%s' LIMIT 1" % (
                            setPermasaged, board["id"], _mysql.escape_string(path_split[4])))
                        regenerateFrontPages()
                        threadUpdated(path_split[4])

                    if setPermasaged == 2:
                        message = 'Thread successfully permasaged.'
                        logAction(
                            staff_account['username'], 'Enabled permasage in thread /' + path_split[3] + '/' + path_split[4])
                    else:
                        message = 'Thread successfully un-permasaged.'
                        logAction(
                            staff_account['username'], 'Disabled permasage in thread /' + path_split[3] + '/' + path_split[4])
                    template_filename = "message.html"
            elif path_split[2] == 'move':
                raise NotImplementedError

                #if not moderator:
                if not administrator:
                    return

                oldboardid = ""
                oldthread = ""
                newboardid = ""
                try:
                    oldboardid = path_split[3]
                    oldthread = path_split[4]
                    newboardid = path_split[5]
                except:
                    pass

                try:
                    oldboardid = self.formdata['oldboardid']
                    oldthread = self.formdata['oldthread']
                    newboardid = self.formdata['newboardid']
                except:
                    pass

                if oldboardid and oldthread and newboardid:
                    message = "import"
                    import shutil
                    message += "ok"

                    board = setBoard(oldboardid)
                    oldboard = board['dir']
                    oldboardsubject = board['subject']
                    oldboardname = random.choice(board["anonymous"].split('|'))

                    # get old posts
                    posts = FetchAll(
                        "SELECT * FROM `posts` WHERE (`id` = {0} OR `parentid` = {0}) AND `boardid` = {1} ORDER BY id ASC".format(oldthread, board['id']))

                    # switch to new board
                    board = setBoard(newboardid)
                    newboard = board['dir']

                    refs = {}
                    moved_files = []
                    moved_thumbs = []
                    moved_cats = []
                    newthreadid = 0
                    newthread = 0
                    num = 1

                    message = "from total: %s<br>" % len(posts)
                    template_filename = "message.html"

                    for p in posts:
                        # save old post ID
                        old_id = p['id']
                        is_op = bool(p['parentid'] == '0')

                        # copy post object but without ID and target boardid
                        post = Post()
                        post.post = p
                        post.post.pop("id")
                        post["boardid"] = board['id']
                        post["parentid"] = newthreadid

                        # save the files we need to move if any
                        if post['IS_DELETED'] == '0':
                            if post['file']:
                                moved_files.append(post['file'])
                            if post['thumb']:
                                moved_thumbs.append(post['thumb'])
                                if is_op:
                                    moved_cats.append(post['thumb'])

                        # fix subject if necessary
                        if post['subject'] and post['subject'] == oldboardsubject:
                            post['subject'] = board['subject']

                        # fix new default name
                        if post['name'] == oldboardname:
                            post['name'] = board['anonymous']

                        # fix date and (re)add post ID if necessary
                        post['timestamp_formatted'] = formatTimestamp(post['timestamp'])
                        if board["useid"] != '0':
                            if post["parentid"]:
                                tym = parent_time
                            else:
                                tym = post["timestamp"]
                            post['timestamp_formatted'] += ' ID:' + iphash(post['ip'], post, tym, board["useid"], False, '', False, False, (board["countrycode"] in ['1', '2']))

                        # insert new post and get its new ID
                        new_id = post.insert()

                        # save the reference (BBS = post number, IB = new ID)
                        refs[old_id] = num if board['board_type'] == '1' else new_id

                        # this was an OP
                        message += "newthread = %s parentid = %s<br>" % (
                            newthreadid, p['parentid'])
                        if is_op:
                            oldthread = old_id
                            newthreadid = new_id
                            oldbumped = post["bumped"]

                            # BBS = new thread timestamp, IB = new thread ID
                            newthread = post['timestamp'] if board['board_type'] == '1' else new_id
                            parent_time = post['timestamp']

                        # log it
                        message += "%s -> %s<br>" % (old_id, new_id)

                        num += 1

                    # fix anchors
                    for old, new in refs.items():
                        old_url = "/{oldboard}/res/{oldthread}.html#{oldpost}\">&gt;&gt;{oldpost}</a>".format(
                            oldboard=oldboard, oldthread=oldthread, oldpost=old)

                        if board['board_type'] == '1':
                            new_url = "/{newboard}/read/{newthread}/{newpost}\">&gt;&gt;{newpost}</a>".format(
                                newboard=newboard, newthread=newthread, newpost=new)
                        else:
                            new_url = "/{newboard}/res/{newthread}.html#{newpost}\">&gt;&gt;{newpost}</a>".format(
                                newboard=newboard, newthread=newthread, newpost=new)

                        sql = "UPDATE `posts` SET `message` = REPLACE(message, '{old}', '{new}') WHERE `boardid` = {newboardid} AND (`id` = {newthreadid} OR `parentid` = {newthreadid})".format(
                            old=old_url, new=new_url, newboardid=board['id'], newthreadid=newthreadid)
                        message += sql + "<br>"
                        UpdateDb(sql)

                    # copy files
                    for file in moved_files:
                        if not os.path.isfile(Settings.IMAGES_DIR + newboard + "/src/" + file):
                            shutil.copyfile(Settings.IMAGES_DIR + oldboard + "/src/" +
                                            file, Settings.IMAGES_DIR + newboard + "/src/" + file)
                    for thumb in moved_thumbs:
                        if not os.path.isfile(Settings.IMAGES_DIR + newboard + "/thumb/" + thumb):
                            shutil.copyfile(Settings.IMAGES_DIR + oldboard + "/thumb/" +
                                            thumb, Settings.IMAGES_DIR + newboard + "/thumb/" + thumb)
                        if not os.path.isfile(Settings.IMAGES_DIR + newboard + "/mobile/" + thumb):
                            shutil.copyfile(Settings.IMAGES_DIR + oldboard + "/mobile/" +
                                            thumb, Settings.IMAGES_DIR + newboard + "/mobile/" + thumb)
                    for cat in moved_cats:
                        try:
                            if not os.path.isfile(Settings.IMAGES_DIR + newboard + "/cat/" + thumb):
                                shutil.copyfile(Settings.IMAGES_DIR + oldboard + "/cat/" +
                                                thumb, Settings.IMAGES_DIR + newboard + "/cat/" + thumb)
                        except:
                            pass

                    # lock original, set expiration to 1 day
                    exp = timestamp()+86400
                    exp_format = datetime.datetime.fromtimestamp(exp).strftime("%d/%m")
                    sql = "UPDATE `posts` SET `locked`=1, `expires`={exp}, `expires_formatted`=\"{exp_format}\" WHERE `boardid`=\"{oldboard}\" AND id=\"{oldthread}\"".format(exp=exp, exp_format=exp_format, oldboard=oldboardid, oldthread=oldthread)
                    UpdateDb(sql)

                    # insert notice message
                    if 'msg' in self.formdata:
                        leavemsg = True
                        board = setBoard(oldboard)

                        if board['board_type'] == '1':
                            thread_url = "/{newboard}/read/{newthread}".format(newboard=newboard, newthread=newthread)
                        else:
                            thread_url = "/{newboard}/res/{newthread}.html".format(newboard=newboard, newthread=newthread)

                        notice_post = Post(board["id"])
                        notice_post["parentid"] = oldthread
                        if board['board_type'] == "0":
                            notice_post["subject"] = "Aviso"
                        notice_post["name"] = "Sistema"
                        notice_post["message"] = "El hilo ha sido movido a <a href=\"{url}\">/{newboard}/{newthread}</a>.".format(
                            url=thread_url, newboard=newboard, newthread=newthread)
                        notice_post["timestamp"] = timestamp()+1
                        notice_post["timestamp_formatted"] = "Hilo movido"
                        notice_post["bumped"] = oldbumped
                        notice_post.insert()
                        regenerateFrontPages()
                        regenerateThreadPage(oldthread)

                    # regenerate again (fix?)
                    board = setBoard(newboardid)
                    regenerateFrontPages()
                    regenerateThreadPage(newthreadid)

                    message += "done"

                    logAction(staff_account['username'], "Movido hilo %s/%s a %s/%s." % (oldboard, oldthread, newboard, newthread))
                else:
                    template_filename = "move.html"
                    template_values = {'boards': boardlist(
                    ), 'oldboardid': oldboardid, 'oldthread': oldthread}
            elif path_split[2] == 'ban':
                if not moderator:
                    return

                if len(path_split) > 4:
                    board = setBoard(path_split[3])
                    post = FetchOne('SELECT INET6_NTOA(`ip`) AS `ip` FROM `posts` WHERE `boardid` = ' +
                                    board['id'] + ' AND `id` = \'' + _mysql.escape_string(path_split[4]) + '\' LIMIT 1')
                    
                    if not post:
                        message = _('Unable to locate a post with that ID.')
                        template_filename = "message.html"
                    else:
                        message = '<meta http-equiv="refresh" content="0;url=' + \
                            Settings.CGI_URL + 'manage/ban?ip=' + post['ip'] + '" />Espere...'
                        template_filename = "message.html"
                else:
                    reason = self.formdata.get('reason')
                    if reason is not None:
                        # Start ban process
                        import netaddr
                        ip = self.formdata['ip']

                        # Parse CIDR or IP glob
                        try:
                            if netaddr.valid_ipv4(ip) or netaddr.valid_ipv6(ip):
                                ipaddress = netaddr.IPAddress(ip)
                                ipstart = ipend = ipstr = str(ipaddress)
                            elif netaddr.valid_glob(ip):
                                iprange = netaddr.glob_to_iprange(ip)
                                ipstart, ipend = str(iprange[0]), str(iprange[-1])

                                cidrs = iprange.cidrs()
                                if len(cidrs) == 1:
                                    ipstr = str(cidrs[0])
                                else:
                                    ipstr = str(iprange)
                            elif '/' in ip:
                                # Try with CIDR
                                ipnetwork = netaddr.IPNetwork(ip)
                                ipstart, ipend = str(ipnetwork[0]), str(ipnetwork[-1])
                                ipstr = str(ipnetwork)
                            else:
                                self.error("IP o rango inválido.")
                                return
                        except netaddr.core.AddrFormatError as e:
                            self.error("Problema con el IP o rango ingresado: {}".format(e))
                            return

                        if self.formdata['seconds'] != '0':
                            until = str(
                                timestamp() + int(self.formdata['seconds']))
                        else:
                            until = '0'
                        where = ''
                        if 'board_all' not in self.formdata:
                            where = []
                            boards = FetchAll('SELECT `dir` FROM `boards`')
                            for board in boards:
                                keyname = 'board_' + board['dir']
                                if keyname in self.formdata:
                                    if self.formdata[keyname] == "1":
                                        where.append(board['dir'])
                            if len(where) > 0:
                                where = pickle.dumps(where)
                            else:
                                self.error(
                                    _("You must select where the ban shall be placed"))
                                return

                        if 'edit' in self.formdata:
                            UpdateDb("DELETE FROM `bans` WHERE `id` = '" +
                                     _mysql.escape_string(self.formdata['edit']) + "' LIMIT 1")
                        """else: # TODO : Duplicate check
                            ban = FetchOne("SELECT `id` FROM `bans` WHERE `ip` = '" + _mysql.escape_string(
                                ip) + "' AND `boards` = '" + _mysql.escape_string(where) + "' LIMIT 1")
                            if ban:
                                self.error(_('There is already an identical ban for this IP.') + '<a href="' +
                                           Settings.CGI_URL+'manage/ban/' + ip + '?edit=' + ban['id']+'">' + _('Edit') + '</a>')
                                return"""

                        # Blind mode
                        blind = self.formdata.get('blind', '0')

                        #raise UserError, "{} {} {}".format(ipstart, ipend, ipstr)

                        # Banear sin mensaje
                        InsertDb("INSERT INTO `bans` (`ipstart`, `ipend`, `ipstr`, `boards`, `added`, `until`, `staff`, `reason`, `note`, `blind`) VALUES (INET6_ATON('" +
                                ipstart + "'), INET6_ATON('" + ipend + "'), '" + ipstr + "', '" +
                                 _mysql.escape_string(where) + "', " + str(timestamp()) + ", " + until + ", '" + _mysql.escape_string(staff_account['username']) + "', '" + _mysql.escape_string(self.formdata['reason']) + "', '" + _mysql.escape_string(self.formdata['note']) + "', '"+blind+"')")

                        regenerateAccess()
                        if 'edit' in self.formdata:
                            message = _('Ban successfully edited.')
                            action = 'Edited ban for ' + ip
                        else:
                            message = _('Ban successfully placed.')
                            action = 'Banned ' + ip
                            if until != '0':
                                action += ' until ' + \
                                    formatTimestamp(until)
                            else:
                                action += ' permanently'
                        logAction(staff_account['username'], action)
                        template_filename = 'message.html'
                    else:
                        startvalues = {'where': [],
                                       'reason': '',
                                       'note': '',
                                       'message': '(GET OUT)',
                                       'seconds': '0',
                                       'blind': '1'}
                        edit_id = 0
                        if 'edit' in self.formdata:
                            edit_id = self.formdata['edit']
                            ban = FetchOne("SELECT `id`, INET6_NTOA(`ip`) AS 'ip', CASE WHEN `netmask` IS NULL THEN '255.255.255.255' ELSE INET_NTOA(`netmask`) END AS 'netmask', boards, added, until, staff, reason, note, blind FROM `bans` WHERE `id` = '" +
                                           _mysql.escape_string(edit_id) + "' ORDER BY `added` DESC")
                            if ban:
                                if ban['boards'] == '':
                                    where = ''
                                else:
                                    where = pickle.loads(ban['boards'])
                                if ban['until'] == '0':
                                    until = 0
                                else:
                                    until = int(ban['until']) - timestamp()
                                startvalues = {'where': where,
                                               'reason': ban['reason'],
                                               'note': ban['note'],
                                               'seconds': str(until),
                                               'blind': ban['blind']
                                               }
                            else:
                                edit_id = 0

                        template_filename = "bans.html"
                        template_values = {'mode': 1,
                                           'boards': boardlist(),
                                           'ip': self.formdata.get('ip'),
                                           'startvalues': startvalues,
                                           'edit_id': edit_id}
            elif path_split[2] == 'bans':
                if not moderator:
                    return

                action_taken = False
                if len(path_split) > 4:
                    if path_split[3] == 'delete':
                        ip = FetchOne("SELECT ipstr FROM `bans` WHERE `id` = '" +
                                      _mysql.escape_string(path_split[4]) + "' LIMIT 1", 0)[0]
                        if ip != '':
                            # Delete ban
                            UpdateDb('DELETE FROM `bans` WHERE `id` = ' +
                                     _mysql.escape_string(path_split[4]) + ' LIMIT 1')
                            regenerateAccess()
                            message = _('Ban successfully deleted.')
                            template_filename = "message.html"
                            logAction(staff_account['username'], _(
                                'Deleted ban for %s') % ip)
                        else:
                            message = _(
                                'There was a problem while deleting that ban.  It may have already been removed, or recently expired.')
                            template_filename = "message.html"

                if not action_taken:
                    bans = FetchAll(
                        "SELECT `id`, `ipstr` AS 'ip', boards, added, until, staff, reason, note, blind FROM `bans` ORDER BY `added` DESC")
                    if bans:
                        for ban in bans:
                            if ban['boards'] == '':
                                ban['boards'] = _('All boards')
                            else:
                                where = pickle.loads(ban['boards'].encode('utf-8'))
                                if len(where) > 1:
                                    ban['boards'] = '/' + \
                                        '/, /'.join(where) + '/'
                                else:
                                    ban['boards'] = '/' + where[0] + '/'
                            ban['added'] = formatTimestamp(ban['added'])
                            if ban['until'] == '0':
                                ban['until'] = _('Does not expire')
                            else:
                                ban['until'] = formatTimestamp(ban['until'])
                            if ban['blind'] == '1':
                                ban['blind'] = 'Sí'
                            else:
                                ban['blind'] = 'No'
                    template_filename = "bans.html"
                    template_values = {'mode': 0, 'bans': bans}
            elif path_split[2] == 'changepassword':
                form_submitted = False
                try:
                    if self.formdata['oldpassword'] != '' and self.formdata['newpassword'] != '' and self.formdata['newpassword2'] != '':
                        form_submitted = True
                except:
                    pass
                if form_submitted:
                    if verifyPasswd(staff_account['username'], self.formdata['oldpassword']):
                        if self.formdata['newpassword'] == self.formdata['newpassword2']:
                            UpdateDb('UPDATE `staff` SET `password` = \'' + genPasswdHash(
                                self.formdata['newpassword']) + '\' WHERE `id` = ' + staff_account['id'] + ' LIMIT 1')
                            message = _(
                                'Password successfully changed.  Please log out and log back in.')
                            template_filename = "message.html"
                        else:
                            message = _('Passwords did not match.')
                            template_filename = "message.html"
                    else:
                        message = _('Current password incorrect.')
                        template_filename = "message.html"
                else:
                    template_filename = "changepassword.html"
                    template_values = {}
            elif path_split[2] == 'board':
                if not administrator:
                    return

                if len(path_split) > 3:
                    board = setBoard(path_split[3])
                    form_submitted = False
                    try:
                        if self.formdata['name'] != '':
                            form_submitted = True
                    except:
                        pass
                    if form_submitted:
                        # Update board settings
                        board['name'] = self.formdata['name']
                        board['longname'] = self.formdata['longname']
                        board['subname'] = self.formdata['subname']
                        board['anonymous'] = self.formdata['anonymous']
                        board['subject'] = self.formdata['subject']
                        board['message'] = self.formdata['message']
                        switchBoard(self.formdata['type'])
                        board['board_type'] = self.formdata['type']
                        board['useid'] = self.formdata['useid']
                        board['slip'] = self.formdata['slip']
                        board['countrycode'] = self.formdata['countrycode']
                        if 'recyclebin' in self.formdata:
                            board['recyclebin'] = '1'
                        else:
                            board['recyclebin'] = '0'
                        if 'disable_name' in self.formdata:
                            board['disable_name'] = '1'
                        else:
                            board['disable_name'] = '0'
                        if 'disable_subject' in self.formdata:
                            board['disable_subject'] = '1'
                        else:
                            board['disable_subject'] = '0'
                        if 'secret' in self.formdata:
                            board['secret'] = '1'
                        else:
                            board['secret'] = '0'
                        if 'locked' in self.formdata:
                            board['locked'] = '1'
                        else:
                            board['locked'] = '0'
                        board['postarea_desc'] = self.formdata['postarea_desc']
                        if 'allow_noimage' in self.formdata:
                            board['allow_noimage'] = '1'
                        else:
                            board['allow_noimage'] = '0'
                        if 'allow_images' in self.formdata:
                            board['allow_images'] = '1'
                        else:
                            board['allow_images'] = '0'
                        if 'allow_image_replies' in self.formdata:
                            board['allow_image_replies'] = '1'
                        else:
                            board['allow_image_replies'] = '0'
                        if 'allow_spoilers' in self.formdata:
                            board['allow_spoilers'] = '1'
                        else:
                            board['allow_spoilers'] = '0'
                        if 'allow_oekaki' in self.formdata:
                            board['allow_oekaki'] = '1'
                        else:
                            board['allow_oekaki'] = '0'
                        if 'archive' in self.formdata:
                            board['archive'] = '1'
                        else:
                            board['archive'] = '0'
                        board['postarea_extra'] = self.formdata['postarea_extra']
                        board['force_css'] = self.formdata['force_css']

                        # Update file types
                        UpdateDb(
                            "DELETE FROM `boards_filetypes` WHERE `boardid` = %s" % board['id'])
                        for filetype in filetypelist():
                            if 'filetype'+filetype['ext'] in self.formdata:
                                UpdateDb("INSERT INTO `boards_filetypes` VALUES (%s, %s)" % (
                                    board['id'], filetype['id']))

                        try:
                            board['numthreads'] = int(
                                self.formdata['numthreads'])
                        except:
                            raise UserError(_("Max threads shown must be numeric."))

                        try:
                            board['numcont'] = int(self.formdata['numcont'])
                        except:
                            raise UserError(_("Max replies shown must be numeric."))

                        try:
                            board['numline'] = int(self.formdata['numline'])
                        except:
                            raise UserError(_("Max lines shown must be numeric."))

                        try:
                            board['thumb_px'] = int(self.formdata['thumb_px'])
                        except:
                            raise UserError(_("Max thumb dimensions must be numeric."))

                        try:
                            board['maxsize'] = int(self.formdata['maxsize'])
                        except:
                            raise UserError(_("Max size must be numeric."))

                        try:
                            board['maxage'] = int(self.formdata['maxage'])
                        except:
                            raise UserError(_("Max age must be numeric."))

                        try:
                            board['maxinactive'] = int(
                                self.formdata['maxinactive'])
                        except:
                            raise UserError(_("Max inactivity must be numeric."))

                        try:
                            board['threadsecs'] = int(
                                self.formdata['threadsecs'])
                        except:
                            raise UserError(_("Time between new threads must be numeric."))

                        try:
                            board['postsecs'] = int(self.formdata['postsecs'])
                        except:
                            raise UserError(_("Time between replies must be numeric."))

                        updateBoardSettings()
                        message = _('Board options successfully updated.') + ' <a href="' + \
                            Settings.CGI_URL+'manage/rebuild/' + \
                            board['dir']+'">'+_('Rebuild')+'</a>'
                        template_filename = "message.html"
                        logAction(staff_account['username'], _(
                            'Updated options for /%s/') % board['dir'])
                    else:
                        template_filename = "boardoptions.html"
                        template_values = {'mode': 1, 'boardopts': board, 'filetypes': filetypelist(
                        ), 'supported_filetypes': board['filetypes_ext']}
                else:
                    # List all boards
                    template_filename = "boardoptions.html"
                    template_values = {'mode': 0, 'boards': boardlist()}
            elif path_split[2] == 'recyclebin':
                if not administrator:
                    return

                message = None
                if len(path_split) > 5:
                    if path_split[4] == 'restore':
                        board = setBoard(path_split[5])

                        post = FetchOne('SELECT `parentid` FROM `posts` WHERE `boardid` = ' +
                                        board['id'] + ' AND `id` = \'' + _mysql.escape_string(path_split[6]) + '\' LIMIT 1')
                        if not post:
                            message = _(
                                'Unable to locate a post with that ID.') + '<br />'
                            template_filename = "message.html"
                        else:
                            UpdateDb('UPDATE `posts` SET `IS_DELETED` = 0 WHERE `boardid` = ' +
                                     board['id'] + ' AND `id` = \'' + _mysql.escape_string(path_split[6]) + '\' LIMIT 1')
                            if post['parentid'] != '0':
                                threadUpdated(post['parentid'])
                            else:
                                regenerateFrontPages()

                            message = _('Post successfully restored.')
                            logAction(staff_account['username'], _('Restored post %s') % (
                                '/' + path_split[5] + '/' + path_split[6]))

                    if path_split[4] == 'delete':
                        board = setBoard(path_split[5])
                        post = FetchOne('SELECT id, parentid, message, INET6_NTOA(ip) AS ip FROM `posts` WHERE `boardid` = ' +
                                        board['id'] + ' AND `id` = \'' + _mysql.escape_string(path_split[6]) + '\' LIMIT 1')
                        if not post:
                            message = _(
                                'Unable to locate a post with that ID.')
                        else:
                            deletePost(path_split[6], None)

                            if post['parentid'] != '0':
                                threadUpdated(post['parentid'])
                            else:
                                regenerateFrontPages()

                            message = "Post %s eliminado permanentemente" % ('/' + board['dir'] + '/' + post['id'])
                            logAction(staff_account['username'], message + ' desde papelera. Contenido: ' + post['message'] + ' IP: ' + post['ip'])

                # Delete more than 1 post
                if 'deleteall' in self.formdata:
                    return  # TODO
                    deleted = 0
                    for key in self.formdata:
                        if key[:2] == '!i':
                            # Board where the post is
                            dir = key[2:].split('/')[0]
                            postid = key[2:].split('/')[1]  # Post to delete

                            # Delete post start
                            post = FetchOne('SELECT `parentid`, `dir` FROM `posts` INNER JOIN `boards` ON posts.boardid = boards.id WHERE `dir` = \'' +
                                            _mysql.escape_string(dir) + '\' AND posts.id = \'' + _mysql.escape_string(postid) + '\' LIMIT 1')
                            if not post:
                                message = _(
                                    'Unable to locate a post with that ID.')
                            else:
                                board = setBoard(dir)
                                deletePost(int(postid), None)
                                if post['parentid'] != '0':
                                  threadUpdated(post['parentid'])
                                else:
                                  regenerateFrontPages()
                                deleted += 1
                            # Delete post end

                    logAction(staff_account['username'], _('Permadeleted %s post(s).') % str(deleted))
                    message = _('Permadeleted %s post(s).') % str(deleted)

                # Start
                import math
                pagesize = float(Settings.RECYCLEBIN_POSTS_PER_PAGE)

                try:
                    currentpage = int(path_split[3])
                except:
                    currentpage = 0

                skip = False
                if 'type' in self.formdata:
                    type = int(self.formdata["type"])
                else:
                    type = 0

                # Generate board list
                boards = FetchAll(
                    'SELECT `name`, `dir` FROM `boards` ORDER BY `dir`')
                for board in boards:
                    if 'board' in self.formdata and self.formdata['board'] == board['dir']:
                        board['checked'] = True
                    else:
                        board['checked'] = False

                # Get type filter
                if type != 0:
                    type_condition = "= " + str(type)
                else:
                    type_condition = "!= 0"

                # Table
                if 'board' in self.formdata and self.formdata['board'] != 'all':
                    cboard = self.formdata['board']
                    posts = FetchAll("SELECT posts.id, posts.timestamp, timestamp_formatted, IS_DELETED, INET6_NTOA(posts.ip) AS ip, posts.message, dir, boardid FROM `posts` INNER JOIN `boards` ON boardid = boards.id WHERE `dir` = '%s' AND IS_DELETED %s ORDER BY `timestamp` DESC LIMIT %d, %d" % (
                        _mysql.escape_string(self.formdata['board']), _mysql.escape_string(type_condition), currentpage*pagesize, pagesize))
                    try:
                        totals = FetchOne("SELECT COUNT(id) FROM `posts` WHERE IS_DELETED %s AND `boardid` = %s" % (
                            _mysql.escape_string(type_condition), _mysql.escape_string(posts[0]['boardid'])), 0)
                    except:
                        skip = True
                else:
                    cboard = 'all'
                    posts = FetchAll("SELECT posts.id, posts.timestamp, timestamp_formatted, IS_DELETED, INET6_NTOA(posts.ip) AS ip, posts.message, dir FROM `posts` INNER JOIN `boards` ON boardid = boards.id WHERE IS_DELETED %s ORDER BY `timestamp` DESC LIMIT %d, %d" % (
                        _mysql.escape_string(type_condition), currentpage*pagesize, pagesize))
                    totals = FetchOne("SELECT COUNT(id) FROM `posts` WHERE IS_DELETED %s" %
                                      _mysql.escape_string(type_condition), 0)

                template_filename = "recyclebin.html"
                template_values = {'message': message,
                                   'type': type,
                                   'boards': boards,
                                   'skip': skip}

                if not skip:
                    # Calculate number of pages
                    total = int(totals[0])
                    pages = int(math.ceil(total / pagesize))

                    # Create delete form
                    if 'board' in self.formdata:
                        board = self.formdata['board']
                    else:
                        board = None

                    navigator = ''
                    if currentpage > 0:
                        navigator += '<a href="'+Settings.CGI_URL+'manage/recyclebin/' + \
                            str(currentpage-1)+'?type='+str(type) + \
                            '&amp;board='+cboard+'">&lt;</a> '
                    else:
                        navigator += '&lt; '

                    for i in range(pages):
                        if i != currentpage:
                            navigator += '<a href="'+Settings.CGI_URL+'manage/recyclebin/' + \
                                str(i)+'?type='+str(type)+'&amp;board=' + \
                                cboard+'">'+str(i)+'</a> '
                        else:
                            navigator += str(i)+' '

                    if currentpage < (pages-1):
                        navigator += '<a href="'+Settings.CGI_URL+'manage/recyclebin/' + \
                            str(currentpage+1)+'?type='+str(type) + \
                            '&amp;board='+cboard+'">&gt;</a> '
                    else:
                        navigator += '&gt; '

                    template_values.update({'currentpage': currentpage,
                                            'curboard': board,
                                            'posts': posts,
                                            'navigator': navigator})
                # End recyclebin
            elif path_split[2] == 'lockboard':
                if not administrator:
                    return

                try:
                    board_dir = path_split[3]
                except:
                    board_dir = ''

                if board_dir == '':
                    template_filename = "lockboard.html"
                    template_values = {'boards': boardlist()}
            elif path_split[2] == 'boardlock':
                board = setBoard(path_split[3])
                if int(board['locked']):
                    # Si esta cerrado... abrir
                    board['locked'] = 0
                    updateBoardSettings()
                    message = _('Board opened successfully.')
                    template_filename = "message.html"
                else:
                    # Si esta abierta, cerrar
                    board['locked'] = 1
                    updateBoardSettings()
                    message = _('Board closed successfully.')
                    template_filename = "message.html"
            elif path_split[2] == 'addboard':
                if not administrator:
                    return

                action_taken = False
                board_dir = ''

                try:
                    if self.formdata['name'] != '':
                        board_dir = self.formdata['dir']
                except:
                    pass

                if board_dir != '':
                    action_taken = True
                    board_exists = FetchOne(
                        'SELECT * FROM `boards` WHERE `dir` = \'' + _mysql.escape_string(board_dir) + '\' LIMIT 1')
                    if not board_exists:
                        os.mkdir(Settings.ROOT_DIR + board_dir)
                        os.mkdir(Settings.ROOT_DIR + board_dir + '/res')
                        if not os.path.exists(Settings.IMAGES_DIR + board_dir):
                            os.mkdir(Settings.IMAGES_DIR + board_dir)
                        os.mkdir(Settings.IMAGES_DIR + board_dir + '/src')
                        os.mkdir(Settings.IMAGES_DIR + board_dir + '/thumb')
                        os.mkdir(Settings.IMAGES_DIR + board_dir + '/mobile')
                        os.mkdir(Settings.IMAGES_DIR + board_dir + '/cat')
                        if os.path.exists(Settings.ROOT_DIR + board_dir) and os.path.isdir(Settings.ROOT_DIR + board_dir):
                            UpdateDb('INSERT INTO `boards` (`dir`, `name`) VALUES (\'' + _mysql.escape_string(
                                board_dir) + '\', \'' + _mysql.escape_string(self.formdata['name']) + '\')')
                            board = setBoard(board_dir)
                            f = open(Settings.ROOT_DIR +
                                     board['dir'] + '/.htaccess', 'w')
                            try:
                                f.write('DirectoryIndex index.html')
                            finally:
                                f.close()
                            regenerateFrontPages()
                            message = _('Board added')
                            template_filename = "message.html"
                            logAction(staff_account['username'], _(
                                'Added board %s') % ('/' + board['dir'] + '/'))
                        else:
                            message = _(
                                'There was a problem while making the directories.')
                            template_filename = "message.html"
                    else:
                        message = _(
                            'There is already a board with that directory.')
                        template_filename = "message.html"

                if not action_taken:
                    template_filename = "addboard.html"
                    template_values = {}
            elif path_split[2] == 'trim':
                if not administrator:
                    return
                
                board = setBoard(path_split[3])
                trimThreads()
                self.output = "done trimming"
                return
            elif path_split[2] == 'setexpires':
                if not administrator:
                    return
                
                board = setBoard(path_split[3])
                parentid = int(path_split[4])
                days = int(path_split[5])
                t = time.time()

                expires = int(t) + (days * 86400)
                date_format = '%d/%m'
                expires_formatted = datetime.datetime.fromtimestamp(
                    expires).strftime(date_format)

                sql = "UPDATE posts SET expires = timestamp + (%s * 86400), expires_formatted = FROM_UNIXTIME((timestamp + (%s * 86400)), '%s') WHERE boardid = %s AND id = %s" % (
                    str(days), str(days), date_format, board["id"], str(parentid))
                UpdateDb(sql)

                self.output = "done " + sql
                return
            elif path_split[2] == 'fixflood':
                if not administrator:
                    return
                
                board = setBoard('zonavip')
                threads = FetchAll(
                    "SELECT * FROM posts WHERE boardid = %s AND parentid = 0 AND subject LIKE 'querido mod%%'" % board['id'])
                
                for thread in threads:
                    self.output += "%s<br>" % thread['id']
                    #deletePost(thread['id'], None)
                return
            elif path_split[2] == 'fixico':
                if not administrator:
                    return
                
                board = setBoard(path_split[3])
                
                if board['dir'] != 'noticias':
                    return

                threads = FetchAll("SELECT * FROM posts WHERE boardid = %s AND parentid = 0 AND message NOT LIKE '<img%%'" % board['id'])
                for t in threads:
                    img_src = '<img src="%s" alt="ico" /><br />' % getRandomIco()
                    newmessage = img_src + t["message"]
                    #UpdateDb("UPDATE posts SET message = '%s' WHERE boardid = %s AND id = %s" % (_mysql.escape_string(newmessage), board['id'], t['id']))

                self.output = repr(threads)
                return
            elif path_split[2] == 'fixkako':
                if not administrator:
                    return
                
                board = setBoard(path_split[3])

                threads = FetchAll(
                    'SELECT * FROM archive WHERE boardid = %s ORDER BY timestamp DESC' % board['id'])
                for item in threads:
                    t = time.time()
                    self.output += item['timestamp'] + '<br />'
                    fname = Settings.ROOT_DIR + \
                        board["dir"] + "/kako/" + \
                        str(item["timestamp"]) + ".json"
                    if os.path.isfile(fname):
                        import json
                        with open(fname) as f:
                            thread = json.load(f)
                        thread['posts'] = [
                            dict(list(zip(thread['keys'], row))) for row in thread['posts']]
                        template_fname = "txt_archive.html"

                        post_preview = cut_home_msg(
                            thread['posts'][0]['message'], 0)
                        page = renderTemplate("txt_archive.html", {"threads": [
                                              thread], "preview": post_preview}, False)
                        with open(Settings.ROOT_DIR + board["dir"] + "/kako/" + str(thread['timestamp']) + ".html", "w") as f:
                            f.write(page)

                        self.output += 'done' + str(time.time() - t) + '<br />'
                    else:
                        self.output += 'El hilo no existe.<br />'
            elif path_split[2] == 'fixexpires':
                if not administrator:
                    return
                
                board = setBoard(path_split[3])

                if int(board["maxage"]):
                    date_format = '%d/%m'
                    date_format_y = '%m/%Y'
                    if int(board["maxage"]) >= 365:
                        date_format = date_format_y
                    sql = "UPDATE posts SET expires = timestamp + (%s * 86400), expires_formatted = FROM_UNIXTIME((timestamp + (%s * 86400)), '%s') WHERE boardid = %s AND parentid = 0" % (
                        board["maxage"], board["maxage"], date_format, board["id"])
                    UpdateDb(sql)

                    alert_time = int(
                        round(int(board['maxage']) * Settings.MAX_AGE_ALERT))
                    sql = "UPDATE posts SET expires_alert = CASE WHEN UNIX_TIMESTAMP() > (expires - %d*86400) THEN 1 ELSE 0 END WHERE boardid = %s AND parentid = 0" % (alert_time,
                                                                                                                                                                        board["id"])
                    UpdateDb(sql)
                else:
                    sql = "UPDATE posts SET expires = 0, expires_formatted = '', expires_alert = 0 WHERE boardid = %s AND parentid = 0" % (
                        board["id"])
                    UpdateDb(sql)

                self.output = "done"
                return
            elif path_split[2] == 'fixid':
                if not administrator:
                    return
                
                board = setBoard(path_split[3])
                posts = FetchAll(
                    'SELECT * FROM `posts` WHERE `boardid` = %s' % board['id'])
                self.output = "total: %d<br />" % len(posts)
                for post in posts:
                    new_timestamp_formatted = formatTimestamp(
                        post['timestamp'])
                    tim = 0
                    if board["useid"] != '0':
                        new_timestamp_formatted += ' ID:' + \
                            iphash(post['ip'], '', tim, '1',
                                   False, False, False, '0')
                    self.output += "%s - %s <br />" % (
                        post['id'], new_timestamp_formatted)
                    query = "UPDATE `posts` SET timestamp_formatted = '%s' WHERE boardid = '%s' AND id = '%s'" % (
                        new_timestamp_formatted, board['id'], post['id'])
                    UpdateDb(query)
                return
            elif path_split[2] == 'fixname':
                return
                board = setBoard(path_split[3])
                #posts = FetchAll('SELECT * FROM `posts` WHERE `boardid` = %s' % board['id'])
                #posts = FetchAll('SELECT * FROM `posts` WHERE `name` LIKE \'%s\'' % '%%')
                #posts = FetchAll('SELECT * FROM `posts` WHERE `name` = \'%s\'' % path_split[4])
                new_name = board['anonymous']
                self.output = new_name + "<br />"
                for post in posts:
                    self.output += "%s<br />" % (post['id'])
                    query = "UPDATE `posts` SET `name` = '%s' WHERE boardid = '%s' AND id = '%s'" % (
                        new_name, board['id'], post['id'])
                    UpdateDb(query)
                return
            elif path_split[2] == 'setsub':
                if not administrator:
                    return
                
                board = setBoard(path_split[3])
                thread = FetchOne(
                    'SELECT * FROM `posts` WHERE `parentid` = 0 AND `boardid` = %s' % board['id'])
                subject = str(path_split[4])
                self.output = subject + "->" + thread['id'] + "<br />"
                query = "UPDATE `posts` SET `subject` = '%s' WHERE boardid = '%s' AND id = '%s'" % (
                    subject, board['id'], thread['id'])
                UpdateDb(query)
                return
            elif path_split[2] == 'fixlength':
                if not administrator:
                    return
                
                board = setBoard(path_split[3])
                threads = FetchAll(
                    'SELECT * FROM `posts` WHERE parentid = 0 AND `boardid` = %s' % board['id'])
                for t in threads:
                    length = threadNumReplies(t['id'])
                    UpdateDb('UPDATE posts SET length = %d WHERE boardid = %s AND id = %s' % (
                        length, board['id'], t['id']))

                self.output = 'done'
                return
            elif path_split[2] == 'archive':
                if not administrator:
                    return
                
                t = time.time()
                board = setBoard(path_split[3])
                postid = int(path_split[4])
                archiveThread(postid)
                self.output = "todo ok %s" % str(time.time() - t)
            elif path_split[2] == 'filters':
                action_taken = False
                if len(path_split) > 3 and path_split[3] == 'add':
                    if "add" in self.formdata:
                        edit_id = 0
                        if 'edit' in self.formdata:
                            edit_id = int(self.formdata['edit'])

                        # We decide what type of filter it is.
                        # 0: Word / 1: Name/Trip
                        filter_type = int(self.formdata["type"])
                        filter_action = int(self.formdata["action"])
                        filter_from = ''
                        filter_tripcode = ''

                        # I don't like pickles... oh well.
                        where = ''
                        if 'board_all' not in self.formdata:
                            where = []
                            boards = FetchAll('SELECT `dir` FROM `boards`')
                            for board in boards:
                                keyname = 'board_' + board['dir']
                                if keyname in self.formdata:
                                    if self.formdata[keyname] == "1":
                                        where.append(board['dir'])
                            if len(where) > 0:
                                where = _mysql.escape_string(
                                    pickle.dumps(where))
                            else:
                                self.error(
                                    _("You must select what board the filter will affect"))
                                return

                        if filter_type == 0:
                            # Word filter
                            if len(self.formdata["word"]) > 0:
                                filter_from = html.escape(self.formdata["word"])
                            else:
                                self.error(_("You must enter a word."))
                                return
                        elif filter_type == 1:
                            # Name/trip filter
                            can_add = False
                            if len(self.formdata["name"]) > 0:
                                filter_from = self.formdata["name"]
                                can_add = True
                            if len(self.formdata["trip"]) > 0:
                                filter_tripcode = self.formdata["trip"]
                                can_add = True
                            if not can_add:
                                self.error(
                                    _("You must enter a name and/or a tripcode."))
                                return

                        # Action
                        sql_query = ''
                        filter_reason = ''
                        if len(self.formdata["reason"]) > 0:
                            filter_reason = self.formdata["reason"]
                        if filter_action == 0:
                            # Cancel post
                            sql_query = "INSERT INTO `filters` (`id`, `boards`, `type`, `action`, `from`, `from_trip`, `reason`, `added`, `staff`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"
                            sql_params = (edit_id, where, filter_type, filter_action, filter_from, filter_tripcode, filter_reason, timestamp(), staff_account['username'])
                        elif filter_action == 1:
                            # Change to
                            if len(self.formdata["changeto"]) > 0:
                                filter_to = _mysql.escape_string(
                                    self.formdata["changeto"])
                                sql_query = "INSERT INTO `filters` (`id`, `boards`, `type`, `action`, `from`, `from_trip`, `reason`, `to`, `added`, `staff`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
                                sql_params = (edit_id, where, filter_type, filter_action, filter_from, filter_tripcode, filter_reason, filter_to, timestamp(), staff_account['username'])
                            else:
                                self.error(
                                    _("You must enter a word to change to."))
                                return
                        elif filter_action == 2:
                            # Ban
                            filter_seconds = '0'
                            if len(self.formdata["seconds"]) > 0:
                                filter_seconds = _mysql.escape_string(
                                    self.formdata["seconds"])
                            if "blind" in self.formdata and self.formdata["blind"] == '1':
                                filter_blind = '1'
                            else:
                                filter_blind = '2'

                            sql_query = "INSERT INTO `filters` (`id`, `boards`, `type`, `action`, `from`, `from_trip`, `reason`, `seconds`, `blind`, `added`, `staff`) VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % \
                                        (edit_id, where, str(filter_type), str(filter_action), filter_from, filter_tripcode, filter_reason,
                                         filter_seconds, filter_blind, str(timestamp()), _mysql.escape_string(staff_account['username']))
                        elif filter_action == 3:
                            # Redirect URL
                            if len(self.formdata['redirect_url']) > 0:
                                redirect_url = _mysql.escape_string(
                                    self.formdata['redirect_url'])
                                redirect_time = 0
                                try:
                                    redirect_time = int(
                                        self.formdata['redirect_time'])
                                except:
                                    pass
                            else:
                                self.error(
                                    _("You must enter a URL to redirect to."))
                                return

                            sql_query = "INSERT INTO `filters` (`id`, `boards`, `type`, `action`, `from`, `from_trip`, `reason`, `redirect_url`, `redirect_time`, `added`, `staff`) VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % \
                                        (edit_id, where, str(filter_type), str(filter_action), filter_from, filter_tripcode, filter_reason, redirect_url, str(
                                            redirect_time), str(timestamp()), _mysql.escape_string(staff_account['username']))
                        # DO QUERY!
                        if edit_id > 0:
                            UpdateDb(
                                "DELETE FROM `filters` WHERE `id` = %s" % str(edit_id))
                            UpdateDb(sql_query)
                            message = 'Filter edited.'
                        else:
                            filt = FetchOne("SELECT `id` FROM `filters` WHERE `boards` = '%s' AND `type` = '%s' AND `from` = '%s'" % (
                                where, str(filter_type), filter_from))
                            if not filt:
                                UpdateDb(sql_query)
                                message = 'Filter added.'
                            else:
                                message = 'This filter already exists here:' + ' <a href="' + \
                                    Settings.CGI_URL+'manage/filters/add?edit=' + \
                                    filt['id']+'">edit</a>'
                        action_taken = True
                        template_filename = "message.html"
                    else:
                        # Create add form
                        edit_id = 0
                        if 'edit' in self.formdata and int(self.formdata['edit']) > 0:
                            # Load values
                            edit_id = int(self.formdata['edit'])
                            filt = FetchOne(
                                "SELECT * FROM `filters` WHERE `id` = %s LIMIT 1" % str(edit_id))
                            if filt['boards'] == '':
                                where = ''
                            else:
                                where = pickle.loads(filt['boards'])
                            startvalues = {'type': filt['type'],
                                           'trip': filt['from_trip'],
                                           'where': where,
                                           'action': filt['action'],
                                           'changeto': cgi.escape(filt['to'], True),
                                           'reason': filt['reason'],
                                           'seconds': filt['seconds'],
                                           'blind': filt['blind'],
                                           'redirect_url': filt['redirect_url'],
                                           'redirect_time': filt['redirect_time'], }
                            if filt['type'] == '1':
                                startvalues['name'] = filt['from']
                                startvalues['word'] = ''
                            else:
                                startvalues['name'] = ''
                                startvalues['word'] = filt['from']
                        else:
                            startvalues = {'type': '0',
                                           'word': '',
                                           'name': '',
                                           'trip': '',
                                           'where': [],
                                           'action': '0',
                                           'changeto': '',
                                           'reason': _('Forbidden word'),
                                           'seconds': '0',
                                           'blind': '1',
                                           'redirect_url': 'http://',
                                           'redirect_time': '5'}

                        if edit_id > 0:
                            submit = "Editar Filtro"
                        else:
                            submit = "Agregar filtro"

                        action_taken = True
                        template_filename = "filters.html"
                        template_values = {'mode': 1,
                                           'edit_id': edit_id,
                                           'boards': boardlist(),
                                           'startvalues': startvalues,
                                           'submit': submit}
                elif len(path_split) > 4 and path_split[3] == 'delete':
                    delid = int(path_split[4])
                    UpdateDb(
                        "DELETE FROM `filters` WHERE id = '%s' LIMIT 1" % str(delid))
                    message = _('Deleted filter %s.') % str(delid)
                    template_filename = "message.html"
                    action_taken = True

                if not action_taken:
                    filters = FetchAll(
                        "SELECT * FROM `filters` ORDER BY `added` DESC")
                    for filter in filters:
                        if not filter['boards']:
                            filter['boards'] = _('All boards')
                        else:
                            where = pickle.loads(filter['boards'].encode('utf-8'))
                            if len(where) > 1:
                                filter['boards'] = '/' + \
                                    '/, /'.join(where) + '/'
                            else:
                                filter['boards'] = '/' + where[0] + '/'
                        if filter['type'] == 0:
                            filter['type_formatted'] = _('Word:') + ' <b>' + html.escape(filter['from']) + '</b>'
                        elif filter['type'] == 1:
                            filter['type_formatted'] = _('Name/Tripcode:')+' '
                            if filter['from']:
                                filter['type_formatted'] += '<b class="name">' + \
                                    filter['from'] + '</b>'
                            if filter['from_trip'] != '':
                                filter['type_formatted'] += '<span class="trip">' + \
                                    filter['from_trip'] + '</span>'
                        else:
                            filter['type_formatted'] = '?'
                        if filter['action'] == 0:
                            filter['action_formatted'] = _('Abort post')
                        elif filter['action'] == 1:
                            filter['action_formatted'] = _(
                                'Change to:') + ' <b>' + html.escape(filter['to']) + '</b>'
                        elif filter['action'] == 2:
                            if filter['blind'] == 1:
                                blind = _('Yes')
                            else:
                                blind = _('No')
                            filter['action_formatted'] = _('Autoban:') + '<br />' + \
                                (_('Length:')+' <i>%s</i><br />'+_('Blind:') +
                                 ' <i>%s</i>') % (filter['seconds'], blind)
                        elif filter['action'] == 3:
                            filter['action_formatted'] = (_('Redirect to:')+' %s ('+_('in %s secs')+')') % (
                                filter['redirect_url'], filter['redirect_time'])
                        else:
                            filter['action_formatted'] = '?'
                        filter['added'] = formatTimestamp(filter['added'])

                    template_filename = "filters.html"
                    template_values = {'mode': 0, 'filters': filters}
            elif path_split[2] == 'logs':
                if staff_account['rights'] not in [0, 2]:
                    return

                logs = FetchAll(
                    'SELECT * FROM `logs` ORDER BY `timestamp` DESC')
                for log in logs:
                    log['timestamp_formatted'] = formatTimestamp(
                        log['timestamp'])
                template_filename = "logs.html"
                template_values = {'logs': logs}
            elif path_split[2] == 'logout':
                message = _('Logging out...') + '<meta http-equiv="refresh" content="0;url=' + \
                    Settings.CGI_URL + 'manage" />'
                deleteCookie(self, 'weabot_manage')
                deleteSession(staff_account['session_id'])
                template_filename = "message.html"
            elif path_split[2] == 'quotes':
                # Quotes for the post screen
                if "save" in self.formdata:
                    try:
                        f = open('quotes.conf', 'w')
                        f.write(self.formdata["data"])
                        f.close()
                        message = 'Datos guardados.'
                        template_filename = "message.html"
                    except:
                        message = 'Error al guardar datos.'
                        template_filename = "message.html"
                try:
                    f = open('quotes.conf', 'r')
                    data = cgi.escape(f.read(1048576), True)
                    f.close()
                    template_filename = "quotes.html"
                    template_values = {'data': data}
                except:
                    message = 'Error al leer datos.'
                    template_filename = 'message.html'
            elif path_split[2] == 'recent_images':
                try:
                    if int(self.formdata['images']) > 100:
                        images = '100'
                    else:
                        images = self.formdata['images']
                    posts = FetchAll(
                        'SELECT * FROM `posts` INNER JOIN `boards` ON boardid = boards.id WHERE CHAR_LENGTH(`thumb`) > 0 ORDER BY `timestamp` DESC LIMIT ' + _mysql.escape_string(images))
                except:
                    posts = FetchAll(
                        'SELECT * FROM `posts` INNER JOIN `boards` ON boardid = boards.id WHERE CHAR_LENGTH(`thumb`) > 0 ORDER BY `timestamp` DESC LIMIT 10')
                template_filename = "recent_images.html"
                template_values = {'posts': posts}
            elif path_split[2] == 'news':
                if not administrator:
                    return

                type = 1
                if 'type' in self.formdata:
                    type = int(self.formdata['type'])

                if type > 2:
                    raise UserError("Tipo no soportado")

                # canal del home
                if len(path_split) > 3:
                    if path_split[3] == 'add':
                        t = datetime.datetime.now()

                        # Insertar el nuevo post
                        title = ''
                        message = self.formdata["message"].replace(
                            "\n", "<br />")

                        # Titulo
                        if 'title' in self.formdata:
                            title = self.formdata["title"]

                        # Post anonimo
                        if 'anonymous' in self.formdata and self.formdata['anonymous'] == '1':
                            to_name = "Staff ★"
                        else:
                            to_name = "%s ★" % staff_account['username']
                        timestamp_formatted = formatDate(t)
                        if type > 0:
                            timestamp_formatted = re.sub(r"\(.+", "", timestamp_formatted)
                        else:
                            timestamp_formatted = re.sub(r"\(...\)", " ", timestamp_formatted)

                        UpdateDb("INSERT INTO `news` (type, staffid, staff_name, title, message, name, timestamp, timestamp_formatted) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
                                (type, staff_account['id'], staff_account['username'], title, message, to_name, timestamp(t), timestamp_formatted))

                        regenerateNews()
                        regenerateHome()
                        message = _("Added successfully.")
                        template_filename = "message.html"
                    if path_split[3] == 'delete':
                        # Eliminar un post
                        id = int(path_split[4])
                        UpdateDb("DELETE FROM `news` WHERE id = %d AND type = %d" % (id, type))
                        regenerateNews()
                        regenerateHome()
                        message = _("Deleted successfully.")
                        template_filename = "message.html"
                else:
                    posts = FetchAll(
                        "SELECT * FROM `news` WHERE type = %d ORDER BY `timestamp` DESC" % type)
                    template_filename = "news.html"
                    template_values = {'action': type, 'posts': posts}
            elif path_split[2] == 'newschannel':
                # if not administrator:
                #  return

                if len(path_split) > 3:
                    if path_split[3] == 'add':
                        t = datetime.datetime.now()
                        # Delete old posts
                        #posts = FetchAll("SELECT `id` FROM `news` WHERE `type` = '1' ORDER BY `timestamp` DESC LIMIT "+str(Settings.MODNEWS_MAX_POSTS)+",30")
                        # for post in posts:
                        #  UpdateDb("DELETE FROM `news` WHERE id = " + post['id'] + " AND `type` = '0'")

                        # Insert new post
                        message = ''
                        try:
                            # Cut long lines
                            message = self.formdata["message"]
                            message = clickableURLs(cgi.escape(message).rstrip()[0:8000])
                            message = onlyAllowedHTML(message)
                            if Settings.USE_MARKDOWN:
                                message = markdown(message)
                            if not Settings.USE_MARKDOWN:
                                message = message.replace("\n", "<br />")
                        except:
                            pass

                        # If it's preferred to remain anonymous...
                        if 'anonymous' in self.formdata and self.formdata['anonymous'] == '1':
                            to_name = "Staff ★"
                        else:
                            to_name = "%s ★" % staff_account['username']
                        timestamp_formatted = formatDate(t)

                        UpdateDb("INSERT INTO `news` (type, staffid, staff_name, title, message, name, timestamp, timestamp_formatted) VALUES (0, %s, %s, %s, %s, %s, %s, %s)",
                            (staff_account['id'], staff_account['username'], self.formdata['title'], message, to_name, timestamp(t), timestamp_formatted))

                        message = _("Added successfully.")
                        template_filename = "message.html"
                    if path_split[3] == 'delete':
                        if not administrator:
                            # We check that if he's not admin, he shouldn't be able to delete other people's posts
                            post = FetchOne("SELECT `staffid` FROM `news` WHERE id = '" + _mysql.escape_string(path_split[4]) +"' AND type = '0'")
                            if post['staffid'] != staff_account['id']:
                                self.error(_('That post is not yours.'))
                                return

                        # Delete!
                        UpdateDb("DELETE FROM `news` WHERE id = '" + _mysql.escape_string(path_split[4]) + "' AND type = '0'")
                        message = _("Deleted successfully.")
                        template_filename = "message.html"
                else:
                    # If he's not admin, show only his own posts
                    if administrator:
                        posts = FetchAll("SELECT * FROM `news` WHERE type = '0' ORDER BY `timestamp` DESC")
                    else:
                        posts = FetchAll("SELECT * FROM `news` WHERE staffid = %s AND type = 0 ORDER BY `timestamp` DESC",
                                        (staff_account['id'],))

                    template_filename = "news.html"
                    template_values = {'action': 'newschannel', 'posts': posts}
            elif path_split[2] == 'reports':
                if not moderator:
                    return

                message = None
                import math
                pagesize = float(Settings.REPORTS_PER_PAGE)
                totals = FetchOne("SELECT COUNT(id) FROM `reports`")
                total = int(totals['COUNT(id)'])
                pages = int(math.ceil(total / pagesize))

                try:
                    currentpage = int(path_split[3])
                except:
                    currentpage = 0

                if len(path_split) > 4:
                    if path_split[4] == 'ignore':
                        # Delete report
                        UpdateDb("DELETE FROM `reports` WHERE `id` = '" +
                                 _mysql.escape_string(path_split[5])+"'")
                        message = _('Report %s ignored.') % path_split[5]
                if 'ignore' in self.formdata:
                    ignored = 0
                    if 'board' in self.formdata and self.formdata['board'] != 'all':
                        reports = FetchAll("SELECT `id` FROM `reports` WHERE `board` = '%s' ORDER BY `timestamp` DESC LIMIT %d, %d" % (
                            _mysql.escape_string(self.formdata['board']), currentpage*pagesize, pagesize))
                    else:
                        reports = FetchAll("SELECT `id` FROM `reports` ORDER BY `timestamp` DESC LIMIT %d, %d" % (
                            currentpage*pagesize, pagesize))

                    for report in reports:
                        keyname = 'i' + report['id']
                        if keyname in self.formdata:
                            # Ignore here
                            UpdateDb("DELETE FROM `reports` WHERE `id` = '" +
                                     _mysql.escape_string(report['id'])+"'")
                            ignored += 1

                    message = _('Ignored %s report(s).') % str(ignored)

                # Generate board list
                boards = FetchAll(
                    'SELECT `name`, `dir` FROM `boards` ORDER BY `dir`')
                for board in boards:
                    if 'board' in self.formdata and self.formdata['board'] == board['dir']:
                        board['checked'] = True
                    else:
                        board['checked'] = False

                # Tabla
                if 'board' in self.formdata and self.formdata['board'] != 'all':
                    reports = FetchAll("SELECT id, timestamp, timestamp_formatted, postid, parentid, link, board, INET6_NTOA(ip) AS ip, reason, INET6_NTOA(repip) AS repip FROM `reports` WHERE `board` = '%s' ORDER BY `timestamp` DESC LIMIT %d, %d" % (
                        _mysql.escape_string(self.formdata['board']), currentpage*pagesize, pagesize))
                else:
                    reports = FetchAll("SELECT id, timestamp, timestamp_formatted, postid, parentid, link, board, INET6_NTOA(ip) AS ip, reason, INET6_NTOA(repip) AS repip FROM `reports` ORDER BY `timestamp` DESC LIMIT %d, %d" % (
                        currentpage*pagesize, pagesize))

                if 'board' in self.formdata:
                    curboard = self.formdata['board']
                else:
                    curboard = None

                # for report in reports:
                #  if report['parentid'] == '0':
                #    report['link'] = Settings.BOARDS_URL + report['board'] + '/res/' + report['postid'] + '.html#' + report['postid']
                #  else:
                #    report['link'] = Settings.BOARDS_URL + report['board'] + '/res/' + report['parentid'] + '.html#' + report['postid']

                navigator = ''
                if currentpage > 0:
                    navigator += '<a href="'+Settings.CGI_URL + \
                        'manage/reports/'+str(currentpage-1)+'">&lt;</a> '
                else:
                    navigator += '&lt; '

                for i in range(pages):
                    if i != currentpage:
                        navigator += '<a href="'+Settings.CGI_URL + \
                            'manage/reports/'+str(i)+'">'+str(i)+'</a> '
                    else:
                        navigator += str(i)+' '

                if currentpage < (pages-1):
                    navigator += '<a href="'+Settings.CGI_URL + \
                        'manage/reports/'+str(currentpage+1)+'">&gt;</a> '
                else:
                    navigator += '&gt; '

                template_filename = "reports.html"
                template_values = {'message': message,
                                   'boards': boards,
                                   'reports': reports,
                                   'currentpage': currentpage,
                                   'curboard': curboard,
                                   'navigator': navigator}
            # Show by IP
            elif path_split[2] == 'ipshow':
                if not moderator:
                    return

                if 'ip' in self.formdata:
                    # If an IP was given...
                    if self.formdata['ip'] != '':
                        ip = self.formdata['ip']
                        posts = FetchAll("SELECT posts.*, boards.dir, boards.board_type, boards.subject AS default_subject FROM `posts` JOIN `boards` ON boards.id = posts.boardid WHERE ip = INET6_ATON(%s) ORDER BY posts.timestamp DESC", (ip,))
                        template_filename = "ipshow.html"
                        template_values = {"mode": 1, "ip": ip, "host": getHost(
                            ip), "country": getCountry(ip), "tor": addressIsTor(ip), "posts": posts}
                        logAction(staff_account['username'],
                                  "ipshow on {}".format(ip))
                else:
                    # Generate form
                    template_filename = "ipshow.html"
                    template_values = {"mode": 0}
            elif path_split[2] == 'ipdelete':
                if not moderator:
                    return

                # Delete by IP
                if 'ip' in self.formdata:
                    # If an IP was given...
                    if self.formdata['ip'] != '':
                        where = []
                        if 'board_all' not in self.formdata:
                            # If he chose boards separately, add them to a list
                            boards = FetchAll(
                                'SELECT `id`, `dir` FROM `boards`')
                            for board in boards:
                                keyname = 'board_' + board['dir']
                                if keyname in self.formdata:
                                    if self.formdata[keyname] == "1":
                                        where.append(board)
                        else:
                            # If all boards were selected="selected", all them all to the list
                            where = FetchAll(
                                'SELECT `id`, `dir` FROM `boards`')

                        # If no board was chosen
                        if len(where) <= 0:
                            self.error(_("Select a board first."))
                            return

                        deletedPostsTotal = 0
                        ip = self.formdata['ip']
                        deletedPosts = 0
                        for theboard in where:
                            board = setBoard(theboard['dir'])
                            isDeletedOP = False

                            # delete all starting posts first
                            op_posts = FetchAll(
                                "SELECT `id`, `message` FROM posts WHERE parentid = 0 AND boardid = '" + board['id'] + "' AND ip = INET6_ATON('" + str(ip) + "')")
                            for post in op_posts:
                                deletePost(post['id'], None)

                                deletedPosts += 1
                                deletedPostsTotal += 1

                            replies = FetchAll(
                                "SELECT `id`, `message`, `parentid` FROM posts WHERE parentid != 0 AND boardid = '" + board['id'] + "' AND ip = INET6_ATON('" + str(ip) + "')")
                            for post in replies:
                                deletePost(post['id'], None, '2')

                                deletedPosts += 1
                                deletedPostsTotal += 1

                            regenerateHome()

                            if deletedPosts > 0:
                                message = '%(posts)s post(s) were deleted from %(board)s.' % {
                                    'posts': str(deletedPosts), 'board': '/' + board['dir'] + '/'}
                                template_filename = "message.html"
                                # logAction(staff_account['username'], '%(posts)s post(s) were deleted from %(board)s. IP: %(ip)s' % \
                                #  {'posts': str(deletedPosts),
                                #   'board': '/' + board['dir'] + '/',
                                #   'ip': self.formdata['ip']})
                    else:
                        self.error(_("Please enter an IP first."))
                        return

                    message = 'In total %(posts)s from IP %(ip)s were deleted.' % {
                        'posts': str(deletedPosts), 'ip': self.formdata['ip']}
                    logAction(staff_account['username'], message)
                    template_filename = "message.html"
                else:
                    # Generate form...
                    template_filename = "ipdelete.html"
                    template_values = {'boards': boardlist()}
            elif path_split[2] == 'goto':
                board = setBoard(path_split[3])
                board_type = board['board_type']
                
                try:
                  pid = int(path_split[4])
                except ValueError:
                  raise UserError("ID no válida.")
                
                if board_type == '1':
                  first = get_parent_post(pid, board['id'])
                  url = "/" + board['dir'] + "/read/" + first['timestamp'] + "/"
                else:
                  url = "/" + board['dir'] + "/res/" + str(pid) + ".html"
                    
                self.output = '<meta http-equiv="refresh" content="0;url=%s" />' % url
            elif path_split[2] == 'fixquote':
                # when a mod deletes a post permanently messing with quote numbers
                if not administrator:
                  return

                board = setBoard(path_split[3])
                if board['board_type'] == 1:
                  return
                
                pid = int(path_split[4])
                parent = FetchOne("SELECT `parentid` FROM `posts` \
                  WHERE `id` = %s AND `boardid` = %s LIMIT 1" % (pid, board['id']))
                parent = parent['parentid']
                
                ranges = '`id` >= ' + str(pid)
                if len(path_split) > 5:
                  ranges += ' AND `id` <= ' + path_split[5]
                
                posts = FetchAll('SELECT `id`, `message` FROM `posts` \
                  WHERE `boardid` = %s AND %s AND `parentid` = %s AND \
                  `message` LIKE \'%%">&gt;&gt;%%\'' % (board['id'], ranges, parent))
                
                def fix_num(capture):
                  qnum = str(int(capture.group(2)) - 1)
                  return '/'+board['dir']+'/read/' + capture.group(1) + '/' + qnum + '">&gt;&gt;' + qnum
                
                for post in posts:
                  rx = r'/'+board['dir']+'/read/(\d+)/(\d+)">&gt;&gt;(\d+)'
                  new_msg = re.sub(rx, fix_num, post['message'])
                  self.output += post['message'] + '<hr>' + new_msg + '<hr><hr>'
                  
                  query = "UPDATE `posts` SET `message` = '%s' WHERE `boardid` = %s AND `id` = %s" % (new_msg, board['id'], post['id'])
                  UpdateDb(query)
                
                # reflect changes
                threadUpdated(parent)
            elif path_split[2] == 'search':
                if not administrator:
                    return
                search_logs = FetchAll(
                    'SELECT `id`,`timestamp`,`keyword`,`ita`,INET_NTOA(`ip`) AS `ip`,`res` FROM `search_log` ORDER BY `timestamp` DESC LIMIT 256')
                for log in search_logs:
                    #log['ip'] = str(inet_ntoa(log['ip']))
                    log['timestamp_formatted'] = formatTimestamp(log['timestamp'])
                    if log['keyword'].startswith('k '):
                        log['keyword'] = log['keyword'][2:]
                        log['archive'] = True
                    else:
                        log['archive'] = False
                template_filename = "search.html"
                template_values = {'search': search_logs}
        else:
            # Main page.
            reports = FetchOne("SELECT COUNT(1) AS 'count' FROM `reports`")["count"]
            posts = FetchAll("SELECT * FROM `news` WHERE type = 0 ORDER BY `timestamp` DESC")
            template_filename = "manage.html"
            template_values = {'reports': reports, 'posts': posts}

    if not skiptemplate:
        try:
            if template_filename == 'message.html':
                template_values = {'message': message}
        except:
            template_filename = 'message.html'
            template_values = {'message': '???'}

        template_values.update({
            'title': 'Manage',
            'validated': validated,
            'page': page,
        })

        if validated:
            template_values.update({
                'username': staff_account['username'],
                'site_title': Settings.SITE_TITLE,
                'rights': staff_account['rights'],
                'administrator': administrator,
                'added': formatTimestamp(staff_account['added']),
            })

        self.output += renderTemplate("manage/" + template_filename, template_values)


def switchBoard(new_type):
    board = Settings._.BOARD

    if new_type == board['board_type']:
        return

    kako_dir = os.path.join(Settings.ROOT_DIR, board['dir'], 'kako')
    res_dir = os.path.join(Settings.ROOT_DIR, board['dir'], 'res')

    if new_type == 0:
        # Switching to Imageboard
        # Delete kako if empty
        if os.path.exists(kako_dir) and not os.listdir(kako_dir):
            os.rmdir(kako_dir)
    elif new_type == 1:
        # Switching to Textboard
        # Make kako dir
        if not os.path.exists(kako_dir):
            os.mkdir(kako_dir)

    # Clean res dir
    cleanDir(res_dir, ext="html")


def newSession(staff_id):
    import uuid
    session_uuid = uuid.uuid4().hex
    expires = timestamp() + Settings.SESSION_TIME

    InsertDb("INSERT INTO `session` (`session_id`, `expires`, `staff_id`) VALUES (UNHEX(%s), %s, %s)",
             (session_uuid, expires, staff_id))

    return session_uuid


def validateSession(session_id):
    cleanSessions()

    session = FetchOne(
        "SELECT HEX(session_id) as session_id, id, username, rights, added FROM `session` "
        "INNER JOIN `staff` ON `session`.`staff_id` = `staff`.`id` "
        "WHERE `session_id` = UNHEX(%s)",
        (session_id,))

    if session:
        return session

    return None


def renewSession(session_id):
    expires = timestamp() + Settings.SESSION_TIME

    UpdateDb("UPDATE `session` SET expires = %s WHERE session_id = UNHEX(%s)", (expires, session_id))


def deleteSession(session_id):
    UpdateDb("DELETE FROM `session` WHERE session_id = UNHEX(%s)", (param_session_id,))


def cleanSessions():
    UpdateDb("DELETE FROM `session` WHERE expires <= %s", (timestamp(),))


def logAction(staff, action):
    InsertDb("INSERT INTO `logs` (`timestamp`, `staff`, `action`) VALUES (%s, %s, %s)",
            (timestamp(), staff, action))


def genPasswdHash(string):
    import argon2
    ph = argon2.PasswordHasher()

    return ph.hash(string)


def verifyPasswd(username, passwd):
    import argon2
    ph = argon2.PasswordHasher()

    staff_account = FetchOne(
        "SELECT * FROM staff WHERE username = %s", (username,))
    if not staff_account:
        return None

    try:
        ph.verify(staff_account['password'], passwd)
    except argon2.exceptions.VerifyMismatchError:
        return None
    except argon2.exceptions.InvalidHash:
        raise UserError("Hash obsoleto o inválido. Por favor contacte al administrador.")

    if ph.check_needs_rehash(staff_account['password']):
        param_new_hash = ph.hash(staff_acount['password'])
        UpdateDb("UPDATE staff SET password = '%s' WHERE id = %s" %
                 (param_new_hash, staff_account['id']))

    return staff_account


def boardlist():
    boards = FetchAll('SELECT * FROM `boards` ORDER BY `board_type`, `dir`')
    return boards


def filetypelist():
    filetypes = FetchAll('SELECT * FROM `filetypes` ORDER BY `ext` ASC')
    return filetypes