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

Revision 3275, 10.1 kB (checked in by jerome, 16 years ago)

Updated copyright years.
Changed some remaining ISO-8859-15 markers to UTF-8 in Python source code.
Added missing source encoding markers.
Added missing copyright messages.

  • 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
31from pykota import version
32from pykota.tool import PyKotaToolError
33from pykota.dumper import DumPyKota
34from pykota.cgifuncs import getLanguagePreference, getCharsetPreference
35
36header = """Content-type: text/html;charset=%s
37
38<html>
39  <head>
40    <title>%s</title>
41    <link rel="stylesheet" type="text/css" href="/pykota.css" />
42    <script type="text/javascript">
43    <!--
44      function checkvalues()
45      {
46          if ((document.mainform.format.value == "cups") && (document.mainform.datatype.value != "history"))
47          {
48              alert("Output format and data type are incompatible.");
49              return false;
50          }
51         
52          if (document.mainform.sum.checked && (document.mainform.datatype.value != "payments") && (document.mainform.datatype.value != "history"))
53          {
54              alert("Summarize is only possible for History and Payments.");
55              return false;
56          }
57         
58          if (document.mainform.sum.checked && (document.mainform.format.value == "cups"))
59          {
60              alert("Summarize is not possible with CUPS' page_log format.");
61              return false;
62          }
63         
64          return true;
65      }
66    //-->
67    </script>
68  </head>
69  <body>
70    <!-- %s %s -->
71    <p>
72      <form action="dumpykota.cgi" method="GET" name="mainform" onsubmit="return checkvalues()">
73        <table>
74          <tr>
75            <td>
76              <p>
77                <a href="%s"><img src="%s?version=%s" alt="PyKota's Logo" /></a>
78                <br />
79                <a href="%s">PyKota v%s</a>
80              </p>
81            </td>
82            <td colspan="2">
83              <h1>%s</h1>
84            </td>
85          </tr>
86          <tr>
87            <td colspan="3" align="center">
88              <input type="submit" name="report" value="%s" />
89            </td>
90          </tr>
91        </table>
92        <p>
93          %s
94        </p>"""
95   
96footer = """
97        <table>
98          <tr>
99            <td colspan="3" align="center">
100              <input type="submit" name="report" value="%s" />
101            </td>
102          </tr>
103        </table> 
104      </form>
105    </p> 
106    <hr width="25%%" />
107    <p>
108      <font size="-2">
109        <a href="http://www.pykota.com/">%s</a>
110        &copy; %s %s
111        <br />
112        <pre>
113%s
114        </pre>
115      </font>
116    </p>
117  </body>
118</html>""" 
119
120class PyKotaDumperGUI(DumPyKota) :
121    """PyKota Dumper GUI"""
122    def guiDisplay(self) :
123        """Displays the dumper interface."""
124        global header, footer
125        print header % (self.charset, _("PyKota Data Dumper"), \
126                        self.language, self.charset, \
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.htmlOrderbyInput(self.options.get("orderby", ""))
139        print "<br />"
140        print self.htmlSumCheckbox(self.options.get("sum", ""))
141        print footer % (_("Dump"), version.__doc__, version.__years__, version.__author__, version.__gplblurb__)
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    admin = PyKotaDumperGUI(lang=getLanguagePreference(), charset=getCharsetPreference())
239    admin.deferredInit()
240    admin.form = cgi.FieldStorage()
241    admin.options = { "output" : "-",
242                "data" : "history",
243                "format" : "cups",
244                "sum" : None,
245                "orderby" : None,
246              }
247    admin.arguments = []
248    admin.guiAction()
249    try :
250        admin.storage.close()
251    except (TypeError, NameError, AttributeError) :   
252        pass
253       
254    sys.exit(0)
Note: See TracBrowser for help on using the browser.