root / pykota / tags / 1.26 / cgi-bin / dumpykota.cgi

Revision 3211, 10.2 kB (checked in by jerome, 17 years ago)

Added missing ordering field for CGI data dumper...

  • 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, 2007 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;charset=%s
38
39<html>
40  <head>
41    <title>%s</title>
42    <link rel="stylesheet" type="text/css" href="/pykota.css" />
43    <script type="text/javascript">
44    <!--
45      function checkvalues()
46      {
47          if ((document.mainform.format.value == "cups") && (document.mainform.datatype.value != "history"))
48          {
49              alert("Output format and data type are incompatible.");
50              return false;
51          }
52         
53          if (document.mainform.sum.checked && (document.mainform.datatype.value != "payments") && (document.mainform.datatype.value != "history"))
54          {
55              alert("Summarize is only possible for History and Payments.");
56              return false;
57          }
58         
59          if (document.mainform.sum.checked && (document.mainform.format.value == "cups"))
60          {
61              alert("Summarize is not possible with CUPS' page_log format.");
62              return false;
63          }
64         
65          return true;
66      }
67    //-->
68    </script>
69  </head>
70  <body>
71    <!-- %s %s -->
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.charset, _("PyKota Data Dumper"), \
127                        self.language, self.charset, \
128                        self.config.getLogoLink(), \
129                        self.config.getLogoURL(), version.__version__, \
130                        self.config.getLogoLink(), \
131                        version.__version__, _("PyKota Data Dumper"), \
132                        _("Dump"), _("Please click on the above button"))
133        print self.htmlListDataTypes(self.options.get("data", ""))
134        print "<br />"
135        print self.htmlListFormats(self.options.get("format", ""))
136        print "<br />"
137        print self.htmlFilterInput(" ".join(self.arguments))
138        print "<br />"
139        print self.htmlOrderbyInput(self.options.get("orderby", ""))
140        print "<br />"
141        print self.htmlSumCheckbox(self.options.get("sum", ""))
142        print footer % (_("Dump"), version.__doc__, version.__years__, version.__author__, version.__gplblurb__)
143       
144    def htmlListDataTypes(self, selected="") :   
145        """Displays the datatype selection list."""
146        message = '<table><tr><td valign="top">%s :</td><td valign="top"><select name="datatype">' % _("Data Type")
147        for dt in self.validdatatypes.items() :
148            if dt[0] == selected :
149                message += '<option value="%s" selected="selected">%s (%s)</option>' % (dt[0], dt[0], dt[1])
150            else :
151                message += '<option value="%s">%s (%s)</option>' % (dt[0], dt[0], dt[1])
152        message += '</select></td></tr></table>'
153        return message
154       
155    def htmlListFormats(self, selected="") :   
156        """Displays the formats selection list."""
157        message = '<table><tr><td valign="top">%s :</td><td valign="top"><select name="format">' % _("Output Format")
158        for fmt in self.validformats.items() :
159            if fmt[0] == selected :
160                message += '<option value="%s" selected="selected">%s (%s)</option>' % (fmt[0], fmt[0], fmt[1])
161            else :
162                message += '<option value="%s">%s (%s)</option>' % (fmt[0], fmt[0], fmt[1])
163        message += '</select></td></tr></table>'
164        return message
165       
166    def htmlFilterInput(self, value="") :   
167        """Input the optional dump filter."""
168        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 ""))
169       
170    def htmlOrderbyInput(self, value="") :   
171        """Input the optional ordering."""
172        return _("Ordering") + (' : <input type="text" name="orderby" size="40" value="%s" /> <em>e.g. <strong>+username,-printername</strong></em>' % (value or ""))
173       
174    def htmlSumCheckbox(self, checked="") :   
175        """Input the optional Sum option."""
176        return _("Summarize") + (' : <input type="checkbox" name="sum" %s /> <em>%s</em>' % ((checked and 'checked="checked"'), _("only for payments or history")))
177       
178    def guiAction(self) :
179        """Main function"""
180        try :
181            wantreport = self.form.has_key("report")
182        except TypeError :   
183            pass # WebDAV request probably, seen when trying to open a csv file in OOo
184        else :   
185            if wantreport :
186                try :
187                    if self.form.has_key("datatype") :
188                        self.options["data"] = self.form["datatype"].value
189                    if self.form.has_key("format") :
190                        self.options["format"] = self.form["format"].value
191                    if self.form.has_key("filter") :   
192                        self.arguments = self.form["filter"].value.split()
193                    if self.form.has_key("sum") :   
194                        self.options["sum"] = self.form["sum"].value
195                    if self.form.has_key("orderby") :   
196                        self.options["orderby"] = self.form["orderby"].value
197                    # when no authentication is done, or when the remote username   
198                    # is 'root' (even if not run as root of course), then unrestricted
199                    # dump is allowed.
200                    remuser = os.environ.get("REMOTE_USER", "root")   
201                    # special hack to accomodate mod_auth_ldap Apache module
202                    try :
203                        remuser = remuser.split("=")[1].split(",")[0]
204                    except IndexError :   
205                        pass
206                    if remuser != "root" :
207                        # non-'root' users when the script is password protected
208                        # can not dump any data as they like, we restrict them
209                        # to their own datas.
210                        if self.options["data"] not in ["printers", "pmembers", "groups", "gpquotas"] :
211                            self.arguments.append("username=%s" % remuser)
212                       
213                    fname = "error"   
214                    ctype = "text/plain"
215                    if self.options["format"] in ("csv", "ssv") :
216                        #ctype = "application/vnd.sun.xml.calc"     # OpenOffice.org
217                        ctype = "text/comma-separated-values"
218                        fname = "dump.csv"
219                    elif self.options["format"] == "tsv" :
220                        #ctype = "application/vnd.sun.xml.calc"     # OpenOffice.org
221                        ctype = "text/tab-separated-values"
222                        fname = "dump.tsv"
223                    elif self.options["format"] == "xml" :
224                        ctype = "text/xml"
225                        fname = "dump.xml"
226                    elif self.options["format"] == "cups" :
227                        ctype = "text/plain"
228                        fname = "page_log"
229                    print "Content-type: %s" % ctype   
230                    print "Content-disposition: attachment; filename=%s" % fname
231                    print
232                    self.main(self.arguments, self.options, restricted=0)
233                except :
234                    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 />")
235            else :       
236                self.guiDisplay()
237           
238if __name__ == "__main__" :
239    admin = PyKotaDumperGUI(lang=getLanguagePreference(), charset=getCharsetPreference())
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.