#!/usr/bin/env python ### # Copyright (c) 2005-2007 Dennis Kaarsemaker # # This program is free software; you can redistribute it and/or modify # it under the terms of version 2 of the GNU General Public License as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # ### import os import sys import time import urllib # This needs to be set to the location of the commoncgi.py file sys.path.append('/var/www/bot') from commoncgi import * ### Variables db = '/home/bot/data/bans.db' num_per_page = 100 pagename = os.path.basename(sys.argv[0]) disable_anonymous = False # Set this to True to disable anonymous access t1 = time.time() con = sqlite.connect(db) cur = con.cursor() # Login check error = '' user = None # Delete old sessions try: session_timeout = int(time.time()) - (2592000 * 3) cur.execute('DELETE FROM sessions WHERE time < %d', (session_timeout,)) except: pass # Session handling if form.has_key('sess'): cookie['sess'] = form['sess'].value if cookie.has_key('sess'): sess = cookie['sess'].value try: cur.execute('SELECT user FROM sessions WHERE session_id=%s',(sess,)) user = cur.fetchall()[0][0] except: con.commit() pass if not user and disable_anonymous: print "Sorry, bantracker is not available for anonymous users
" print "Join #ubuntu-ops on irc.freenode.net to discuss bans" send_page('bans.tmpl') sys.exit(0) def urlencode(**kwargs): """Return the url options as a string, inserting additional ones if given.""" d = dict([ (i.name, i.value) for i in form.list ]) d.update(kwargs) return urllib.urlencode(d.items()) # Log if form.has_key('log'): log_id = form['log'].value plain = False mark = False mark_value = '' regex = False regex_value = '' if form.has_key('plain') and form['plain'].value.lower() in ('1', 'true', 'on'): plain = True if form.has_key('mark'): mark = True mark_value = form['mark'].value if form.has_key('regex') and form['regex'].value in ('1', 'true', 'on'): regex = True regex_value = 'checked="checked"' con = sqlite.connect(db) cur = con.cursor() cur.execute("SELECT log FROM bans WHERE id=%s", log_id) log = cur.fetchall() con.commit() con.close() if not log or not log[0] or not log[0][0]: if plain: print >> sys.stderr, '
No such log with ID: %s' % q(log_id) send_page('empty.tmpl') else: print >> sys.stderr, 'No such log with ID: %s' % q(log_id) send_page('log.tmpl') log = log[0][0] if not plain: print '
' print '
' % pagename print '
' print ' ' % q(log_id) print ' ' print ' ' % q(mark_value) print ' ' % regex_value print ' ' print '
' print ' ' print '
' print '
' pad = '
' if plain: pad = '' print '
'
    else:
        print '
' if mark: if regex: mark = re.compile(mark_value, re.I) else: escaped = re.escape(mark_value).replace('%', '.*') mark = re.compile(escaped, re.I) lines = log.splitlines() for line in lines: if plain: print q(line) elif mark: if mark.search(line): print ' %s%s' % (q(line), pad) else: print " %s%s" % (q(line), pad) else: print ' %s%s' % (q(line), pad) if plain: print '
' send_page('empty.tmpl') print '

' print '
' print '
' % pagename print '
' print ' Add a comment' print '
' print ' ' % log_id print ' ' print '
' print '
' print '
' send_page('log.tmpl') # Main page # Process comments if form.has_key('comment') and form.has_key('comment_id') and user: cur.execute('SELECT ban_id FROM comments WHERE ban_id=%s and comment=%s', (form['comment_id'].value, form['comment'].value)) comm = cur.fetchall() if not len(comm): cur.execute('INSERT INTO comments (ban_id, who, comment, time) VALUES (%s, %s, %s, %s)', (form['comment_id'].value,user,form['comment'].value,pickle.dumps(datetime.datetime.now(pytz.UTC)))) con.commit() # Write the page print '
' % pagename # Personal data print '
' if user: print 'Logged in as: %s
' % user print 'Timezone: ' if form.has_key('tz') and form['tz'].value in pytz.common_timezones: tz = form['tz'].value elif cookie.has_key('tz') and cookie['tz'].value in pytz.common_timezones: tz = cookie['tz'].value else: tz = 'UTC' cookie['tz'] = tz print '' print '' print '
' print '
' tz = pytz.timezone(tz) haveQuery = form.has_key('query') or form.has_key('channel') or form.has_key('operator') def isOn(k): default = not haveQuery if not form.has_key(k): return default if form[k].value.lower() in ('on', '1', 'true', 'yes'): return True if form[k].value.lower() in ('off', '0', 'false', 'no'): return False return default def makeInput(name, label, before=False, type="checkbox", extra=''): if before: print '' % (name, label) value = '' if type == "checkbox": if isOn(name): value = ' checked="checked"' else: if form.has_key(name): value = ' value="%s"' % form[name].value, print ' %s' \ % (type, name, name, value, extra) if not before: print '' % (name, label) print '
' # Search form print '' # Select and filter bans def getBans(id=None, mask=None, kicks=True, oldbans=True, bans=True, floodbots=True, operator=None, channel=None, limit=None, offset=0, withCount=False): sql = "SELECT channel, mask, operator, time, removal, removal_op, id FROM bans" args = [] where = [] if id: where.append("id = %s") args.append(id) if mask: where.append("mask LIKE %s") args.append('%' + mask + '%') if not floodbots: where.append("operator NOT LIKE 'floodbot%%'") if operator: where.append("operator LIKE %s") args.append(operator) if channel: where.append("channel LIKE %s") args.append(channel) if not kicks: where.append("mask LIKE '%%!%%'") if not (oldbans or bans): where.append("mask NOT LIKE '%%!%%'") else: if kicks: s = "(mask NOT LIKE '%%%%!%%%%' OR (mask LIKE '%%%%!%%%%' AND %s))" else: s = "%s" if not oldbans: where.append(s % "removal IS NULL") elif not bans: where.append(s % "removal IS NOT NULL") if where: where = " WHERE " + " AND ".join(where) else: where = '' count = None if withCount: sql_count = "SELECT count(*) FROM bans%s" % where cur.execute(sql_count, args) count = int(cur.fetchall()[0][0]) sql += where sql += " ORDER BY id DESC" if limit: sql += " LIMIT %s OFFSET %s" % (limit, offset) #print sql, "
" #print sql_count, "
" #print args, "
" cur.execute(sql, args) bans = cur.fetchall() if withCount: return bans, count return bans def filterMutes(item): if item[1][0] == '%': return False return True def getQueryTerm(query, term): if term[-1] != ':': term += ':' if term in query: idx = query.index(term) + len(term) ret = query[idx:].split(None, 1)[0] query = query.replace(term + ret, '', 1).strip() return (query, ret) return (query, None) page = 0 if form.has_key('page'): page = int(form['page'].value) bans = [] ban_count = 0 query = oper = chan = None if form.has_key('query'): query = form['query'].value if query and query.isdigit(): bans = getBans(id=int(query)) ban_count = len(bans) if not bans: if form.has_key('channel'): chan = form['channel'].value if form.has_key('operator'): oper = form['operator'].value bans, ban_count = getBans(mask=query, kicks=isOn('kicks'), oldbans=isOn('oldbans'), bans=isOn('bans'), floodbots=isOn('floodbots'), operator=oper, channel=chan, limit=num_per_page, offset=num_per_page * page, withCount=True) if not form.has_key('mutes'): bans = filter(lambda x: filterMutes(x), bans) # Sort the bans def _sortf(x1,x2,field): if x1[field] < x2[field]: return -1 if x1[field] > x2[field]: return 1 return 0 if form.has_key('sort'): try: field = int(form['sort'].value) except: pass else: if field in (0,1,2,6,10,11,12,16): bans.sort(lambda x1,x2: _sortf(x1,x2,field%10)) if field >= 10: bans.reverse() if 'query' in form or 'operator' in form or 'channel' in form: if not ban_count: print '
Nothing found.
' elif ban_count == 1: print '
Found one match.
' else: print '
Found %s matches.
' % ban_count # Pagination if bans: print '
' print '·' num_pages = int(math.ceil(ban_count / float(num_per_page))) for i in range(num_pages): print '%d ·' % (pagename, urlencode(page=i), i + 1) print '
' else: # nothign to show print '
' # if I don't print this the page is messed up. send_page('bans.tmpl') sys.exit(0) # Empty log div, will be filled with AJAX print '
 
' # Main bans table # Table heading print '
' print '' print '' print '' for h in [['Channel',0, 45], ['Nick/Mask',1, 25], ['Operator',2, 0], ['Time',6, 15]]: # Negative integers for backwards searching try: v = int(form['sort'].value) if v < 10: h[1] += 10 except: pass print '' % (pagename, h[2], h[1], h[0]) print '' print '' print '' print '' print '' # And finally, display them! i = 0 for b in bans: if i % 2: print '' else: print "" # Channel print '' % (b[6],'',b[0]) # Mask print '' # Operator print '' # Time print '' # Log link print """""" % (b[6], b[6], pagename, b[6]) # ID print '' % (b[6], b[6]) print "" # Comments if i % 2: print '' else: print "" cur.execute('SELECT who, comment, time FROM comments WHERE ban_id = %d', (b[6],)) comments = cur.fetchall() if len(comments) == 0: print '' i += 1 print '
%sLogID
%s %s%s' % (b[6], b[1]) # Ban removal if b[4]: print '
(Removed)' print'
%s' % (b[6], b[2]) if b[4]: # Ban removal print u'
%s' % b[5] print '
%s' % (b[6], pickle.loads(b[3]).astimezone(tz).strftime("%b %d %Y %H:%M:%S")) if b[4]: # Ban removal print '
%s' % pickle.loads(b[4]).astimezone(tz).strftime("%b %d %Y %H:%M:%S") print '
Show log inline | full %d
' print '' % b[6] print '(No comments) ' else: print '' % b[6] print '' % b[6] for c in comments: print q(c[1]).replace('\n', '
') print u'
%s, %s

' % \ (c[0],pickle.loads(c[2]).astimezone(tz).strftime("%b %d %Y %H:%M:%S")) if user: print """Add comment""" % b[6] print """""" print '
' t2 = time.time() print "Generated in %.4f seconds
" % (t2 - t1) # Aaaaaaaaaaaaaaaaand send! send_page('bans.tmpl')