#!/usr/bin/python
import sqlite
import datetime
import cgi, cgitb
from math import ceil
import re
cgitb.enable
NUM_PER_PAGE=50.0
buf = ''
def out(txt):
global buf
buf += str(txt)
def link(match):
url = match.group('url')
txt = url
if len(txt) > 30:
txt = txt[:20] + '…' + txt[-10:]
return '%s' % (url, txt)
def q(txt):
txt = str(txt).replace('&','&').replace('<','<').replace('>','>').replace('"','"').replace('\n','
').replace('$hr$','
')
# linkify
rx = re.compile('(?P(https?://\S+|www\S+))')
return rx.sub(link, txt)
database = 'ubuntu'
form = cgi.FieldStorage()
if 'db' in form:
database = form['db'].value
try:
page = int(form['page'].value)
except:
page = 0
order_by = 'added DESC'
try:
order_by = form['order'].value
if order_by not in ('added DESC', 'added ASC', 'name DESC', 'name ASC', 'popularity DESC','popularity ASC'):
order_by = 'added DESC'
except:
order_by = 'added DESC'
con = sqlite.connect('/home/dennis/ubugtu/data/facts/%s.db' % database)
cur = con.cursor()
if 'search' not in form:
cur.execute("""SELECT COUNT(*) FROM facts WHERE value NOT LIKE '%%'""")
num = cur.fetchall()[0][0]
npages = int(ceil(num / float(NUM_PER_PAGE)))
out('·')
for i in range(npages):
out(' %d ·' % (database, order_by, i, i+1))
out('
Order by
·')
out(' %s ·' % (database, 'name ASC', page, 'Name +'))
out(' %s ·' % (database, 'name DESC', page, 'Name -'))
out(' %s ·' % (database, 'popularity ASC', page, 'Popularity +'))
out(' %s ·' % (database, 'popularity DESC', page, 'Popularity -'))
out(' %s ·' % (database, 'added ASC', page, 'Date added +'))
out(' %s ·' % (database, 'added DESC', page, 'Date added -'))
out('Factoid | Value | Author |
')
if 'search' in form:
keys = form['search'].value.split()[:5]
ret = {}
for k in keys:
k = k.replace("'","\'")
cur.execute("SELECT name, value, author, added, popularity FROM facts WHERE name LIKE '%%%s%%' OR VAlUE LIKE '%%%s%%'" % (k, k))
res = cur.fetchall()
for r in res:
r0 = r[0]
try:
ret[r][1] += 1
except:
ret[r0] = (r, 1)
keys = sorted(ret.keys(), lambda x, y: cmp(ret[x][1], ret[y][1]))
factoids = []
for k in keys[:50]:
factoids.append(ret[k][0])
else:
cur.execute("SELECT name, value, author, added, popularity FROM facts WHERE value NOT LIKE '%%' AND name NOT LIKE '%%-also' ORDER BY %s LIMIT %d, %d" % (order_by, page*NUM_PER_PAGE, NUM_PER_PAGE))
factoids = cur.fetchall()
i = 0
for f in factoids:
f = list(f)
cur.execute("SELECT value FROM facts WHERE name = %s", f[0] + '-also')
more = cur.fetchall()
if len(more):
f[1] += ' $hr$' + ' $hr$'.join([x[0] for x in more])
cur.execute("SELECT name FROM facts WHERE value LIKE %s", ' ' + f[0])
f[0] += ' \n' + ' \n'.join([x[0] for x in cur.fetchall()])
out('%s | %s | %s Added on: %s Requested %s times | ' % tuple([q(x) for x in f]))
out('
')
print "Content-Type: text/html; charset=UTF-8"
print ""
fd = open('factoids.tmpl')
tmpl = fd.read()
fd.close()
print tmpl % (buf)