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

Revision 2262, 20.2 kB (checked in by jerome, 19 years ago)

The URL to the logo used in the CGI scripts is now configurable

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[695]1# PyKota
[1144]2# -*- coding: ISO-8859-15 -*-
[695]3#
[952]4# PyKota : Print Quotas for CUPS and LPRng
[695]5#
[1257]6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
[873]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.
[695]11#
[873]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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
[695]20#
21# $Id$
22#
[2074]23#
[695]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."""
[1785]41        self.isAdmin = 0
42        self.directory = directory
[695]43        self.filename = os.path.join(directory, "pykota.conf")
[872]44        if not os.path.isfile(self.filename) :
45            raise PyKotaConfigError, _("Configuration file %s not found.") % self.filename
[695]46        self.config = ConfigParser.ConfigParser()
47        self.config.read([self.filename])
[1227]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
[695]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       
[802]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               
[1192]70    def getPrinterOption(self, printername, option) :   
[802]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 :
[1192]74            return self.config.get(printername, option, raw=1)
[802]75        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
76            if globaloption is not None :
77                return globaloption
78            else :
[1192]79                raise PyKotaConfigError, _("Option %s not found in section %s of %s") % (option, printername, self.filename)
[802]80       
[695]81    def getStorageBackend(self) :   
[800]82        """Returns the storage backend information as a Python mapping."""       
83        backendinfo = {}
[695]84        for option in [ "storagebackend", "storageserver", \
[1087]85                        "storagename", "storageuser", \
[695]86                      ] :
[804]87            backendinfo[option] = self.getGlobalOption(option)
[1087]88        backendinfo["storageuserpw"] = self.getGlobalOption("storageuserpw", ignore=1)  # password is optional
89        backendinfo["storageadmin"] = None
90        backendinfo["storageadminpw"] = None
91        adminconf = ConfigParser.ConfigParser()
[1785]92        filename = os.path.join(self.directory, "pykotadmin.conf")
93        adminconf.read([filename])
[1087]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) :   
[1785]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
[1087]101            try :
102                backendinfo["storageadminpw"] = adminconf.get("global", "storageadminpw", raw=1)
103            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
104                pass # Password is optional
[800]105        return backendinfo
[695]106       
[1029]107    def getLDAPInfo(self) :   
108        """Returns some hints for the LDAP backend."""       
109        ldapinfo = {}
110        for option in [ "userbase", "userrdn", \
[1041]111                        "balancebase", "balancerdn", \
[1029]112                        "groupbase", "grouprdn", "groupmembers", \
113                        "printerbase", "printerrdn", \
114                        "userquotabase", "groupquotabase", \
115                        "jobbase", "lastjobbase", \
[1105]116                        "newuser", "newgroup", \
[1111]117                        "usermail", \
[1029]118                      ] :
[1105]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]
[1968]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"])
[1029]132        return ldapinfo
133       
[695]134    def getLoggingBackend(self) :   
135        """Returns the logging backend information."""
[802]136        validloggers = [ "stderr", "system" ] 
[853]137        try :
138            logger = self.getGlobalOption("logger").lower()
139        except PyKotaConfigError :   
140            logger = "system"
[802]141        if logger not in validloggers :             
142            raise PyKotaConfigError, _("Option logger only supports values in %s") % str(validloggers)
143        return logger   
[695]144       
[2262]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   
[1192]151    def getAccounterBackend(self, printername) :   
[973]152        """Returns the accounter backend to use for a given printer.
153       
[1475]154           if it is not set, it defaults to 'hardware' which means ask printer
[973]155           for its internal lifetime page counter.
156        """   
[1475]157        validaccounters = [ "hardware", "software" ]     
[1371]158        fullaccounter = self.getPrinterOption(printername, "accounter").strip()
[1483]159        flower = fullaccounter.lower()
160        if flower.startswith("software") or flower.startswith("hardware") :   
[980]161            try :
162                (accounter, args) = [x.strip() for x in fullaccounter.split('(', 1)]
163            except ValueError :   
[1483]164                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
[980]165            if args.endswith(')') :
[2074]166                args = args[:-1].strip()
167            if (accounter == "hardware") and not args :
[1483]168                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
[1000]169            return (accounter.lower(), args)   
[1483]170        else :
[1192]171            raise PyKotaConfigError, _("Option accounter in section %s only supports values in %s") % (printername, str(validaccounters))
[973]172       
[1371]173    def getPreHook(self, printername) :   
174        """Returns the prehook command line to launch, or None if unset."""
175        try :
176            return self.getPrinterOption(printername, "prehook").strip()
177        except PyKotaConfigError :   
178            return      # No command to launch in the pre-hook
179           
180    def getPostHook(self, printername) :   
181        """Returns the posthook command line to launch, or None if unset."""
182        try :
183            return self.getPrinterOption(printername, "posthook").strip()
184        except PyKotaConfigError :   
185            return      # No command to launch in the post-hook
186           
[1495]187    def getPrinterEnforcement(self, printername) :   
188        """Returns if quota enforcement should be strict or laxist for the current printer."""
189        validenforcements = [ "STRICT", "LAXIST" ]     
190        try :
191            enforcement = self.getPrinterOption(printername, "enforcement")
192        except PyKotaConfigError :   
193            return "LAXIST"
194        else :   
195            enforcement = enforcement.upper()
196            if enforcement not in validenforcements :
197                raise PyKotaConfigError, _("Option enforcement in section %s only supports values in %s") % (printername, str(validenforcements))
198            return enforcement   
199           
[1687]200    def getPrinterOnAccounterError(self, printername) :   
201        """Returns what must be done whenever the accounter fails."""
202        validactions = [ "CONTINUE", "STOP" ]     
203        try :
204            action = self.getPrinterOption(printername, "onaccountererror")
205        except PyKotaConfigError :   
206            return "STOP"
207        else :   
208            action = action.upper()
209            if action not in validactions :
210                raise PyKotaConfigError, _("Option onaccountererror in section %s only supports values in %s") % (printername, str(validactions))
211            return action 
212           
[1192]213    def getPrinterPolicy(self, printername) :   
[695]214        """Returns the default policy for the current printer."""
[1152]215        validpolicies = [ "ALLOW", "DENY", "EXTERNAL" ]     
[853]216        try :
[1192]217            fullpolicy = self.getPrinterOption(printername, "policy")
[853]218        except PyKotaConfigError :   
[1152]219            return ("DENY", None)
220        else :   
221            try :
222                policy = [x.strip() for x in fullpolicy.split('(', 1)]
223            except ValueError :   
[1192]224                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
[1152]225            if len(policy) == 1 :   
226                policy.append("")
227            (policy, args) = policy   
228            if args.endswith(')') :
229                args = args[:-1]
230            policy = policy.upper()   
231            if (policy == "EXTERNAL") and not args :
[1192]232                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
[1152]233            if policy not in validpolicies :
[1192]234                raise PyKotaConfigError, _("Option policy in section %s only supports values in %s") % (printername, str(validpolicies))
[1152]235            return (policy, args)
[695]236       
[1518]237    def getCrashRecipient(self) :   
238        """Returns the email address of the software crash messages recipient."""
239        try :
240            return self.getGlobalOption("crashrecipient")
241        except :   
242            return
243           
[695]244    def getSMTPServer(self) :   
245        """Returns the SMTP server to use to send messages to users."""
[853]246        try :
247            return self.getGlobalOption("smtpserver")
248        except PyKotaConfigError :   
249            return "localhost"
[695]250       
[1353]251    def getMailDomain(self) :   
252        """Returns the mail domain to use to send messages to users."""
253        try :
254            return self.getGlobalOption("maildomain")
255        except PyKotaConfigError :   
256            return 
257       
[1192]258    def getAdminMail(self, printername) :   
[695]259        """Returns the Email address of the Print Quota Administrator."""
[853]260        try :
[1192]261            return self.getPrinterOption(printername, "adminmail")
[853]262        except PyKotaConfigError :   
263            return "root@localhost"
[695]264       
[1192]265    def getAdmin(self, printername) :   
[695]266        """Returns the full name of the Print Quota Administrator."""
[853]267        try :
[1192]268            return self.getPrinterOption(printername, "admin")
[853]269        except PyKotaConfigError :   
270            return "root"
[708]271       
[1192]272    def getMailTo(self, printername) :   
[852]273        """Returns the recipient of email messages."""
[1192]274        validmailtos = [ "EXTERNAL", "NOBODY", "NONE", "NOONE", "BITBUCKET", "DEVNULL", "BOTH", "USER", "ADMIN" ]
[853]275        try :
[1192]276            fullmailto = self.getPrinterOption(printername, "mailto")
[853]277        except PyKotaConfigError :   
[1192]278            return ("BOTH", None)
279        else :   
280            try :
281                mailto = [x.strip() for x in fullmailto.split('(', 1)]
282            except ValueError :   
283                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
284            if len(mailto) == 1 :   
285                mailto.append("")
286            (mailto, args) = mailto   
287            if args.endswith(')') :
288                args = args[:-1]
289            mailto = mailto.upper()   
290            if (mailto == "EXTERNAL") and not args :
291                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
292            if mailto not in validmailtos :
293                raise PyKotaConfigError, _("Option mailto in section %s only supports values in %s") % (printername, str(validmailtos))
294            return (mailto, args)
[852]295       
[2054]296    def getMaxDenyBanners(self, printername) :   
297        """Returns the maximum number of deny banners to be printed for a particular user on a particular printer."""
298        try :
299            maxdb = self.getPrinterOption(printername, "maxdenybanners")
300        except PyKotaConfigError :   
301            return 0 # default value is to forbid printing a deny banner.
302        try :
303            value = int(maxdb.strip())
304            if value < 0 :
305                raise ValueError
306        except (TypeError, ValueError) :   
307            raise PyKotaConfigError, _("Invalid maximal deny banners counter %s") % maxdb
308        else :   
309            return value
310           
[1192]311    def getGraceDelay(self, printername) :   
[708]312        """Returns the grace delay in days."""
[731]313        try :
[1192]314            gd = self.getPrinterOption(printername, "gracedelay")
[853]315        except PyKotaConfigError :   
[1914]316            gd = 7      # default value of 7 days
[853]317        try :
[731]318            return int(gd)
[1077]319        except (TypeError, ValueError) :   
[773]320            raise PyKotaConfigError, _("Invalid grace delay %s") % gd
[1021]321           
[1077]322    def getPoorMan(self) :   
[1646]323        """Returns the poor man's threshold."""
[1077]324        try :
325            pm = self.getGlobalOption("poorman")
326        except PyKotaConfigError :   
[1914]327            pm = 1.0    # default value of 1 unit
[1077]328        try :
329            return float(pm)
330        except (TypeError, ValueError) :   
[1646]331            raise PyKotaConfigError, _("Invalid poor man's threshold %s") % pm
[1077]332           
333    def getPoorWarn(self) :   
334        """Returns the poor man's warning message."""
335        try :
336            return self.getGlobalOption("poorwarn")
337        except PyKotaConfigError :   
338            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.")
339           
[1192]340    def getHardWarn(self, printername) :   
[1077]341        """Returns the hard limit error message."""
342        try :
[1192]343            return self.getPrinterOption(printername, "hardwarn")
[1077]344        except PyKotaConfigError :   
[1192]345            return _("You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s.") % printername
[1077]346           
[1192]347    def getSoftWarn(self, printername) :   
[1077]348        """Returns the soft limit error message."""
349        try :
[1192]350            return self.getPrinterOption(printername, "softwarn")
[1077]351        except PyKotaConfigError :   
[1192]352            return _("You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s.") % printername
[1077]353           
[1875]354    def getPrivacy(self) :       
355        """Returns 1 if privacy is activated, else 0."""
356        return self.isTrue(self.getGlobalOption("privacy", ignore=1))
357       
[1021]358    def getDebug(self) :         
359        """Returns 1 if debugging is activated, else 0."""
[1227]360        return self.isTrue(self.getGlobalOption("debug", ignore=1))
[1130]361           
362    def getCaching(self) :         
363        """Returns 1 if database caching is enabled, else 0."""
[1227]364        return self.isTrue(self.getGlobalOption("storagecaching", ignore=1))
[1148]365           
[1356]366    def getLDAPCache(self) :         
367        """Returns 1 if low-level LDAP caching is enabled, else 0."""
368        return self.isTrue(self.getGlobalOption("ldapcache", ignore=1))
369           
[1148]370    def getDisableHistory(self) :         
371        """Returns 1 if we want to disable history, else 0."""
[1227]372        return self.isTrue(self.getGlobalOption("disablehistory", ignore=1))
373           
374    def getUserNameToLower(self) :         
375        """Returns 1 if we want to convert usernames to lowercase when printing, else 0."""
376        return self.isTrue(self.getGlobalOption("utolower", ignore=1))
[1757]377       
[1956]378    def getRejectUnknown(self) :         
379        """Returns 1 if we want to reject the creation of unknown users or groups, else 0."""
380        return self.isTrue(self.getGlobalOption("reject_unknown", ignore=1))
381       
[2066]382    def getDenyDuplicates(self, printername) :         
383        """Returns 1 if we want to deny duplicate jobs, else 0."""
384        try : 
385            return self.isTrue(self.getPrinterOption(printername, "denyduplicates"))
386        except PyKotaConfigError :   
387            return 0
388       
[1757]389    def getWinbindSeparator(self) :         
390        """Returns the winbind separator's value if it is set, else None."""
391        return self.getGlobalOption("winbind_separator", ignore=1)
[1914]392
393    def getAccountBanner(self, printername) :
394        """Returns which banner(s) to account for: NONE, BOTH, STARTING, ENDING."""
395        validvalues = [ "NONE", "BOTH", "STARTING", "ENDING" ]     
396        try :
397            value = self.getPrinterOption(printername, "accountbanner")
398        except PyKotaConfigError :   
399            return "BOTH"       # Default value of BOTH
400        else :   
[1916]401            value = value.strip().upper()
[1914]402            if value not in validvalues :
[1916]403                raise PyKotaConfigError, _("Option accountbanner in section %s only supports values in %s") % (printername, str(validvalues))
[1914]404            return value 
405
406    def getStartingBanner(self, printername) :
407        """Returns the startingbanner value if set, else None."""
408        try :
[1916]409            return self.getPrinterOption(printername, "startingbanner").strip()
[1914]410        except PyKotaConfigError :
411            return None
412
413    def getEndingBanner(self, printername) :
414        """Returns the endingbanner value if set, else None."""
415        try :
[1916]416            return self.getPrinterOption(printername, "endingbanner").strip()
[1914]417        except PyKotaConfigError :
418            return None
[2062]419           
420    def getTrustJobSize(self, printername) :
421        """Returns the normalized value of the trustjobsize's directive."""
422        try :
423            value = self.getPrinterOption(printername, "trustjobsize").strip().upper()
424        except PyKotaConfigError :
425            return (None, "YES")
426        else :   
427            if value == "YES" :
428                return (None, "YES")
429            try :   
430                (limit, replacement) = [p.strip() for p in value.split(">")[1].split(":")]
431                limit = int(limit)
432                try :
433                    replacement = int(replacement) 
434                except ValueError :   
435                    if replacement != "PRECOMPUTED" :
436                        raise
437                if limit < 0 :
438                    raise ValueError
439                if (replacement != "PRECOMPUTED") and (replacement < 0) :
440                    raise ValueError
441            except (IndexError, ValueError, TypeError) :
442                raise PyKotaConfigError, _("Option trustjobsize for printer %s is incorrect") % printername
443            return (limit, replacement)   
Note: See TracBrowser for help on using the browser.