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

Revision 1693, 14.2 kB (checked in by jalet, 20 years ago)

Fixed problem with mod_auth_ldap Apache module

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