root / pykota / trunk / cgi-bin / pykotme.cgi @ 3295

Revision 3295, 7.8 kB (checked in by jerome, 16 years ago)

Made the CGI scripts work again.
Moved even more functions to the utils module.
Removed the cgifuncs module, moved (and changed) content into utils.
If no output encoding defined, use UTF-8 : when wget is used to try
the CGI scripts, it doesn't set by default the accepted charset and
language headers.

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Rev
Line 
1#! /usr/bin/python
2# -*- coding: UTF-8 -*-
3
4# PyKota Print Quotes generator
5#
6# PyKota - Print Quotas for CUPS
7#
8# (c) 2003, 2004, 2005, 2006, 2007, 2008 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 3 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, see <http://www.gnu.org/licenses/>.
21#
22# $Id$
23#
24#
25
26import sys
27import os
28import cgi
29import urllib
30import cStringIO
31
32import pykota.appinit
33
34from pykota import version, utils
35from pykota.tool import PyKotaTool
36from pykota.errors import PyKotaToolError
37
38from pkpgpdls import analyzer, pdlparser
39   
40
41header = """Content-type: text/html;charset=%s
42
43<html>
44  <head>
45    <title>%s</title>
46    <link rel="stylesheet" type="text/css" href="/pykota.css" />
47  </head>
48  <body>
49    <p>
50      <form action="pykotme.cgi" method="POST" enctype="multipart/form-data">
51        <table>
52          <tr>
53            <td>
54              <p>
55                <a href="%s"><img src="%s?version=%s" alt="PyKota's Logo" /></a>
56                <br />
57                <a href="%s">PyKota v%s</a>
58              </p>
59            </td>
60            <td colspan="2">
61              <h1>%s</h1>
62            </td>
63          </tr>
64          <tr>
65            <td colspan="3" align="center">
66              <input type="submit" name="report" value="%s" />
67            </td>
68          </tr>
69        </table>"""
70   
71footer = """
72        <table>
73          <tr>
74            <td colspan="3" align="center">
75              <input type="submit" name="report" value="%s" />
76            </td>
77          </tr>
78        </table> 
79      </form>
80    </p>
81    <hr width="25%%" />
82    <p>
83      <font size="-2">
84        <a href="http://www.pykota.com/">%s</a>
85        &copy; %s %s
86        <br />
87        <pre>
88%s
89        </pre>
90      </font>
91    </p>
92  </body>
93</html>""" 
94
95class PyKotMeGUI(PyKotaTool) :
96    """PyKota Quote's Generator GUI"""
97    def guiDisplay(self) :
98        """Displays the administrative interface."""
99        global header, footer
100        content = [ header % (self.charset, _("PyKota Quotes"), \
101                        self.config.getLogoLink(), \
102                        self.config.getLogoURL(), version.__version__, \
103                        self.config.getLogoLink(), \
104                        version.__version__, _("PyKota Quotes"), \
105                        _("Quote")) ]
106        content.append(self.body)
107        content.append(footer % (_("Quote"), version.__doc__, version.__years__, version.__author__, version.__gplblurb__))
108        for c in content :
109            sys.stdout.write(c.encode(self.charset, "replace"))
110        sys.stdout.flush()
111       
112    def error(self, message) :
113        """Adds an error message to the GUI's body."""
114        if message :
115            self.body = '<p><font color="red">%s</font></p>\n%s' % (message, self.body)
116       
117    def htmlListPrinters(self, selected=[], mask="*") :   
118        """Displays the printers multiple selection list."""
119        printers = self.storage.getMatchingPrinters(mask)
120        selectednames = [p.Name for p in selected]
121        message = '<table><tr><td valign="top">%s :</td><td valign="top"><select name="printers" multiple="multiple">' % _("Printer")
122        for printer in printers :
123            if printer.Name in selectednames :
124                message += '<option value="%s" selected="selected">%s (%s)</option>' % (printer.Name, printer.Name, printer.Description)
125            else :
126                message += '<option value="%s">%s (%s)</option>' % (printer.Name, printer.Name, printer.Description)
127        message += '</select></td></tr></table>'
128        return message
129       
130    def guiAction(self) :
131        """Main function"""
132        printers = inputfile = None
133        self.body = "<p>%s</p>\n" % _("Please click on the above button")
134        if self.form.has_key("report") :
135            if self.form.has_key("printers") :
136                printersfield = self.form["printers"]
137                if type(printersfield) != type([]) :
138                    printersfield = [ printersfield ]
139                printers = [self.storage.getPrinter(p.value) for p in printersfield]
140            else :   
141                printers = self.storage.getMatchingPrinters("*")
142            if self.form.has_key("inputfile") :   
143                inputfile = self.form["inputfile"].value
144               
145        if os.environ.get("REMOTE_USER") is not None :       
146            self.body += self.htmlListPrinters(printers or [])           
147            self.body += "<br />"
148        self.body += _("Filename") + " : "
149        self.body += '<input type="file" size="64" name="inputfile" />'
150        self.body += "<br />"
151        if inputfile :
152            try :
153                parser = analyzer.PDLAnalyzer(cStringIO.StringIO(inputfile))
154                jobsize = parser.getJobSize()
155            except pdlparser.PDLParserError, msg :   
156                self.body += '<p><font color="red">%s</font></p>' % msg
157                jobsize = 0 # unknown file format ?
158            else :   
159                self.body += "<p>%s</p>" % (_("Job size : %i pages") % jobsize)
160               
161            remuser = os.environ.get("REMOTE_USER")
162            # special hack to accomodate mod_auth_ldap Apache module
163            try :
164                remuser = remuser.split("=")[1].split(",")[0]
165            except :   
166                pass
167            if not remuser :   
168                self.body += "<p>%s</p>" % _("The exact cost of a print job can only be determined for a particular user. Please retry while logged-in.")
169            else :   
170                try :   
171                    user = self.storage.getUser(remuser)
172                    if user.Exists :
173                        if user.LimitBy == "noprint" :
174                            self.body += "<p>%s</p>" % _("Your account settings forbid you to print at this time.")
175                        else :   
176                            for printer in printers :
177                                upquota = self.storage.getUserPQuota(user, printer)
178                                if upquota.Exists :
179                                    if printer.MaxJobSize and (jobsize > printer.MaxJobSize) :
180                                        msg = _("You are not allowed to print so many pages on printer %s at this time.") % printer.Name
181                                    else :   
182                                        cost = upquota.computeJobPrice(jobsize)
183                                        msg = _("Cost on printer %s : %.2f") % (printer.Name, cost)
184                                        if printer.PassThrough :
185                                            msg = "%s (%s)" % (msg, _("won't be charged, printer is in passthrough mode"))
186                                        elif user.LimitBy == "nochange" :   
187                                            msg = "%s (%s)" % (msg, _("won't be charged, your account is immutable"))
188                                    self.body += "<p>%s</p>" % msg
189                except :
190                    self.body += '<p><font color="red">%s</font></p>' % self.crashed("CGI Error").replace("\n", "<br />")
191           
192if __name__ == "__main__" :
193    utils.reinitcgilocale()
194    admin = PyKotMeGUI()
195    admin.deferredInit()
196    admin.form = cgi.FieldStorage()
197    admin.guiAction()
198    admin.guiDisplay()
199    try :
200        admin.storage.close()
201    except (TypeError, NameError, AttributeError) :   
202        pass
203       
204    sys.exit(0)
Note: See TracBrowser for help on using the browser.