root / pykota / trunk / cgi-bin / dumpykota.cgi @ 2631

Revision 2630, 8.8 kB (checked in by jerome, 19 years ago)

Fixed a variable used before assignment problem when garbage data was feed to the program.

  • 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, 2006 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22#
23# $Id$
24#
25#
26
27import sys
28import os
29import cgi
30import urllib
31
32from pykota import version
33from pykota.tool import PyKotaToolError
34from pykota.dumper import DumPyKota
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="dumpykota.cgi" method="GET">
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        <p>
68          %s
69        </p>"""
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.librelogiciel.com/software/">%s</a>
85        &copy; %s %s
86        <br />
87        <pre>
88%s
89        </pre>
90      </font>
91    </p>
92  </body>
93</html>""" 
94
95class PyKotaDumperGUI(DumPyKota) :
96    """PyKota Dumper GUI"""
97    def guiDisplay(self) :
98        """Displays the dumper interface."""
99        global header, footer
100        print header % (self.getCharset(), _("PyKota Data Dumper"), \
101                        self.config.getLogoLink(), \
102                        self.config.getLogoURL(), version.__version__, \
103                        self.config.getLogoLink(), \
104                        version.__version__, _("PyKota Data Dumper"), \
105                        _("Dump"), _("Please click on the above button"))
106        print self.htmlListDataTypes(self.options.get("data", ""))
107        print "<br />"
108        print self.htmlListFormats(self.options.get("format", ""))
109        print "<br />"
110        print self.htmlFilterInput(" ".join(self.arguments))
111        print "<br />"
112        print self.htmlSumCheckbox(self.options.get("sum", ""))
113        print footer % (_("Dump"), version.__doc__, version.__years__, version.__author__, version.__gplblurb__)
114       
115    def htmlListDataTypes(self, selected="") :   
116        """Displays the datatype selection list."""
117        message = '<table><tr><td valign="top">%s :</td><td valign="top"><select name="datatype">' % _("Data Type")
118        for dt in self.validdatatypes.items() :
119            if dt[0] == selected :
120                message += '<option value="%s" selected="selected">%s (%s)</option>' % (dt[0], dt[0], dt[1])
121            else :
122                message += '<option value="%s">%s (%s)</option>' % (dt[0], dt[0], dt[1])
123        message += '</select></td></tr></table>'
124        return message
125       
126    def htmlListFormats(self, selected="") :   
127        """Displays the formats selection list."""
128        message = '<table><tr><td valign="top">%s :</td><td valign="top"><select name="format">' % _("Output Format")
129        for fmt in self.validformats.items() :
130            if fmt[0] == selected :
131                message += '<option value="%s" selected="selected">%s (%s)</option>' % (fmt[0], fmt[0], fmt[1])
132            else :
133                message += '<option value="%s">%s (%s)</option>' % (fmt[0], fmt[0], fmt[1])
134        message += '</select></td></tr></table>'
135        return message
136       
137    def htmlFilterInput(self, value="") :   
138        """Input the optional dump filter."""
139        return _("Filter") + (' : <input type="text" name="filter" size="40" value="%s" /> <em>e.g. <strong>username=jerome printername=HP2100</strong></em>' % (value or ""))
140       
141    def htmlSumCheckbox(self, checked="") :   
142        """Input the optional Sum option."""
143        return _("Summarize") + (' : <input type="checkbox" name="sum" %s /> <em>%s</em>' % ((checked and 'checked="checked"'), _("only for payments or history")))
144       
145    def guiAction(self) :
146        """Main function"""
147        try :
148            wantreport = self.form.has_key("report")
149        except TypeError :   
150            pass # WebDAV request probably, seen when trying to open a csv file in OOo
151        else :   
152            if wantreport :
153                try :
154                    if self.form.has_key("datatype") :
155                        self.options["data"] = self.form["datatype"].value
156                    if self.form.has_key("format") :
157                        self.options["format"] = self.form["format"].value
158                    if self.form.has_key("filter") :   
159                        self.arguments = self.form["filter"].value.split()
160                    if self.form.has_key("sum") :   
161                        self.options["sum"] = self.form["sum"].value
162                    # when no authentication is done, or when the remote username   
163                    # is 'root' (even if not run as root of course), then unrestricted
164                    # dump is allowed.
165                    remuser = os.environ.get("REMOTE_USER", "root")   
166                    # special hack to accomodate mod_auth_ldap Apache module
167                    try :
168                        remuser = remuser.split("=")[1].split(",")[0]
169                    except IndexError :   
170                        pass
171                    if remuser != "root" :
172                        # non-'root' users when the script is password protected
173                        # can not dump any data as they like, we restrict them
174                        # to their own datas.
175                        if self.options["data"] not in ["printers", "pmembers", "groups", "gpquotas"] :
176                            self.arguments.append("username=%s" % remuser)
177                       
178                    fname = "error"   
179                    ctype = "text/plain"
180                    if self.options["format"] in ("csv", "ssv") :
181                        #ctype = "application/vnd.sun.xml.calc"     # OpenOffice.org
182                        ctype = "text/comma-separated-values"
183                        fname = "dump.csv"
184                    elif self.options["format"] == "tsv" :
185                        #ctype = "application/vnd.sun.xml.calc"     # OpenOffice.org
186                        ctype = "text/tab-separated-values"
187                        fname = "dump.tsv"
188                    elif self.options["format"] == "xml" :
189                        ctype = "text/xml"
190                        fname = "dump.xml"
191                    elif self.options["format"] == "cups" :
192                        ctype = "text/plain"
193                        fname = "page_log"
194                    print "Content-type: %s" % ctype   
195                    print "Content-disposition: attachment; filename=%s" % fname
196                    print
197                    self.main(self.arguments, self.options, restricted=0)
198                except :
199                    print 'Content-type: text/html\n\n<html><head><title>CGI Error</title></head><body><p><font color="red">%s</font></p></body></html>' % self.crashed("CGI Error").replace("\n", "<br />")
200            else :       
201                self.guiDisplay()
202           
203if __name__ == "__main__" :
204    os.environ["LC_ALL"] = getLanguagePreference()
205    admin = PyKotaDumperGUI(lang=os.environ["LC_ALL"], charset=getCharsetPreference())
206    admin.deferredInit()
207    admin.form = cgi.FieldStorage()
208    admin.options = { "output" : "-",
209                "data" : "history",
210                "format" : "cups",
211                "sum" : None,
212              }
213    admin.arguments = []
214    admin.guiAction()
215    try :
216        admin.storage.close()
217    except (TypeError, NameError, AttributeError) :   
218        pass
219       
220    sys.exit(0)
Note: See TracBrowser for help on using the browser.