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

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