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

Revision 3032, 9.7 kB (checked in by jerome, 18 years ago)

Added some javascript form validation code to avoid common mistakes
and incompatibilities between output format and data type.

  • 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    <script type="text/javascript">
45    <!--
46      function checkvalues()
47      {
48          if ((document.mainform.format.value == "cups") && (document.mainform.datatype.value != "history"))
49          {
50              alert("Output format and data type are incompatible.");
51              return false;
52          }
53         
54          if (document.mainform.sum.checked && (document.mainform.datatype.value != "payments") && (document.mainform.datatype.value != "history"))
55          {
56              alert("Summarize is only possible for History and Payments.");
57              return false;
58          }
59         
60          if (document.mainform.sum.checked && (document.mainform.format.value == "cups"))
61          {
62              alert("Summarize is not possible with CUPS' page_log format.");
63              return false;
64          }
65         
66          return true;
67      }
68    //-->
69    </script>
70  </head>
71  <body>
72    <p>
73      <form action="dumpykota.cgi" method="GET" name="mainform" onsubmit="return checkvalues()">
74        <table>
75          <tr>
76            <td>
77              <p>
78                <a href="%s"><img src="%s?version=%s" alt="PyKota's Logo" /></a>
79                <br />
80                <a href="%s">PyKota v%s</a>
81              </p>
82            </td>
83            <td colspan="2">
84              <h1>%s</h1>
85            </td>
86          </tr>
87          <tr>
88            <td colspan="3" align="center">
89              <input type="submit" name="report" value="%s" />
90            </td>
91          </tr>
92        </table>
93        <p>
94          %s
95        </p>"""
96   
97footer = """
98        <table>
99          <tr>
100            <td colspan="3" align="center">
101              <input type="submit" name="report" value="%s" />
102            </td>
103          </tr>
104        </table> 
105      </form>
106    </p> 
107    <hr width="25%%" />
108    <p>
109      <font size="-2">
110        <a href="http://www.pykota.com/">%s</a>
111        &copy; %s %s
112        <br />
113        <pre>
114%s
115        </pre>
116      </font>
117    </p>
118  </body>
119</html>""" 
120
121class PyKotaDumperGUI(DumPyKota) :
122    """PyKota Dumper GUI"""
123    def guiDisplay(self) :
124        """Displays the dumper interface."""
125        global header, footer
126        print header % (self.getCharset(), _("PyKota Data Dumper"), \
127                        self.config.getLogoLink(), \
128                        self.config.getLogoURL(), version.__version__, \
129                        self.config.getLogoLink(), \
130                        version.__version__, _("PyKota Data Dumper"), \
131                        _("Dump"), _("Please click on the above button"))
132        print self.htmlListDataTypes(self.options.get("data", ""))
133        print "<br />"
134        print self.htmlListFormats(self.options.get("format", ""))
135        print "<br />"
136        print self.htmlFilterInput(" ".join(self.arguments))
137        print "<br />"
138        print self.htmlSumCheckbox(self.options.get("sum", ""))
139        print footer % (_("Dump"), version.__doc__, version.__years__, version.__author__, version.__gplblurb__)
140       
141    def htmlListDataTypes(self, selected="") :   
142        """Displays the datatype selection list."""
143        message = '<table><tr><td valign="top">%s :</td><td valign="top"><select name="datatype">' % _("Data Type")
144        for dt in self.validdatatypes.items() :
145            if dt[0] == selected :
146                message += '<option value="%s" selected="selected">%s (%s)</option>' % (dt[0], dt[0], dt[1])
147            else :
148                message += '<option value="%s">%s (%s)</option>' % (dt[0], dt[0], dt[1])
149        message += '</select></td></tr></table>'
150        return message
151       
152    def htmlListFormats(self, selected="") :   
153        """Displays the formats selection list."""
154        message = '<table><tr><td valign="top">%s :</td><td valign="top"><select name="format">' % _("Output Format")
155        for fmt in self.validformats.items() :
156            if fmt[0] == selected :
157                message += '<option value="%s" selected="selected">%s (%s)</option>' % (fmt[0], fmt[0], fmt[1])
158            else :
159                message += '<option value="%s">%s (%s)</option>' % (fmt[0], fmt[0], fmt[1])
160        message += '</select></td></tr></table>'
161        return message
162       
163    def htmlFilterInput(self, value="") :   
164        """Input the optional dump filter."""
165        return _("Filter") + (' : <input type="text" name="filter" size="40" value="%s" /> <em>e.g. <strong>username=jerome printername=HP2100 start=today-30</strong></em>' % (value or ""))
166       
167    def htmlSumCheckbox(self, checked="") :   
168        """Input the optional Sum option."""
169        return _("Summarize") + (' : <input type="checkbox" name="sum" %s /> <em>%s</em>' % ((checked and 'checked="checked"'), _("only for payments or history")))
170       
171    def guiAction(self) :
172        """Main function"""
173        try :
174            wantreport = self.form.has_key("report")
175        except TypeError :   
176            pass # WebDAV request probably, seen when trying to open a csv file in OOo
177        else :   
178            if wantreport :
179                try :
180                    if self.form.has_key("datatype") :
181                        self.options["data"] = self.form["datatype"].value
182                    if self.form.has_key("format") :
183                        self.options["format"] = self.form["format"].value
184                    if self.form.has_key("filter") :   
185                        self.arguments = self.form["filter"].value.split()
186                    if self.form.has_key("sum") :   
187                        self.options["sum"] = self.form["sum"].value
188                    # when no authentication is done, or when the remote username   
189                    # is 'root' (even if not run as root of course), then unrestricted
190                    # dump is allowed.
191                    remuser = os.environ.get("REMOTE_USER", "root")   
192                    # special hack to accomodate mod_auth_ldap Apache module
193                    try :
194                        remuser = remuser.split("=")[1].split(",")[0]
195                    except IndexError :   
196                        pass
197                    if remuser != "root" :
198                        # non-'root' users when the script is password protected
199                        # can not dump any data as they like, we restrict them
200                        # to their own datas.
201                        if self.options["data"] not in ["printers", "pmembers", "groups", "gpquotas"] :
202                            self.arguments.append("username=%s" % remuser)
203                       
204                    fname = "error"   
205                    ctype = "text/plain"
206                    if self.options["format"] in ("csv", "ssv") :
207                        #ctype = "application/vnd.sun.xml.calc"     # OpenOffice.org
208                        ctype = "text/comma-separated-values"
209                        fname = "dump.csv"
210                    elif self.options["format"] == "tsv" :
211                        #ctype = "application/vnd.sun.xml.calc"     # OpenOffice.org
212                        ctype = "text/tab-separated-values"
213                        fname = "dump.tsv"
214                    elif self.options["format"] == "xml" :
215                        ctype = "text/xml"
216                        fname = "dump.xml"
217                    elif self.options["format"] == "cups" :
218                        ctype = "text/plain"
219                        fname = "page_log"
220                    print "Content-type: %s" % ctype   
221                    print "Content-disposition: attachment; filename=%s" % fname
222                    print
223                    self.main(self.arguments, self.options, restricted=0)
224                except :
225                    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 />")
226            else :       
227                self.guiDisplay()
228           
229if __name__ == "__main__" :
230    os.environ["LC_ALL"] = getLanguagePreference()
231    admin = PyKotaDumperGUI(lang=os.environ["LC_ALL"], charset=getCharsetPreference())
232    admin.deferredInit()
233    admin.form = cgi.FieldStorage()
234    admin.options = { "output" : "-",
235                "data" : "history",
236                "format" : "cups",
237                "sum" : None,
238              }
239    admin.arguments = []
240    admin.guiAction()
241    try :
242        admin.storage.close()
243    except (TypeError, NameError, AttributeError) :   
244        pass
245       
246    sys.exit(0)
Note: See TracBrowser for help on using the browser.