root / pykota / trunk / cgi-bin / printquota.cgi @ 1358

Revision 1278, 11.6 kB (checked in by jalet, 21 years ago)

Now can output the user's history on several printers at the same time.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1#! /usr/bin/python
2
3# PyKota Print Quota Reports generator
4#
5# PyKota - Print Quotas for CUPS and LPRng
6#
7# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
8# This program is free software; you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation; either version 2 of the License, or
11# (at your option) any later version.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License
19# along with this program; if not, write to the Free Software
20# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
21#
22# $Id$
23#
24# $Log$
25# Revision 1.25  2004/01/12 15:28:45  jalet
26# Now can output the user's history on several printers at the same time.
27#
28# Revision 1.24  2004/01/12 14:52:03  jalet
29# Cuts the date string
30#
31# Revision 1.23  2004/01/12 14:35:01  jalet
32# Printing history added to CGI script.
33#
34# Revision 1.22  2004/01/09 07:58:53  jalet
35# Changed URL to PyKota's logo
36#
37# Revision 1.21  2004/01/08 14:10:32  jalet
38# Copyright year changed.
39#
40# Revision 1.20  2004/01/07 16:07:17  jalet
41# The stylesheet is again expected to be local, it was a bad idea to use
42# the one on my server.
43#
44# Revision 1.19  2004/01/06 16:05:45  jalet
45# Will now search the stylesheet on my own website.
46#
47# Revision 1.18  2003/12/27 16:49:25  uid67467
48# Should be ok now.
49#
50# Revision 1.16  2003/12/02 14:40:20  jalet
51# Some code refactoring.
52# New HTML reporter added, which is now used in the CGI script for web based
53# print quota reports. It will need some de-uglyfication though...
54#
55# Revision 1.15  2003/10/24 22:06:42  jalet
56# Initial support for browser's language preference added.
57#
58# Revision 1.14  2003/10/10 19:48:07  jalet
59# Now displays version number
60#
61# Revision 1.13  2003/08/25 11:23:05  jalet
62# More powerful CGI script for quota reports
63#
64# Revision 1.12  2003/07/29 20:55:17  jalet
65# 1.14 is out !
66#
67# Revision 1.11  2003/07/01 12:37:31  jalet
68# Nicer UI
69#
70# Revision 1.10  2003/07/01 07:30:32  jalet
71# Message changed.
72#
73# Revision 1.9  2003/06/30 13:47:26  jalet
74# Allows multiple user / group names masks in the input field
75#
76# Revision 1.8  2003/06/30 13:32:01  jalet
77# Much more powerful CGI script for quota reports
78#
79# Revision 1.7  2003/06/30 12:46:15  jalet
80# Extracted reporting code.
81#
82# Revision 1.6  2003/04/23 22:13:56  jalet
83# Preliminary support for LPRng added BUT STILL UNTESTED.
84#
85# Revision 1.5  2003/04/17 21:30:09  jalet
86# Now includes the logo
87#
88# Revision 1.4  2003/04/08 21:20:25  jalet
89# CGI Script now displays a link to PyKota's website.
90#
91# Revision 1.3  2003/03/29 13:45:27  jalet
92# GPL paragraphs were incorrectly (from memory) copied into the sources.
93# Two README files were added.
94# Upgrade script for PostgreSQL pre 1.01 schema was added.
95#
96# Revision 1.2  2003/02/12 11:31:51  jalet
97# doesn't use the jaxml module anymore
98#
99# Revision 1.1  2003/02/10 13:41:38  jalet
100# repykota cgi script added.
101# cleaner doc.
102#
103
104import sys
105import os
106import cgi
107import urllib
108
109from pykota import version
110from pykota.tool import PyKotaTool, PyKotaToolError
111from pykota.reporter import PyKotaReporterError, openReporter
112
113header = """Content-type: text/html
114
115<?xml version="1.0" encoding="iso-8859-1"?>
116<html>
117  <head>
118    <title>PyKota Reports</title>
119    <link rel="stylesheet" type="text/css" href="/pykota.css" />
120  </head>
121  <body>
122    <form action="printquota.cgi" method="POST">
123      <table>
124        <tr>
125          <td>
126            <p>
127              <a href="http://www.librelogiciel.com/software/"><img src="http://www.librelogiciel.com/software/PyKota/pykota.png" alt="PyKota's Logo" /></a>
128              <br />
129              <a href="http://www.librelogiciel.com/software/">PyKota version %s</a>
130            </p>
131          </td>
132          <td colspan="2">
133            <h1>PyKota Reports</h1>
134          </td>
135        </tr>
136        <tr>
137          <td colspan="3" align="center">
138            <input type="submit" name="action" value="Report" />
139          </td>
140        </tr>
141      </table>"""
142   
143footer = """
144    </form>
145  </body>
146</html>""" 
147
148def getLanguagePreference() :
149    """Returns the preferred language."""
150    languages = os.environ.get("HTTP_ACCEPT_LANGUAGE", "")
151    langs = [l.strip().split(';')[0] for l in languages.split(",")]
152    return "%s_%s" % (langs[0], langs[0].upper())
153
154class PyKotaReportGUI(PyKotaTool) :
155    """PyKota Administrative GUI"""
156       
157    def guiDisplay(self) :
158        """Displays the administrative interface."""
159        global header, footer
160        print header % version.__version__
161        print self.body
162        print footer
163       
164    def error(self, message) :
165        """Adds an error message to the GUI's body."""
166        if message :
167            self.body = '<p><font color="red">%s</font></p>\n%s' % (message, self.body)
168       
169    def htmlListPrinters(self, selected=[], mask="*") :   
170        """Displays the printers multiple selection list."""
171        printers = self.storage.getMatchingPrinters(mask)
172        selectednames = [p.Name for p in selected]
173        message = '<table><tr><td valign="top">Printer :</td><td valign="top"><select name="printers" multiple="multiple">'
174        for printer in printers :
175            if printer.Name in selectednames :
176                message += '<option value="%s" selected="selected">%s</option>' % (printer.Name, printer.Name)
177            else :
178                message += '<option value="%s">%s</option>' % (printer.Name, printer.Name)
179        message += '</select></td></tr></table>'
180        return message
181       
182    def htmlUGNamesInput(self, value="*") :   
183        """Input field for user/group names wildcard."""
184        return 'User / Group names mask : <input type="text" name="ugmask" size="20" value="%s" /> <em>e.g. <strong>jo*</strong></em>' % (value or "*")
185       
186    def htmlGroupsCheckbox(self, isgroup=0) :
187        """Groups checkbox."""
188        if isgroup :
189            return 'Groups report : <input type="checkbox" checked="checked" name="isgroup" />'
190        else :   
191            return 'Groups report : <input type="checkbox" name="isgroup" />'
192           
193    def guiAction(self) :
194        """Main function"""
195        printers = ugmask = isgroup = None
196        self.body = "<p>Please click on the button above</p>\n"
197        if self.form.has_key("action") :
198            action = self.form["action"].value
199            if action == "Report" :
200                if self.form.has_key("printers") :
201                    printersfield = self.form["printers"]
202                    if type(printersfield) != type([]) :
203                        printersfield = [ printersfield ]
204                    printers = [self.storage.getPrinter(p.value) for p in printersfield]
205                else :   
206                    printers = self.storage.getMatchingPrinters("*")
207                remuser = os.environ.get("REMOTE_USER", "root")   
208                if remuser == "root" :
209                    if self.form.has_key("ugmask") :     
210                        ugmask = self.form["ugmask"].value
211                    else :     
212                        ugmask = "*"
213                else :       
214                    if self.form.has_key("isgroup") :   
215                        user = self.storage.getUser(remuser)
216                        if user.Exists :
217                            ugmask = " ".join([ g.Name for g in self.storage.getUserGroups(user) ])
218                        else :   
219                            ugmask = remuser # result will probably be empty, we don't care
220                    else :   
221                        ugmask = remuser
222                if self.form.has_key("isgroup") :   
223                    isgroup = 1
224                else :   
225                    isgroup = 0
226            else :
227                self.error(body, "Invalid action [%s]" % action)
228        self.body += self.htmlListPrinters(printers or [])           
229        self.body += "<br />"
230        self.body += self.htmlUGNamesInput(ugmask)
231        self.body += "<br />"
232        self.body += self.htmlGroupsCheckbox(isgroup)
233        if not self.form.has_key("history") :
234            if printers and ugmask :
235                self.reportingtool = openReporter(admin, "html", printers, ugmask.split(), isgroup)
236                self.body += "%s" % self.reportingtool.generateReport()
237        else :       
238            remuser = os.environ.get("REMOTE_USER", "root")   
239            if remuser != "root" :
240                username = remuser
241            elif self.form.has_key("username") :   
242                username = self.form["username"].value
243            else :   
244                username = None
245            if username is not None :   
246                user = self.storage.getUser(username)
247            else :   
248                user =None
249            if self.form.has_key("printername") :
250                printer = self.storage.getPrinter(self.form["printername"].value)
251            else :   
252                printer = None
253            if self.form.has_key("datelimit") :   
254                datelimit = self.form["datelimit"].value
255            else :   
256                datelimit = None
257            self.report = ["<h2>History</h2>"]   
258            history = self.storage.retrieveHistory(user, printer, datelimit)
259            if not history :
260                self.report.append("<h3>Empty</h3>")
261            else :
262                self.report.append('<table class="pykotatable" border="1">')
263                headers = ["Date", "User", "Printer", "PageCounter", "JobId", "JobSize", "JobPrice", "Copies", "Title", "Filename", "Options", "Action"]
264                self.report.append('<tr class="pykotacolsheader">%s</tr>' % "".join(["<th>%s</th>" % h for h in headers]))
265                oddeven = 0
266                for job in history :
267                    oddeven += 1
268                    if oddeven % 2 :
269                        oddevenclass = "odd"
270                    else :   
271                        oddevenclass = "even"
272                    if job.JobAction == "DENY" :
273                        oddevenclass = "deny"
274                    elif job.JobAction == "WARN" :   
275                        oddevenclass = "warn"
276                    username = '<a href="%s?%s">%s</a>' % (os.environ.get("SCRIPT_NAME", ""), urllib.urlencode({"history" : 1, "username" : job.User.Name}), job.User.Name)
277                    self.report.append('<tr class="%s">%s</tr>' % (oddevenclass, "".join(["<td>%s</td>" % h for h in (job.JobDate[:19], username, job.Printer.Name, job.PrinterPageCounter, job.JobId, job.JobSize, job.JobPrice, job.JobCopies, job.JobTitle, job.JobFileName, job.JobOptions, job.JobAction)])))
278                self.report.append('</table>')
279                dico = { "history" : 1,
280                         "datelimit" : job.JobDate,
281                       }
282                if user and user.Exists :
283                    dico.update({ "username" : user.Name })
284                if printer and printer.Exists :
285                    dico.update({ "printername" : printer.Name })
286                prevurl = "%s?%s" % (os.environ.get("SCRIPT_NAME", ""), urllib.urlencode(dico))
287                self.report.append('<a href="%s">Previous page</a>' % prevurl)
288            self.body = "\n".join(self.report)   
289           
290if __name__ == "__main__" :
291    os.environ["LC_ALL"] = getLanguagePreference()
292    admin = PyKotaReportGUI(lang=os.environ["LC_ALL"])
293    admin.form = cgi.FieldStorage()
294    admin.guiAction()
295    admin.guiDisplay()
296    try :
297        admin.storage.close()
298    except (TypeError, NameError, AttributeError) :   
299        pass
300       
301    sys.exit(0)
Note: See TracBrowser for help on using the browser.