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

Revision 1871, 14.7 kB (checked in by jalet, 20 years ago)

Small fix to the cgi script to please Freshmeat's fmII URL validator/1.1

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