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

Revision 2017, 14.4 kB (checked in by jalet, 19 years ago)

Move some functions outside of the CGI to allow their use in other CGI scripts

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