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

Revision 1620, 13.6 kB (checked in by jalet, 20 years ago)

Missing translation in CGI script

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