~ubuntu-ru-irc/+junk/irckit

« back to all changes in this revision

Viewing changes to ubuntuhelp/ubuntubot/plugins/Encyclopedia/factoids.cgi

  • Committer: rmPIC30 at gmail
  • Date: 2010-07-13 09:08:58 UTC
  • Revision ID: rmpic30@gmail.com-20100713090858-w5kkmk093hx38cen
Добавляю бота

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
###
 
3
# Copyright (c) 2006,2007 Dennis Kaarsemaker
 
4
# Copyright (c) 2008, 2009 Terence Simpson
 
5
#
 
6
# This program is free software; you can redistribute it and/or modify
 
7
# it under the terms of version 2 of the GNU General Public License as
 
8
# published by the Free Software Foundation.
 
9
#
 
10
# This program is distributed in the hope that it will be useful,
 
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
13
# GNU General Public License for more details.
 
14
#
 
15
###
 
16
 
 
17
import sys
 
18
# This needs to be set to the location of the commoncgi.py file
 
19
sys.path.append('/var/www/bot')
 
20
from commoncgi import *
 
21
 
 
22
### Variables
 
23
NUM_PER_PAGE=50.0
 
24
# Directory containing the factoid database
 
25
datadir = '/home/bot/'
 
26
# Database filename (without the .db extention)
 
27
default_database = 'ubuntu'
 
28
 
 
29
### Nothing below this line should be edited unless you know what you're doing ###
 
30
 
 
31
databases = [x for x in os.listdir(datadir)]
 
32
 
 
33
# Initialize
 
34
database = default_database
 
35
order_by = 'popularity DESC'
 
36
page = 0
 
37
search = ''
 
38
factoids = []
 
39
total = 0
 
40
 
 
41
class Factoid:
 
42
    def __init__(self, name, value, author, added, popularity):
 
43
        self.name, self.value, self._author, self._added, self.popularity = (name, value, author, added, popularity)
 
44
 
 
45
    @property
 
46
    def author(self):
 
47
        if '!' in self._author:
 
48
            return self._author[:self._author.find('!')]
 
49
        return self._author
 
50
 
 
51
    @property
 
52
    def added(self):
 
53
        if '.' in self._added:
 
54
            return self._added[:self._added.find('.')]
 
55
        return self._added
 
56
 
 
57
    def __iter__(self):
 
58
        yield self.name
 
59
        yield self.value
 
60
        yield self.author
 
61
        yield self.added
 
62
        yield self.popularity
 
63
 
 
64
class Log:
 
65
    def __init__(self, author, added):
 
66
        self._author, self._added = (author, added)
 
67
 
 
68
    @property
 
69
    def author(self):
 
70
        if '!' in self._author:
 
71
            return self._author[:self._author.find('!')]
 
72
        return self._author
 
73
 
 
74
    @property
 
75
    def added(self):
 
76
        if '.' in self._added:
 
77
            return self._added[:self._added.find('.')]
 
78
        return self._added
 
79
 
 
80
# Read POST
 
81
if 'db' in form:
 
82
    database = form['db'].value
 
83
if database not in databases:
 
84
    database = default_database
 
85
con = sqlite.connect(os.path.join(datadir, database + '.db'))
 
86
cur = con.cursor()
 
87
 
 
88
try: page = int(form['page'].value)
 
89
except: pass
 
90
    
 
91
if 'order' in form:
 
92
    if form['order'].value in ('added DESC', 'added ASC', 'name DESC', 'name ASC', 'popularity DESC','popularity ASC'):
 
93
        order_by = form['order'].value
 
94
if 'search' in form:
 
95
    search = form['search'].value
 
96
    
 
97
# Select factoids
 
98
if search:
 
99
    keys = [urllib2.unquote(x.strip()) for x in search.split() if len(x.strip()) >=2][:5]
 
100
    if not keys:
 
101
        keys = ['']
 
102
    query1 = "SELECT name, value, author, added, popularity FROM facts WHERE name NOT LIKE '%-also' AND ("
 
103
    query2 = "SELECT COUNT(name) FROM facts WHERE "
 
104
    bogus = False
 
105
    for k in keys:
 
106
        k = repr('%' + k + '%')
 
107
        if bogus:
 
108
            query1 += ' OR '
 
109
            query2 += ' OR '
 
110
        query1 += "name LIKE %s OR VAlUE LIKE %s" % (k, k)
 
111
        query2 += "name LIKE %s OR VAlUE LIKE %s" % (k, k)
 
112
        bogus=True
 
113
 
 
114
    query1 += ') ORDER BY %s LIMIT %d, %d' % (order_by, NUM_PER_PAGE*page, NUM_PER_PAGE)
 
115
    cur.execute(query1)
 
116
    factoids = [Factoid(x) for x in cur.fetchall()]
 
117
    cur.execute(query2)
 
118
    total = cur.fetchall()[0][0]
 
119
else:
 
120
    cur.execute("SELECT name, value, author, added, popularity FROM facts WHERE value NOT LIKE '<alias>%%' AND name NOT LIKE '%%-also' ORDER BY %s LIMIT %d, %d" % (order_by, page*NUM_PER_PAGE, NUM_PER_PAGE))
 
121
    factoids = [Factoid(*x) for x in cur.fetchall()]
 
122
    cur.execute("""SELECT COUNT(*) FROM facts WHERE value NOT LIKE '<alias>%%'""")
 
123
    total = cur.fetchall()[0][0]
 
124
 
 
125
# Pagination links
 
126
npages = int(math.ceil(total / float(NUM_PER_PAGE)))
 
127
print '&middot;'
 
128
for i in range(npages):
 
129
    print '<a href="factoids.cgi?db=%s&search=%s&order=%s&page=%s">%d</a> &middot;' % (database, search, order_by, i, i+1)
 
130
    
 
131
print '<br />Order by<br />&middot;';
 
132
print ' <a href="factoids.cgi?db=%s&search=%s&order=%s&page=0">%s</a> &middot;' % (database, search, 'name ASC', 'Name +')
 
133
print ' <a href="factoids.cgi?db=%s&search=%s&order=%s&page=0">%s</a> &middot;' % (database, search, 'name DESC', 'Name -')
 
134
print ' <a href="factoids.cgi?db=%s&search=%s&order=%s&page=0">%s</a> &middot;' % (database, search, 'popularity ASC', 'Popularity +')
 
135
print ' <a href="factoids.cgi?db=%s&search=%s&order=%s&page=0">%s</a> &middot;' % (database, search, 'popularity DESC', 'Popularity -')
 
136
print ' <a href="factoids.cgi?db=%s&search=%s&order=%s&page=0">%s</a> &middot;' % (database, search, 'added ASC', 'Date added +')
 
137
print ' <a href="factoids.cgi?db=%s&search=%s&order=%s&page=0">%s</a> &middot;' % (database, search, 'added DESC', 'Date added -')
 
138
 
 
139
print '''
 
140
 <table cellspacing="0">
 
141
  <thead>
 
142
   <tr>
 
143
    <th style="width: 10%;">Factoid</th>
 
144
    <th style="width: 70%;">Value</th>
 
145
    <th style="width: 20%;">Author</th>
 
146
   </tr>
 
147
  </thead>
 
148
  <tbody>'''
 
149
 
 
150
url_re = re.compile('(?P<url>(https?://\S+|www\S+))')
 
151
def q(x):
 
152
    x = str(x).replace('&','&amp;').replace('<','&lt;').replace('>','&gt;').replace('\n','<br />')
 
153
    return url_re.sub(link, x)
 
154
def link(match):
 
155
    url = match.group('url')
 
156
    txt = url
 
157
    if len(txt) > 30:
 
158
        txt = txt[:20] + '&hellip;' + txt[-10:]
 
159
    return '<a href="%s">%s</a>' % (url, txt)
 
160
 
 
161
i = 0
 
162
for fact in factoids:
 
163
    name = fact.name
 
164
    cur.execute("SELECT value FROM facts WHERE name = %s", fact.name + '-also')
 
165
    more = cur.fetchall()
 
166
    if len(more):
 
167
        name += ' $hr$' + ' $hr$'.join([x[0] for x in more])
 
168
    cur.execute("SELECT name FROM facts WHERE value LIKE %s", '<alias> ' + fact.name)
 
169
    name += ' \n' + ' \n'.join([x[0] for x in cur.fetchall()])
 
170
    data = [ q(x) for x in fact ]
 
171
    cur.execute("SELECT author, added FROM log WHERE name = %s ORDER BY id DESC LIMIT 1", fact.name)
 
172
    edit = [Log(*x) for x in cur.fetchall()]
 
173
#    edit = [Log(author, added) for (author, added) in cur.fetchall()]
 
174
    if edit:
 
175
        log = edit[0]
 
176
        data[3] += "<br />Last edited by %s<br />Last modified: %s" % (q(log.author), q(log.added))
 
177
    else:
 
178
        data[3] += "<br />Never edited"
 
179
    fact.name = name
 
180
    sys.stdout.write('   <tr')
 
181
    if i % 2: sys.stdout.write(' class="bg2"')
 
182
    i += 1
 
183
    print '''>
 
184
    <td>%s</td>
 
185
    <td>%s</td>
 
186
    <td>%s<br />
 
187
        Added on: %s<br />
 
188
        Requested %s times</td>
 
189
   </tr>''' % tuple(data)
 
190
 
 
191
print '''
 
192
  </tbody>
 
193
 </table>'''
 
194
 
 
195
send_page('factoids.tmpl')