aboutsummaryrefslogtreecommitdiff
path: root/cgi/manage.py
diff options
context:
space:
mode:
Diffstat (limited to 'cgi/manage.py')
-rw-r--r--cgi/manage.py285
1 files changed, 132 insertions, 153 deletions
diff --git a/cgi/manage.py b/cgi/manage.py
index 0ad2d48..40be3b2 100644
--- a/cgi/manage.py
+++ b/cgi/manage.py
@@ -1,7 +1,7 @@
# coding=utf-8
-import _mysql
import os
import cgi
+import html
import shutil
import datetime
import logging
@@ -24,18 +24,15 @@ def manage(self, path_split):
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", 0)
+ 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', '" +
- _mysql.escape_string(genPasswdHash("admin")) + "', 0, 0)")
+ InsertDb("INSERT INTO `staff` (`username`, `password`, `added`, `rights`) VALUES ('admin', %s, 0, 0)", (genPasswdHash("admin"),))
- staff_account = verifyPasswd(
- self.formdata['username'], self.formdata['password'])
+ 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` < ' +
- str(timestamp() - Settings.MANAGE_LOG_TIME)) # three months
+ 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.')
@@ -54,12 +51,12 @@ def manage(self, path_split):
if 'session_id' in staff_account:
renewSession(staff_account['session_id'])
- if staff_account['rights'] in ['0', '1', '2']:
+ if staff_account['rights'] in [0, 1, 2]:
administrator = True
- if staff_account['rights'] == '2':
+ if staff_account['rights'] == 2:
moderator = False
- UpdateDb('UPDATE `staff` SET `lastactive` = ' + str(timestamp()
- ) + ' WHERE `id` = ' + staff_account['id'] + ' LIMIT 1')
+ UpdateDb('UPDATE `staff` SET `lastactive` = %s WHERE `id` = %s LIMIT 1',
+ (timestamp(), staff_account['id']))
if not validated:
template_filename = "login.html"
@@ -178,11 +175,11 @@ def manage(self, path_split):
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'] != "0":
+ 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 = %d OR id = %d) AND boardid = %s ORDER BY `id` ASC' % (parentid, parentid, board['id']))
+ 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:
@@ -190,11 +187,11 @@ def manage(self, path_split):
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, 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")
+ 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':
+ if staff_account['rights'] != 0:
return
action_taken = False
@@ -202,23 +199,23 @@ def manage(self, path_split):
if path_split[3] == 'add' or path_split[3] == 'edit':
member = None
member_username = ''
- member_rights = '3'
+ member_rights = 3
if path_split[3] == 'edit':
if len(path_split) > 4:
- member = FetchOne('SELECT * FROM `staff` WHERE `id` = ' + _mysql.escape_string(path_split[4]) + ' LIMIT 1')
+ 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/' + member['id']
+ action = 'edit/' + str(member['id'])
try:
if self.formdata.get('user'):
- if self.formdata['rights'] in ['0', '1', '2', '3']:
+ if self.formdata['rights'] in [0, 1, 2, 3]:
action_taken = True
- UpdateDb("UPDATE `staff` SET `username` = '" + _mysql.escape_string(
- self.formdata['user']) + "', `rights` = " + self.formdata['rights'] + " WHERE `id` = " + member['id'] + " LIMIT 1")
+ 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'], _(
@@ -231,15 +228,15 @@ def manage(self, path_split):
try:
if self.formdata.get('user') and self.formdata.get('pass'):
username_taken = FetchOne(
- 'SELECT * FROM `staff` WHERE `username` = \'' + _mysql.escape_string(self.formdata['user']) + '\' LIMIT 1')
+ 'SELECT * FROM `staff` WHERE `username` = %s LIMIT 1', (self.formdata['user'],))
if not username_taken:
- if self.formdata['rights'] in ['0', '1', '2', '3']:
+ 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 ('" + _mysql.escape_string(
- self.formdata['user']) + "', '" + _mysql.escape_string(pass_hash) + "', " + str(timestamp()) + ", " + self.formdata['rights'] + ")")
+ 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'])
@@ -301,21 +298,21 @@ def manage(self, path_split):
if not action_taken:
staff = FetchAll('SELECT * FROM `staff` ORDER BY `rights`')
for member in staff:
- if member['rights'] == '0':
+ if member['rights'] == 0:
member['rights'] = _('Super-administrator')
- elif member['rights'] == '1':
+ elif member['rights'] == 1:
member['rights'] = _('Administrator')
- elif member['rights'] == '2':
+ elif member['rights'] == 2:
member['rights'] = _('Developer')
- elif member['rights'] == '3':
+ elif member['rights'] == 3:
member['rights'] = _('Moderator')
- if member['lastactive'] != '0':
+ if member['lastactive']:
member['lastactivestamp'] = member['lastactive']
member['lastactive'] = formatTimestamp(
member['lastactive'])
else:
member['lastactive'] = _('Never')
- member['lastactivestamp'] = '0'
+ member['lastactivestamp'] = 0
template_filename = "staff.html"
template_values = {'mode': 0, 'staff': staff}
elif path_split[2] == 'delete':
@@ -562,7 +559,7 @@ def manage(self, path_split):
num += 1
# fix anchors
- for old, new in refs.iteritems():
+ for old, new in refs.items():
old_url = "/{oldboard}/res/{oldthread}.html#{oldpost}\">&gt;&gt;{oldpost}</a>".format(
oldboard=oldboard, oldthread=oldthread, oldpost=old)
@@ -685,7 +682,7 @@ def manage(self, path_split):
else:
self.error("IP o rango inválido.")
return
- except netaddr.core.AddrFormatError, e:
+ except netaddr.core.AddrFormatError as e:
self.error("Problema con el IP o rango ingresado: {}".format(e))
return
@@ -695,12 +692,12 @@ def manage(self, path_split):
else:
until = '0'
where = ''
- if 'board_all' not in self.formdata.keys():
+ 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.keys():
+ if keyname in self.formdata:
if self.formdata[keyname] == "1":
where.append(board['dir'])
if len(where) > 0:
@@ -710,7 +707,7 @@ def manage(self, path_split):
_("You must select where the ban shall be placed"))
return
- if 'edit' in self.formdata.keys():
+ if 'edit' in self.formdata:
UpdateDb("DELETE FROM `bans` WHERE `id` = '" +
_mysql.escape_string(self.formdata['edit']) + "' LIMIT 1")
"""else: # TODO : Duplicate check
@@ -732,7 +729,7 @@ def manage(self, path_split):
_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.keys():
+ if 'edit' in self.formdata:
message = _('Ban successfully edited.')
action = 'Edited ban for ' + ip
else:
@@ -753,7 +750,7 @@ def manage(self, path_split):
'seconds': '0',
'blind': '1'}
edit_id = 0
- if 'edit' in self.formdata.keys():
+ 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")
@@ -812,7 +809,7 @@ def manage(self, path_split):
if ban['boards'] == '':
ban['boards'] = _('All boards')
else:
- where = pickle.loads(ban['boards'])
+ where = pickle.loads(ban['boards'].encode('utf-8'))
if len(where) > 1:
ban['boards'] = '/' + \
'/, /'.join(where) + '/'
@@ -878,48 +875,48 @@ def manage(self, path_split):
board['useid'] = self.formdata['useid']
board['slip'] = self.formdata['slip']
board['countrycode'] = self.formdata['countrycode']
- if 'recyclebin' in self.formdata.keys():
+ if 'recyclebin' in self.formdata:
board['recyclebin'] = '1'
else:
board['recyclebin'] = '0'
- if 'disable_name' in self.formdata.keys():
+ if 'disable_name' in self.formdata:
board['disable_name'] = '1'
else:
board['disable_name'] = '0'
- if 'disable_subject' in self.formdata.keys():
+ if 'disable_subject' in self.formdata:
board['disable_subject'] = '1'
else:
board['disable_subject'] = '0'
- if 'secret' in self.formdata.keys():
+ if 'secret' in self.formdata:
board['secret'] = '1'
else:
board['secret'] = '0'
- if 'locked' in self.formdata.keys():
+ 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.keys():
+ if 'allow_noimage' in self.formdata:
board['allow_noimage'] = '1'
else:
board['allow_noimage'] = '0'
- if 'allow_images' in self.formdata.keys():
+ if 'allow_images' in self.formdata:
board['allow_images'] = '1'
else:
board['allow_images'] = '0'
- if 'allow_image_replies' in self.formdata.keys():
+ if 'allow_image_replies' in self.formdata:
board['allow_image_replies'] = '1'
else:
board['allow_image_replies'] = '0'
- if 'allow_spoilers' in self.formdata.keys():
+ if 'allow_spoilers' in self.formdata:
board['allow_spoilers'] = '1'
else:
board['allow_spoilers'] = '0'
- if 'allow_oekaki' in self.formdata.keys():
+ if 'allow_oekaki' in self.formdata:
board['allow_oekaki'] = '1'
else:
board['allow_oekaki'] = '0'
- if 'archive' in self.formdata.keys():
+ if 'archive' in self.formdata:
board['archive'] = '1'
else:
board['archive'] = '0'
@@ -930,7 +927,7 @@ def manage(self, path_split):
UpdateDb(
"DELETE FROM `boards_filetypes` WHERE `boardid` = %s" % board['id'])
for filetype in filetypelist():
- if 'filetype'+filetype['ext'] in self.formdata.keys():
+ if 'filetype'+filetype['ext'] in self.formdata:
UpdateDb("INSERT INTO `boards_filetypes` VALUES (%s, %s)" % (
board['id'], filetype['id']))
@@ -938,49 +935,49 @@ def manage(self, path_split):
board['numthreads'] = int(
self.formdata['numthreads'])
except:
- raise UserError, _("Max threads shown must be numeric.")
+ raise UserError(_("Max threads shown must be numeric."))
try:
board['numcont'] = int(self.formdata['numcont'])
except:
- raise UserError, _("Max replies shown must be numeric.")
+ raise UserError(_("Max replies shown must be numeric."))
try:
board['numline'] = int(self.formdata['numline'])
except:
- raise UserError, _("Max lines shown must be numeric.")
+ 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.")
+ raise UserError(_("Max thumb dimensions must be numeric."))
try:
board['maxsize'] = int(self.formdata['maxsize'])
except:
- raise UserError, _("Max size must be numeric.")
+ raise UserError(_("Max size must be numeric."))
try:
board['maxage'] = int(self.formdata['maxage'])
except:
- raise UserError, _("Max age must be numeric.")
+ raise UserError(_("Max age must be numeric."))
try:
board['maxinactive'] = int(
self.formdata['maxinactive'])
except:
- raise UserError, _("Max inactivity must be numeric.")
+ raise UserError(_("Max inactivity must be numeric."))
try:
board['threadsecs'] = int(
self.formdata['threadsecs'])
except:
- raise UserError, _("Time between new threads must be numeric.")
+ 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.")
+ raise UserError(_("Time between replies must be numeric."))
updateBoardSettings()
message = _('Board options successfully updated.') + ' <a href="' + \
@@ -1043,10 +1040,10 @@ def manage(self, path_split):
logAction(staff_account['username'], message + ' desde papelera. Contenido: ' + post['message'] + ' IP: ' + post['ip'])
# Delete more than 1 post
- if 'deleteall' in self.formdata.keys():
+ if 'deleteall' in self.formdata:
return # TODO
deleted = 0
- for key in self.formdata.keys():
+ for key in self.formdata:
if key[:2] == '!i':
# Board where the post is
dir = key[2:].split('/')[0]
@@ -1081,7 +1078,7 @@ def manage(self, path_split):
currentpage = 0
skip = False
- if 'type' in self.formdata.keys():
+ if 'type' in self.formdata:
type = int(self.formdata["type"])
else:
type = 0
@@ -1090,7 +1087,7 @@ def manage(self, path_split):
boards = FetchAll(
'SELECT `name`, `dir` FROM `boards` ORDER BY `dir`')
for board in boards:
- if 'board' in self.formdata.keys() and self.formdata['board'] == board['dir']:
+ if 'board' in self.formdata and self.formdata['board'] == board['dir']:
board['checked'] = True
else:
board['checked'] = False
@@ -1102,7 +1099,7 @@ def manage(self, path_split):
type_condition = "!= 0"
# Table
- if 'board' in self.formdata.keys() and self.formdata['board'] != 'all':
+ 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))
@@ -1130,7 +1127,7 @@ def manage(self, path_split):
pages = int(math.ceil(total / pagesize))
# Create delete form
- if 'board' in self.formdata.keys():
+ if 'board' in self.formdata:
board = self.formdata['board']
else:
board = None
@@ -1318,7 +1315,7 @@ def manage(self, path_split):
with open(fname) as f:
thread = json.load(f)
thread['posts'] = [
- dict(zip(thread['keys'], row)) for row in thread['posts']]
+ dict(list(zip(thread['keys'], row))) for row in thread['posts']]
template_fname = "txt_archive.html"
post_preview = cut_home_msg(
@@ -1433,9 +1430,9 @@ def manage(self, path_split):
elif path_split[2] == 'filters':
action_taken = False
if len(path_split) > 3 and path_split[3] == 'add':
- if "add" in self.formdata.keys():
+ if "add" in self.formdata:
edit_id = 0
- if 'edit' in self.formdata.keys():
+ if 'edit' in self.formdata:
edit_id = int(self.formdata['edit'])
# We decide what type of filter it is.
@@ -1447,12 +1444,12 @@ def manage(self, path_split):
# I don't like pickles... oh well.
where = ''
- if 'board_all' not in self.formdata.keys():
+ 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.keys():
+ if keyname in self.formdata:
if self.formdata[keyname] == "1":
where.append(board['dir'])
if len(where) > 0:
@@ -1466,8 +1463,7 @@ def manage(self, path_split):
if filter_type == 0:
# Word filter
if len(self.formdata["word"]) > 0:
- filter_from = _mysql.escape_string(
- cgi.escape(self.formdata["word"]))
+ filter_from = html.escape(self.formdata["word"])
else:
self.error(_("You must enter a word."))
return
@@ -1475,12 +1471,10 @@ def manage(self, path_split):
# Name/trip filter
can_add = False
if len(self.formdata["name"]) > 0:
- filter_from = _mysql.escape_string(
- self.formdata["name"])
+ filter_from = self.formdata["name"]
can_add = True
if len(self.formdata["trip"]) > 0:
- filter_tripcode = _mysql.escape_string(
- self.formdata["trip"])
+ filter_tripcode = self.formdata["trip"]
can_add = True
if not can_add:
self.error(
@@ -1491,21 +1485,18 @@ def manage(self, path_split):
sql_query = ''
filter_reason = ''
if len(self.formdata["reason"]) > 0:
- filter_reason = _mysql.escape_string(
- self.formdata["reason"])
+ 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 (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % \
- (edit_id, where, str(filter_type), str(filter_action), filter_from, filter_tripcode, filter_reason, str(
- timestamp()), _mysql.escape_string(staff_account['username']))
+ 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 (%d, '%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_to, str(
- timestamp()), _mysql.escape_string(staff_account['username']))
+ 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."))
@@ -1516,7 +1507,7 @@ def manage(self, path_split):
if len(self.formdata["seconds"]) > 0:
filter_seconds = _mysql.escape_string(
self.formdata["seconds"])
- if "blind" in self.formdata.keys() and self.formdata["blind"] == '1':
+ if "blind" in self.formdata and self.formdata["blind"] == '1':
filter_blind = '1'
else:
filter_blind = '2'
@@ -1564,7 +1555,7 @@ def manage(self, path_split):
else:
# Create add form
edit_id = 0
- if 'edit' in self.formdata.keys() and int(self.formdata['edit']) > 0:
+ if 'edit' in self.formdata and int(self.formdata['edit']) > 0:
# Load values
edit_id = int(self.formdata['edit'])
filt = FetchOne(
@@ -1627,21 +1618,20 @@ def manage(self, path_split):
filters = FetchAll(
"SELECT * FROM `filters` ORDER BY `added` DESC")
for filter in filters:
- if filter['boards'] == '':
+ if not filter['boards']:
filter['boards'] = _('All boards')
else:
- where = pickle.loads(filter['boards'])
+ 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>' + cgi.escape(filter['from']) + '</b>'
- elif filter['type'] == '1':
+ 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'] != '':
+ if filter['from']:
filter['type_formatted'] += '<b class="name">' + \
filter['from'] + '</b>'
if filter['from_trip'] != '':
@@ -1649,20 +1639,20 @@ def manage(self, path_split):
filter['from_trip'] + '</span>'
else:
filter['type_formatted'] = '?'
- if filter['action'] == '0':
+ if filter['action'] == 0:
filter['action_formatted'] = _('Abort post')
- elif filter['action'] == '1':
+ elif filter['action'] == 1:
filter['action_formatted'] = _(
- 'Change to:') + ' <b>' + cgi.escape(filter['to']) + '</b>'
- elif filter['action'] == '2':
- if filter['blind'] == '1':
+ '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':
+ elif filter['action'] == 3:
filter['action_formatted'] = (_('Redirect to:')+' %s ('+_('in %s secs')+')') % (
filter['redirect_url'], filter['redirect_time'])
else:
@@ -1672,7 +1662,7 @@ def manage(self, path_split):
template_filename = "filters.html"
template_values = {'mode': 0, 'filters': filters}
elif path_split[2] == 'logs':
- if staff_account['rights'] != '0' and staff_account['rights'] != '2':
+ if staff_account['rights'] not in [0, 2]:
return
logs = FetchAll(
@@ -1690,7 +1680,7 @@ def manage(self, path_split):
template_filename = "message.html"
elif path_split[2] == 'quotes':
# Quotes for the post screen
- if "save" in self.formdata.keys():
+ if "save" in self.formdata:
try:
f = open('quotes.conf', 'w')
f.write(self.formdata["data"])
@@ -1731,7 +1721,7 @@ def manage(self, path_split):
type = int(self.formdata['type'])
if type > 2:
- raise UserError, "Tipo no soportado"
+ raise UserError("Tipo no soportado")
# canal del home
if len(path_split) > 3:
@@ -1748,7 +1738,7 @@ def manage(self, path_split):
title = self.formdata["title"]
# Post anonimo
- if 'anonymous' in self.formdata.keys() and self.formdata['anonymous'] == '1':
+ if 'anonymous' in self.formdata and self.formdata['anonymous'] == '1':
to_name = "Staff ★"
else:
to_name = "%s ★" % staff_account['username']
@@ -1758,7 +1748,8 @@ def manage(self, path_split):
else:
timestamp_formatted = re.sub(r"\(...\)", " ", timestamp_formatted)
- UpdateDb("INSERT INTO `news` (type, staffid, staff_name, title, message, name, timestamp, timestamp_formatted) VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%d', '%s')" % (type, staff_account['id'], staff_account['username'], _mysql.escape_string(title), _mysql.escape_string(message), to_name, timestamp(t), 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()
@@ -1804,14 +1795,14 @@ def manage(self, path_split):
pass
# If it's preferred to remain anonymous...
- if 'anonymous' in self.formdata.keys() and self.formdata['anonymous'] == '1':
+ 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', '%d', '%s')" % (
- staff_account['id'], staff_account['username'], _mysql.escape_string(self.formdata['title']), _mysql.escape_string(message), to_name, timestamp(t), timestamp_formatted))
+ 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"
@@ -1832,7 +1823,8 @@ def manage(self, path_split):
if administrator:
posts = FetchAll("SELECT * FROM `news` WHERE type = '0' ORDER BY `timestamp` DESC")
else:
- posts = FetchAll("SELECT * FROM `news` WHERE staffid = '" + staff_account['id']+"' AND type = '0' ORDER BY `timestamp` DESC")
+ 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}
@@ -1858,9 +1850,9 @@ def manage(self, path_split):
UpdateDb("DELETE FROM `reports` WHERE `id` = '" +
_mysql.escape_string(path_split[5])+"'")
message = _('Report %s ignored.') % path_split[5]
- if 'ignore' in self.formdata.keys():
+ if 'ignore' in self.formdata:
ignored = 0
- if 'board' in self.formdata.keys() and self.formdata['board'] != 'all':
+ 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:
@@ -1869,7 +1861,7 @@ def manage(self, path_split):
for report in reports:
keyname = 'i' + report['id']
- if keyname in self.formdata.keys():
+ if keyname in self.formdata:
# Ignore here
UpdateDb("DELETE FROM `reports` WHERE `id` = '" +
_mysql.escape_string(report['id'])+"'")
@@ -1881,20 +1873,20 @@ def manage(self, path_split):
boards = FetchAll(
'SELECT `name`, `dir` FROM `boards` ORDER BY `dir`')
for board in boards:
- if 'board' in self.formdata.keys() and self.formdata['board'] == board['dir']:
+ if 'board' in self.formdata and self.formdata['board'] == board['dir']:
board['checked'] = True
else:
board['checked'] = False
# Tabla
- if 'board' in self.formdata.keys() and self.formdata['board'] != 'all':
+ 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.keys():
+ if 'board' in self.formdata:
curboard = self.formdata['board']
else:
curboard = None
@@ -1937,11 +1929,11 @@ def manage(self, path_split):
if not moderator:
return
- if 'ip' in self.formdata.keys():
+ 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" % _mysql.escape_string(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}
@@ -1956,17 +1948,17 @@ def manage(self, path_split):
return
# Delete by IP
- if 'ip' in self.formdata.keys():
+ if 'ip' in self.formdata:
# If an IP was given...
if self.formdata['ip'] != '':
where = []
- if 'board_all' not in self.formdata.keys():
+ 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.keys():
+ if keyname in self.formdata:
if self.formdata[keyname] == "1":
where.append(board)
else:
@@ -2032,7 +2024,7 @@ def manage(self, path_split):
try:
pid = int(path_split[4])
except ValueError:
- raise UserError, "ID no válida."
+ raise UserError("ID no válida.")
if board_type == '1':
first = get_parent_post(pid, board['id'])
@@ -2094,8 +2086,8 @@ def manage(self, path_split):
template_values = {'search': search_logs}
else:
# Main page.
- reports = FetchOne("SELECT COUNT(1) FROM `reports`", 0)[0]
- posts = FetchAll("SELECT * FROM `news` WHERE type = '0' ORDER BY `timestamp` DESC")
+ 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}
@@ -2134,12 +2126,12 @@ def switchBoard(new_type):
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':
+ 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':
+ elif new_type == 1:
# Switching to Textboard
# Make kako dir
if not os.path.exists(kako_dir):
@@ -2152,13 +2144,10 @@ def switchBoard(new_type):
def newSession(staff_id):
import uuid
session_uuid = uuid.uuid4().hex
+ expires = timestamp() + Settings.SESSION_TIME
- param_session_id = _mysql.escape_string(session_uuid)
- param_expires = timestamp() + Settings.SESSION_TIME
- param_staff_id = int(staff_id)
-
- InsertDb("INSERT INTO `session` (`session_id`, `expires`, `staff_id`) VALUES (UNHEX('%s'), %d, %d)" %
- (param_session_id, param_expires, param_staff_id))
+ InsertDb("INSERT INTO `session` (`session_id`, `expires`, `staff_id`) VALUES (UNHEX(%s), %s, %s)",
+ (session_uuid, expires, staff_id))
return session_uuid
@@ -2166,13 +2155,11 @@ def newSession(staff_id):
def validateSession(session_id):
cleanSessions()
- param_session_id = _mysql.escape_string(session_id)
- param_now = timestamp()
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')" %
- (param_session_id))
+ "WHERE `session_id` = UNHEX(%s)",
+ (session_id,))
if session:
return session
@@ -2181,29 +2168,22 @@ def validateSession(session_id):
def renewSession(session_id):
- param_session_id = _mysql.escape_string(session_id)
- param_expires = timestamp() + Settings.SESSION_TIME
+ expires = timestamp() + Settings.SESSION_TIME
- UpdateDb("UPDATE `session` SET expires = %d WHERE session_id = UNHEX('%s')" %
- (param_expires, param_session_id))
+ UpdateDb("UPDATE `session` SET expires = %s WHERE session_id = UNHEX(%s)", (expires, session_id))
def deleteSession(session_id):
- param_session_id = _mysql.escape_string(session_id)
-
- UpdateDb("DELETE FROM `session` WHERE session_id = UNHEX('%s')" %
- param_session_id)
+ UpdateDb("DELETE FROM `session` WHERE session_id = UNHEX(%s)", (param_session_id,))
def cleanSessions():
- param_now = timestamp()
-
- UpdateDb("DELETE FROM `session` WHERE expires <= %d" % param_now)
+ UpdateDb("DELETE FROM `session` WHERE expires <= %s", (timestamp(),))
def logAction(staff, action):
- InsertDb("INSERT INTO `logs` (`timestamp`, `staff`, `action`) VALUES (" + str(timestamp()) +
- ", '" + _mysql.escape_string(staff) + "\', \'" + _mysql.escape_string(action) + "\')")
+ InsertDb("INSERT INTO `logs` (`timestamp`, `staff`, `action`) VALUES (%s, %s, %s)",
+ (timestamp(), staff, action))
def genPasswdHash(string):
@@ -2217,9 +2197,8 @@ def verifyPasswd(username, passwd):
import argon2
ph = argon2.PasswordHasher()
- param_username = _mysql.escape_string(username)
staff_account = FetchOne(
- "SELECT * FROM staff WHERE username = '%s'" % param_username)
+ "SELECT * FROM staff WHERE username = %s", (username,))
if not staff_account:
return None
@@ -2228,7 +2207,7 @@ def verifyPasswd(username, passwd):
except argon2.exceptions.VerifyMismatchError:
return None
except argon2.exceptions.InvalidHash:
- raise UserError, "Hash obsoleto o inválido. Por favor contacte al administrador."
+ 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'])