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

Revision 2265, 13.0 kB (checked in by jerome, 19 years ago)

The destination URL for a click on the logos in CGI scripts is now
configurable.
A copyright message was added to the page's footer.

  • 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, 2005 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#
26
27import sys
28import os
29import cgi
30import urllib
31
32from pykota import version
33from pykota.tool import PyKotaTool, PyKotaToolError
34from pykota.reporter import PyKotaReporterError, openReporter
35from pykota.cgifuncs import getLanguagePreference, getCharsetPreference
36
37header = """Content-type: text/html
38
39<?xml version="1.0" encoding="%s"?>
40<html>
41  <head>
42    <title>%s</title>
43    <link rel="stylesheet" type="text/css" href="/pykota.css" />
44  </head>
45  <body>
46    <p>
47      <form action="printquota.cgi" method="POST">
48        <table>
49          <tr>
50            <td>
51              <p>
52                <a href="%s"><img src="%s?version=%s" alt="PyKota's Logo" /></a>
53                <br />
54                <a href="%s">PyKota v%s</a>
55              </p>
56            </td>
57            <td colspan="2">
58              <h1>%s</h1>
59            </td>
60          </tr>
61          <tr>
62            <td colspan="3" align="center">
63              <input type="submit" name="report" value="%s" />
64            </td>
65          </tr>
66        </table>"""
67   
68footer = """
69        <table>
70          <tr>
71            <td colspan="3" align="center">
72              <input type="submit" name="report" value="%s" />
73            </td>
74          </tr>
75        </table> 
76      </form>
77    </p>
78    <hr width="25%%" />
79    <p>
80      <font size="-2">
81        <a href="http://www.librelogiciel.com/software/">%s</a>
82        &copy; 2003, 2004, 2005 %s
83      </font>
84    </p>
85  </body>
86</html>""" 
87
88class PyKotaReportGUI(PyKotaTool) :
89    """PyKota Administrative GUI"""
90    def guiDisplay(self) :
91        """Displays the administrative interface."""
92        global header, footer
93        print header % (self.getCharset(), _("PyKota Reports"), \
94                        self.config.getLogoLink(), \
95                        self.config.getLogoURL(), version.__version__, \
96                        self.config.getLogoLink(), \
97                        version.__version__, _("PyKota Reports"), \
98                        _("Report"))
99        print self.body
100        print footer % (_("Report"), version.__doc__, version.__author__)
101       
102    def error(self, message) :
103        """Adds an error message to the GUI's body."""
104        if message :
105            self.body = '<p><font color="red">%s</font></p>\n%s' % (message, self.body)
106       
107    def htmlListPrinters(self, selected=[], mask="*") :   
108        """Displays the printers multiple selection list."""
109        printers = self.storage.getMatchingPrinters(mask)
110        selectednames = [p.Name for p in selected]
111        message = '<table><tr><td valign="top">%s :</td><td valign="top"><select name="printers" multiple="multiple">' % _("Printer")
112        for printer in printers :
113            if printer.Name in selectednames :
114                message += '<option value="%s" selected="selected">%s (%s)</option>' % (printer.Name, printer.Name, printer.Description)
115            else :
116                message += '<option value="%s">%s (%s)</option>' % (printer.Name, printer.Name, printer.Description)
117        message += '</select></td></tr></table>'
118        return message
119       
120    def htmlUGNamesInput(self, value="*") :   
121        """Input field for user/group names wildcard."""
122        return _("User / Group names mask") + (' : <input type="text" name="ugmask" size="20" value="%s" /> <em>e.g. <strong>jo*</strong></em>' % (value or "*"))
123       
124    def htmlGroupsCheckbox(self, isgroup=0) :
125        """Groups checkbox."""
126        if isgroup :
127            return _("Groups report") + ' : <input type="checkbox" checked="checked" name="isgroup" />'
128        else :   
129            return _("Groups report") + ' : <input type="checkbox" name="isgroup" />'
130           
131    def guiAction(self) :
132        """Main function"""
133        printers = ugmask = isgroup = None
134        remuser = os.environ.get("REMOTE_USER", "root")   
135        # special hack to accomodate mod_auth_ldap Apache module
136        try :
137            remuser = remuser.split("=")[1].split(",")[0]
138        except IndexError :   
139            pass
140        self.body = "<p>%s</p>\n" % _("Please click on the above button")
141        if self.form.has_key("report") :
142            if self.form.has_key("printers") :
143                printersfield = self.form["printers"]
144                if type(printersfield) != type([]) :
145                    printersfield = [ printersfield ]
146                printers = [self.storage.getPrinter(p.value) for p in printersfield]
147            else :   
148                printers = self.storage.getMatchingPrinters("*")
149            if remuser == "root" :
150                if self.form.has_key("ugmask") :     
151                    ugmask = self.form["ugmask"].value
152                else :     
153                    ugmask = "*"
154            else :       
155                if self.form.has_key("isgroup") :   
156                    user = self.storage.getUser(remuser)
157                    if user.Exists :
158                        ugmask = " ".join([ g.Name for g in self.storage.getUserGroups(user) ])
159                    else :   
160                        ugmask = remuser # result will probably be empty, we don't care
161                else :   
162                    ugmask = remuser
163            if self.form.has_key("isgroup") :   
164                isgroup = 1
165            else :   
166                isgroup = 0
167        self.body += self.htmlListPrinters(printers or [])           
168        self.body += "<br />"
169        self.body += self.htmlUGNamesInput(ugmask)
170        self.body += "<br />"
171        self.body += self.htmlGroupsCheckbox(isgroup)
172        try :
173            if not self.form.has_key("history") :
174                if printers and ugmask :
175                    self.reportingtool = openReporter(admin, "html", printers, ugmask.split(), isgroup)
176                    self.body += "%s" % self.reportingtool.generateReport()
177            else :       
178                if remuser != "root" :
179                    username = remuser
180                elif self.form.has_key("username") :   
181                    username = self.form["username"].value
182                else :   
183                    username = None
184                if username is not None :   
185                    user = self.storage.getUser(username)
186                else :   
187                    user =None
188                if self.form.has_key("printername") :
189                    printer = self.storage.getPrinter(self.form["printername"].value)
190                else :   
191                    printer = None
192                if self.form.has_key("datelimit") :   
193                    datelimit = self.form["datelimit"].value
194                else :   
195                    datelimit = None
196                if self.form.has_key("hostname") :   
197                    hostname = self.form["hostname"].value
198                else :   
199                    hostname = None
200                if self.form.has_key("billingcode") :   
201                    billingcode = self.form["billingcode"].value
202                else :   
203                    billingcode = None
204                self.report = ["<h2>%s</h2>" % _("History")]   
205                history = self.storage.retrieveHistory(user, printer, datelimit, hostname, billingcode)
206                if not history :
207                    self.report.append("<h3>%s</h3>" % _("Empty"))
208                else :
209                    self.report.append('<table class="pykotatable" border="1">')
210                    headers = [_("Date"), _("Action"), _("User"), _("Printer"), \
211                               _("Hostname"), _("JobId"), _("JobSize"), \
212                               _("JobPrice"), _("Copies"), _("JobBytes"), \
213                               _("PageCounter"), _("Title"), _("Filename"), \
214                               _("Options"), _("MD5Sum"), _("BillingCode"), \
215                               _("Pages")]
216                    self.report.append('<tr class="pykotacolsheader">%s</tr>' % "".join(["<th>%s</th>" % h for h in headers]))
217                    oddeven = 0
218                    for job in history :
219                        oddeven += 1
220                        if oddeven % 2 :
221                            oddevenclass = "odd"
222                        else :   
223                            oddevenclass = "even"
224                        if job.JobAction == "DENY" :
225                            oddevenclass = "deny"
226                        elif job.JobAction == "WARN" :   
227                            oddevenclass = "warn"
228                        username_url = '<a href="%s?%s">%s</a>' % (os.environ.get("SCRIPT_NAME", ""), urllib.urlencode({"history" : 1, "username" : job.UserName}), job.UserName)
229                        printername_url = '<a href="%s?%s">%s</a>' % (os.environ.get("SCRIPT_NAME", ""), urllib.urlencode({"history" : 1, "printername" : job.PrinterName}), job.PrinterName)
230                        if job.JobHostName :
231                            hostname_url = '<a href="%s?%s">%s</a>' % (os.environ.get("SCRIPT_NAME", ""), urllib.urlencode({"history" : 1, "hostname" : job.JobHostName}), job.JobHostName)
232                        else :   
233                            hostname_url = None
234                        if job.JobBillingCode :
235                            billingcode_url = '<a href="%s?%s">%s</a>' % (os.environ.get("SCRIPT_NAME", ""), urllib.urlencode({"history" : 1, "billingcode" : job.JobBillingCode}), job.JobBillingCode)
236                        else :   
237                            billingcode_url = None
238                        self.report.append('<tr class="%s">%s</tr>' % \
239                                              (oddevenclass, \
240                                               "".join(["<td>%s</td>" % (h or "&nbsp;") \
241                                                  for h in (job.JobDate[:19], \
242                                                            job.JobAction, \
243                                                            username_url, \
244                                                            printername_url, \
245                                                            hostname_url, \
246                                                            job.JobId, \
247                                                            job.JobSize, \
248                                                            job.JobPrice, \
249                                                            job.JobCopies, \
250                                                            job.JobSizeBytes, \
251                                                            job.PrinterPageCounter, \
252                                                            job.JobTitle, \
253                                                            job.JobFileName, \
254                                                            job.JobOptions, \
255                                                            job.JobMD5Sum, \
256                                                            billingcode_url, \
257                                                            job.JobPages)])))
258                    self.report.append('</table>')
259                    dico = { "history" : 1,
260                             "datelimit" : job.JobDate,
261                           }
262                    if user and user.Exists :
263                        dico.update({ "username" : user.Name })
264                    if printer and printer.Exists :
265                        dico.update({ "printername" : printer.Name })
266                    if hostname :   
267                        dico.update({ "hostname" : hostname })
268                    prevurl = "%s?%s" % (os.environ.get("SCRIPT_NAME", ""), urllib.urlencode(dico))
269                    self.report.append('<a href="%s">%s</a>' % (prevurl, _("Previous page")))
270                self.body = "\n".join(self.report)   
271        except :
272                self.body += '<p><font color="red">%s</font></p>' % self.crashed("CGI Error").replace("\n", "<br />")
273           
274if __name__ == "__main__" :
275    os.environ["LC_ALL"] = getLanguagePreference()
276    admin = PyKotaReportGUI(lang=os.environ["LC_ALL"], charset=getCharsetPreference())
277    admin.deferredInit()
278    admin.form = cgi.FieldStorage()
279    admin.guiAction()
280    admin.guiDisplay()
281    try :
282        admin.storage.close()
283    except (TypeError, NameError, AttributeError) :   
284        pass
285       
286    sys.exit(0)
Note: See TracBrowser for help on using the browser.