root / pykota / trunk / pykota / config.py @ 2307

Revision 2307, 20.8 kB (checked in by jerome, 19 years ago)

Added the striptitle directive.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23#
24
25import os
26import ConfigParser
27
28class PyKotaConfigError(Exception):
29    """An exception for PyKota config related stuff."""
30    def __init__(self, message = ""):
31        self.message = message
32        Exception.__init__(self, message)
33    def __repr__(self):
34        return self.message
35    __str__ = __repr__
36   
37class PyKotaConfig :
38    """A class to deal with PyKota's configuration."""
39    def __init__(self, directory) :
40        """Reads and checks the configuration file."""
41        self.isAdmin = 0
42        self.directory = directory
43        self.filename = os.path.join(directory, "pykota.conf")
44        if not os.path.isfile(self.filename) :
45            raise PyKotaConfigError, _("Configuration file %s not found.") % self.filename
46        self.config = ConfigParser.ConfigParser()
47        self.config.read([self.filename])
48           
49    def isTrue(self, option) :       
50        """Returns 1 if option is set to true, else 0."""
51        if (option is not None) and (option.upper().strip() in ['Y', 'YES', '1', 'ON', 'T', 'TRUE']) :
52            return 1
53        else :   
54            return 0
55                       
56    def getPrinterNames(self) :   
57        """Returns the list of configured printers, i.e. all sections names minus 'global'."""
58        return [pname for pname in self.config.sections() if pname != "global"]
59       
60    def getGlobalOption(self, option, ignore=0) :   
61        """Returns an option from the global section, or raises a PyKotaConfigError if ignore is not set, else returns None."""
62        try :
63            return self.config.get("global", option, raw=1)
64        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
65            if ignore :
66                return
67            else :
68                raise PyKotaConfigError, _("Option %s not found in section global of %s") % (option, self.filename)
69               
70    def getPrinterOption(self, printername, option) :   
71        """Returns an option from the printer section, or the global section, or raises a PyKotaConfigError."""
72        globaloption = self.getGlobalOption(option, ignore=1)
73        try :
74            return self.config.get(printername, option, raw=1)
75        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
76            if globaloption is not None :
77                return globaloption
78            else :
79                raise PyKotaConfigError, _("Option %s not found in section %s of %s") % (option, printername, self.filename)
80       
81    def getStorageBackend(self) :   
82        """Returns the storage backend information as a Python mapping."""       
83        backendinfo = {}
84        for option in [ "storagebackend", "storageserver", \
85                        "storagename", "storageuser", \
86                      ] :
87            backendinfo[option] = self.getGlobalOption(option)
88        backendinfo["storageuserpw"] = self.getGlobalOption("storageuserpw", ignore=1)  # password is optional
89        backendinfo["storageadmin"] = None
90        backendinfo["storageadminpw"] = None
91        adminconf = ConfigParser.ConfigParser()
92        filename = os.path.join(self.directory, "pykotadmin.conf")
93        adminconf.read([filename])
94        if adminconf.sections() : # were we able to read the file ?
95            try :
96                backendinfo["storageadmin"] = adminconf.get("global", "storageadmin", raw=1)
97            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
98                raise PyKotaConfigError, _("Option %s not found in section global of %s") % ("storageadmin", filename)
99            else :   
100                self.isAdmin = 1 # We are a PyKota administrator
101            try :
102                backendinfo["storageadminpw"] = adminconf.get("global", "storageadminpw", raw=1)
103            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
104                pass # Password is optional
105        return backendinfo
106       
107    def getLDAPInfo(self) :   
108        """Returns some hints for the LDAP backend."""       
109        ldapinfo = {}
110        for option in [ "userbase", "userrdn", \
111                        "balancebase", "balancerdn", \
112                        "groupbase", "grouprdn", "groupmembers", \
113                        "printerbase", "printerrdn", \
114                        "userquotabase", "groupquotabase", \
115                        "jobbase", "lastjobbase", \
116                        "newuser", "newgroup", \
117                        "usermail", \
118                      ] :
119            ldapinfo[option] = self.getGlobalOption(option).strip()
120        for field in ["newuser", "newgroup"] :
121            if ldapinfo[field].lower().startswith('attach(') :
122                ldapinfo[field] = ldapinfo[field][7:-1]
123               
124        # should we use TLS, by default (if unset) value is NO       
125        ldapinfo["ldaptls"] = self.isTrue(self.getGlobalOption("ldaptls", ignore=1))
126        ldapinfo["cacert"] = self.getGlobalOption("cacert", ignore=1)
127        if ldapinfo["cacert"] :
128            ldapinfo["cacert"] = ldapinfo["cacert"].strip()
129        if ldapinfo["ldaptls"] :   
130            if not os.access(ldapinfo["cacert"] or "", os.R_OK) :
131                raise PyKotaConfigError, _("Option ldaptls is set, but certificate %s is not readable.") % str(ldapinfo["cacert"])
132        return ldapinfo
133       
134    def getLoggingBackend(self) :   
135        """Returns the logging backend information."""
136        validloggers = [ "stderr", "system" ] 
137        try :
138            logger = self.getGlobalOption("logger").lower()
139        except PyKotaConfigError :   
140            logger = "system"
141        if logger not in validloggers :             
142            raise PyKotaConfigError, _("Option logger only supports values in %s") % str(validloggers)
143        return logger   
144       
145    def getLogoURL(self) :
146        """Returns the URL to use for the logo in the CGI scripts."""
147        url = self.getGlobalOption("logourl", ignore=1) or \
148                   "http://www.librelogiciel.com/software/PyKota/pykota.png"
149        return url.strip()           
150       
151    def getLogoLink(self) :
152        """Returns the URL to go to when the user clicks on the logo in the CGI scripts."""
153        url = self.getGlobalOption("logolink", ignore=1) or \
154                   "http://www.librelogiciel.com/software/"
155        return url.strip()           
156   
157    def getAccounterBackend(self, printername) :   
158        """Returns the accounter backend to use for a given printer.
159       
160           if it is not set, it defaults to 'hardware' which means ask printer
161           for its internal lifetime page counter.
162        """   
163        validaccounters = [ "hardware", "software" ]     
164        fullaccounter = self.getPrinterOption(printername, "accounter").strip()
165        flower = fullaccounter.lower()
166        if flower.startswith("software") or flower.startswith("hardware") :   
167            try :
168                (accounter, args) = [x.strip() for x in fullaccounter.split('(', 1)]
169            except ValueError :   
170                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
171            if args.endswith(')') :
172                args = args[:-1].strip()
173            if (accounter == "hardware") and not args :
174                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
175            return (accounter.lower(), args)   
176        else :
177            raise PyKotaConfigError, _("Option accounter in section %s only supports values in %s") % (printername, str(validaccounters))
178       
179    def getPreHook(self, printername) :   
180        """Returns the prehook command line to launch, or None if unset."""
181        try :
182            return self.getPrinterOption(printername, "prehook").strip()
183        except PyKotaConfigError :   
184            return      # No command to launch in the pre-hook
185           
186    def getPostHook(self, printername) :   
187        """Returns the posthook command line to launch, or None if unset."""
188        try :
189            return self.getPrinterOption(printername, "posthook").strip()
190        except PyKotaConfigError :   
191            return      # No command to launch in the post-hook
192           
193    def getStripTitle(self, printername) :   
194        """Returns the striptitle directive's content, or None if unset."""
195        try :
196            return self.getPrinterOption(printername, "striptitle").strip()
197        except PyKotaConfigError :   
198            return      # No prefix to strip off
199           
200    def getPrinterEnforcement(self, printername) :   
201        """Returns if quota enforcement should be strict or laxist for the current printer."""
202        validenforcements = [ "STRICT", "LAXIST" ]     
203        try :
204            enforcement = self.getPrinterOption(printername, "enforcement")
205        except PyKotaConfigError :   
206            return "LAXIST"
207        else :   
208            enforcement = enforcement.upper()
209            if enforcement not in validenforcements :
210                raise PyKotaConfigError, _("Option enforcement in section %s only supports values in %s") % (printername, str(validenforcements))
211            return enforcement   
212           
213    def getPrinterOnAccounterError(self, printername) :   
214        """Returns what must be done whenever the accounter fails."""
215        validactions = [ "CONTINUE", "STOP" ]     
216        try :
217            action = self.getPrinterOption(printername, "onaccountererror")
218        except PyKotaConfigError :   
219            return "STOP"
220        else :   
221            action = action.upper()
222            if action not in validactions :
223                raise PyKotaConfigError, _("Option onaccountererror in section %s only supports values in %s") % (printername, str(validactions))
224            return action 
225           
226    def getPrinterPolicy(self, printername) :   
227        """Returns the default policy for the current printer."""
228        validpolicies = [ "ALLOW", "DENY", "EXTERNAL" ]     
229        try :
230            fullpolicy = self.getPrinterOption(printername, "policy")
231        except PyKotaConfigError :   
232            return ("DENY", None)
233        else :   
234            try :
235                policy = [x.strip() for x in fullpolicy.split('(', 1)]
236            except ValueError :   
237                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
238            if len(policy) == 1 :   
239                policy.append("")
240            (policy, args) = policy   
241            if args.endswith(')') :
242                args = args[:-1]
243            policy = policy.upper()   
244            if (policy == "EXTERNAL") and not args :
245                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
246            if policy not in validpolicies :
247                raise PyKotaConfigError, _("Option policy in section %s only supports values in %s") % (printername, str(validpolicies))
248            return (policy, args)
249       
250    def getCrashRecipient(self) :   
251        """Returns the email address of the software crash messages recipient."""
252        try :
253            return self.getGlobalOption("crashrecipient")
254        except :   
255            return
256           
257    def getSMTPServer(self) :   
258        """Returns the SMTP server to use to send messages to users."""
259        try :
260            return self.getGlobalOption("smtpserver")
261        except PyKotaConfigError :   
262            return "localhost"
263       
264    def getMailDomain(self) :   
265        """Returns the mail domain to use to send messages to users."""
266        try :
267            return self.getGlobalOption("maildomain")
268        except PyKotaConfigError :   
269            return 
270       
271    def getAdminMail(self, printername) :   
272        """Returns the Email address of the Print Quota Administrator."""
273        try :
274            return self.getPrinterOption(printername, "adminmail")
275        except PyKotaConfigError :   
276            return "root@localhost"
277       
278    def getAdmin(self, printername) :   
279        """Returns the full name of the Print Quota Administrator."""
280        try :
281            return self.getPrinterOption(printername, "admin")
282        except PyKotaConfigError :   
283            return "root"
284       
285    def getMailTo(self, printername) :   
286        """Returns the recipient of email messages."""
287        validmailtos = [ "EXTERNAL", "NOBODY", "NONE", "NOONE", "BITBUCKET", "DEVNULL", "BOTH", "USER", "ADMIN" ]
288        try :
289            fullmailto = self.getPrinterOption(printername, "mailto")
290        except PyKotaConfigError :   
291            return ("BOTH", None)
292        else :   
293            try :
294                mailto = [x.strip() for x in fullmailto.split('(', 1)]
295            except ValueError :   
296                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
297            if len(mailto) == 1 :   
298                mailto.append("")
299            (mailto, args) = mailto   
300            if args.endswith(')') :
301                args = args[:-1]
302            mailto = mailto.upper()   
303            if (mailto == "EXTERNAL") and not args :
304                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
305            if mailto not in validmailtos :
306                raise PyKotaConfigError, _("Option mailto in section %s only supports values in %s") % (printername, str(validmailtos))
307            return (mailto, args)
308       
309    def getMaxDenyBanners(self, printername) :   
310        """Returns the maximum number of deny banners to be printed for a particular user on a particular printer."""
311        try :
312            maxdb = self.getPrinterOption(printername, "maxdenybanners")
313        except PyKotaConfigError :   
314            return 0 # default value is to forbid printing a deny banner.
315        try :
316            value = int(maxdb.strip())
317            if value < 0 :
318                raise ValueError
319        except (TypeError, ValueError) :   
320            raise PyKotaConfigError, _("Invalid maximal deny banners counter %s") % maxdb
321        else :   
322            return value
323           
324    def getGraceDelay(self, printername) :   
325        """Returns the grace delay in days."""
326        try :
327            gd = self.getPrinterOption(printername, "gracedelay")
328        except PyKotaConfigError :   
329            gd = 7      # default value of 7 days
330        try :
331            return int(gd)
332        except (TypeError, ValueError) :   
333            raise PyKotaConfigError, _("Invalid grace delay %s") % gd
334           
335    def getPoorMan(self) :   
336        """Returns the poor man's threshold."""
337        try :
338            pm = self.getGlobalOption("poorman")
339        except PyKotaConfigError :   
340            pm = 1.0    # default value of 1 unit
341        try :
342            return float(pm)
343        except (TypeError, ValueError) :   
344            raise PyKotaConfigError, _("Invalid poor man's threshold %s") % pm
345           
346    def getPoorWarn(self) :   
347        """Returns the poor man's warning message."""
348        try :
349            return self.getGlobalOption("poorwarn")
350        except PyKotaConfigError :   
351            return _("Your Print Quota account balance is Low.\nSoon you'll not be allowed to print anymore.\nPlease contact the Print Quota Administrator to solve the problem.")
352           
353    def getHardWarn(self, printername) :   
354        """Returns the hard limit error message."""
355        try :
356            return self.getPrinterOption(printername, "hardwarn")
357        except PyKotaConfigError :   
358            return _("You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s.") % printername
359           
360    def getSoftWarn(self, printername) :   
361        """Returns the soft limit error message."""
362        try :
363            return self.getPrinterOption(printername, "softwarn")
364        except PyKotaConfigError :   
365            return _("You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s.") % printername
366           
367    def getPrivacy(self) :       
368        """Returns 1 if privacy is activated, else 0."""
369        return self.isTrue(self.getGlobalOption("privacy", ignore=1))
370       
371    def getDebug(self) :         
372        """Returns 1 if debugging is activated, else 0."""
373        return self.isTrue(self.getGlobalOption("debug", ignore=1))
374           
375    def getCaching(self) :         
376        """Returns 1 if database caching is enabled, else 0."""
377        return self.isTrue(self.getGlobalOption("storagecaching", ignore=1))
378           
379    def getLDAPCache(self) :         
380        """Returns 1 if low-level LDAP caching is enabled, else 0."""
381        return self.isTrue(self.getGlobalOption("ldapcache", ignore=1))
382           
383    def getDisableHistory(self) :         
384        """Returns 1 if we want to disable history, else 0."""
385        return self.isTrue(self.getGlobalOption("disablehistory", ignore=1))
386           
387    def getUserNameToLower(self) :         
388        """Returns 1 if we want to convert usernames to lowercase when printing, else 0."""
389        return self.isTrue(self.getGlobalOption("utolower", ignore=1))
390       
391    def getRejectUnknown(self) :         
392        """Returns 1 if we want to reject the creation of unknown users or groups, else 0."""
393        return self.isTrue(self.getGlobalOption("reject_unknown", ignore=1))
394       
395    def getDenyDuplicates(self, printername) :         
396        """Returns 1 if we want to deny duplicate jobs, else 0."""
397        try : 
398            return self.isTrue(self.getPrinterOption(printername, "denyduplicates"))
399        except PyKotaConfigError :   
400            return 0
401       
402    def getWinbindSeparator(self) :         
403        """Returns the winbind separator's value if it is set, else None."""
404        return self.getGlobalOption("winbind_separator", ignore=1)
405
406    def getAccountBanner(self, printername) :
407        """Returns which banner(s) to account for: NONE, BOTH, STARTING, ENDING."""
408        validvalues = [ "NONE", "BOTH", "STARTING", "ENDING" ]     
409        try :
410            value = self.getPrinterOption(printername, "accountbanner")
411        except PyKotaConfigError :   
412            return "BOTH"       # Default value of BOTH
413        else :   
414            value = value.strip().upper()
415            if value not in validvalues :
416                raise PyKotaConfigError, _("Option accountbanner in section %s only supports values in %s") % (printername, str(validvalues))
417            return value 
418
419    def getStartingBanner(self, printername) :
420        """Returns the startingbanner value if set, else None."""
421        try :
422            return self.getPrinterOption(printername, "startingbanner").strip()
423        except PyKotaConfigError :
424            return None
425
426    def getEndingBanner(self, printername) :
427        """Returns the endingbanner value if set, else None."""
428        try :
429            return self.getPrinterOption(printername, "endingbanner").strip()
430        except PyKotaConfigError :
431            return None
432           
433    def getTrustJobSize(self, printername) :
434        """Returns the normalized value of the trustjobsize's directive."""
435        try :
436            value = self.getPrinterOption(printername, "trustjobsize").strip().upper()
437        except PyKotaConfigError :
438            return (None, "YES")
439        else :   
440            if value == "YES" :
441                return (None, "YES")
442            try :   
443                (limit, replacement) = [p.strip() for p in value.split(">")[1].split(":")]
444                limit = int(limit)
445                try :
446                    replacement = int(replacement) 
447                except ValueError :   
448                    if replacement != "PRECOMPUTED" :
449                        raise
450                if limit < 0 :
451                    raise ValueError
452                if (replacement != "PRECOMPUTED") and (replacement < 0) :
453                    raise ValueError
454            except (IndexError, ValueError, TypeError) :
455                raise PyKotaConfigError, _("Option trustjobsize for printer %s is incorrect") % printername
456            return (limit, replacement)   
Note: See TracBrowser for help on using the browser.