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

Revision 2302, 20.5 kB (checked in by jerome, 19 years ago)

Updated the FSF's address

  • 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
[2302]19# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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()           
[2265]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()           
[2262]156   
[1192]157    def getAccounterBackend(self, printername) :   
[973]158        """Returns the accounter backend to use for a given printer.
159       
[1475]160           if it is not set, it defaults to 'hardware' which means ask printer
[973]161           for its internal lifetime page counter.
162        """   
[1475]163        validaccounters = [ "hardware", "software" ]     
[1371]164        fullaccounter = self.getPrinterOption(printername, "accounter").strip()
[1483]165        flower = fullaccounter.lower()
166        if flower.startswith("software") or flower.startswith("hardware") :   
[980]167            try :
168                (accounter, args) = [x.strip() for x in fullaccounter.split('(', 1)]
169            except ValueError :   
[1483]170                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
[980]171            if args.endswith(')') :
[2074]172                args = args[:-1].strip()
173            if (accounter == "hardware") and not args :
[1483]174                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
[1000]175            return (accounter.lower(), args)   
[1483]176        else :
[1192]177            raise PyKotaConfigError, _("Option accounter in section %s only supports values in %s") % (printername, str(validaccounters))
[973]178       
[1371]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           
[1495]193    def getPrinterEnforcement(self, printername) :   
194        """Returns if quota enforcement should be strict or laxist for the current printer."""
195        validenforcements = [ "STRICT", "LAXIST" ]     
196        try :
197            enforcement = self.getPrinterOption(printername, "enforcement")
198        except PyKotaConfigError :   
199            return "LAXIST"
200        else :   
201            enforcement = enforcement.upper()
202            if enforcement not in validenforcements :
203                raise PyKotaConfigError, _("Option enforcement in section %s only supports values in %s") % (printername, str(validenforcements))
204            return enforcement   
205           
[1687]206    def getPrinterOnAccounterError(self, printername) :   
207        """Returns what must be done whenever the accounter fails."""
208        validactions = [ "CONTINUE", "STOP" ]     
209        try :
210            action = self.getPrinterOption(printername, "onaccountererror")
211        except PyKotaConfigError :   
212            return "STOP"
213        else :   
214            action = action.upper()
215            if action not in validactions :
216                raise PyKotaConfigError, _("Option onaccountererror in section %s only supports values in %s") % (printername, str(validactions))
217            return action 
218           
[1192]219    def getPrinterPolicy(self, printername) :   
[695]220        """Returns the default policy for the current printer."""
[1152]221        validpolicies = [ "ALLOW", "DENY", "EXTERNAL" ]     
[853]222        try :
[1192]223            fullpolicy = self.getPrinterOption(printername, "policy")
[853]224        except PyKotaConfigError :   
[1152]225            return ("DENY", None)
226        else :   
227            try :
228                policy = [x.strip() for x in fullpolicy.split('(', 1)]
229            except ValueError :   
[1192]230                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
[1152]231            if len(policy) == 1 :   
232                policy.append("")
233            (policy, args) = policy   
234            if args.endswith(')') :
235                args = args[:-1]
236            policy = policy.upper()   
237            if (policy == "EXTERNAL") and not args :
[1192]238                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
[1152]239            if policy not in validpolicies :
[1192]240                raise PyKotaConfigError, _("Option policy in section %s only supports values in %s") % (printername, str(validpolicies))
[1152]241            return (policy, args)
[695]242       
[1518]243    def getCrashRecipient(self) :   
244        """Returns the email address of the software crash messages recipient."""
245        try :
246            return self.getGlobalOption("crashrecipient")
247        except :   
248            return
249           
[695]250    def getSMTPServer(self) :   
251        """Returns the SMTP server to use to send messages to users."""
[853]252        try :
253            return self.getGlobalOption("smtpserver")
254        except PyKotaConfigError :   
255            return "localhost"
[695]256       
[1353]257    def getMailDomain(self) :   
258        """Returns the mail domain to use to send messages to users."""
259        try :
260            return self.getGlobalOption("maildomain")
261        except PyKotaConfigError :   
262            return 
263       
[1192]264    def getAdminMail(self, printername) :   
[695]265        """Returns the Email address of the Print Quota Administrator."""
[853]266        try :
[1192]267            return self.getPrinterOption(printername, "adminmail")
[853]268        except PyKotaConfigError :   
269            return "root@localhost"
[695]270       
[1192]271    def getAdmin(self, printername) :   
[695]272        """Returns the full name of the Print Quota Administrator."""
[853]273        try :
[1192]274            return self.getPrinterOption(printername, "admin")
[853]275        except PyKotaConfigError :   
276            return "root"
[708]277       
[1192]278    def getMailTo(self, printername) :   
[852]279        """Returns the recipient of email messages."""
[1192]280        validmailtos = [ "EXTERNAL", "NOBODY", "NONE", "NOONE", "BITBUCKET", "DEVNULL", "BOTH", "USER", "ADMIN" ]
[853]281        try :
[1192]282            fullmailto = self.getPrinterOption(printername, "mailto")
[853]283        except PyKotaConfigError :   
[1192]284            return ("BOTH", None)
285        else :   
286            try :
287                mailto = [x.strip() for x in fullmailto.split('(', 1)]
288            except ValueError :   
289                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
290            if len(mailto) == 1 :   
291                mailto.append("")
292            (mailto, args) = mailto   
293            if args.endswith(')') :
294                args = args[:-1]
295            mailto = mailto.upper()   
296            if (mailto == "EXTERNAL") and not args :
297                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
298            if mailto not in validmailtos :
299                raise PyKotaConfigError, _("Option mailto in section %s only supports values in %s") % (printername, str(validmailtos))
300            return (mailto, args)
[852]301       
[2054]302    def getMaxDenyBanners(self, printername) :   
303        """Returns the maximum number of deny banners to be printed for a particular user on a particular printer."""
304        try :
305            maxdb = self.getPrinterOption(printername, "maxdenybanners")
306        except PyKotaConfigError :   
307            return 0 # default value is to forbid printing a deny banner.
308        try :
309            value = int(maxdb.strip())
310            if value < 0 :
311                raise ValueError
312        except (TypeError, ValueError) :   
313            raise PyKotaConfigError, _("Invalid maximal deny banners counter %s") % maxdb
314        else :   
315            return value
316           
[1192]317    def getGraceDelay(self, printername) :   
[708]318        """Returns the grace delay in days."""
[731]319        try :
[1192]320            gd = self.getPrinterOption(printername, "gracedelay")
[853]321        except PyKotaConfigError :   
[1914]322            gd = 7      # default value of 7 days
[853]323        try :
[731]324            return int(gd)
[1077]325        except (TypeError, ValueError) :   
[773]326            raise PyKotaConfigError, _("Invalid grace delay %s") % gd
[1021]327           
[1077]328    def getPoorMan(self) :   
[1646]329        """Returns the poor man's threshold."""
[1077]330        try :
331            pm = self.getGlobalOption("poorman")
332        except PyKotaConfigError :   
[1914]333            pm = 1.0    # default value of 1 unit
[1077]334        try :
335            return float(pm)
336        except (TypeError, ValueError) :   
[1646]337            raise PyKotaConfigError, _("Invalid poor man's threshold %s") % pm
[1077]338           
339    def getPoorWarn(self) :   
340        """Returns the poor man's warning message."""
341        try :
342            return self.getGlobalOption("poorwarn")
343        except PyKotaConfigError :   
344            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.")
345           
[1192]346    def getHardWarn(self, printername) :   
[1077]347        """Returns the hard limit error message."""
348        try :
[1192]349            return self.getPrinterOption(printername, "hardwarn")
[1077]350        except PyKotaConfigError :   
[1192]351            return _("You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s.") % printername
[1077]352           
[1192]353    def getSoftWarn(self, printername) :   
[1077]354        """Returns the soft limit error message."""
355        try :
[1192]356            return self.getPrinterOption(printername, "softwarn")
[1077]357        except PyKotaConfigError :   
[1192]358            return _("You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s.") % printername
[1077]359           
[1875]360    def getPrivacy(self) :       
361        """Returns 1 if privacy is activated, else 0."""
362        return self.isTrue(self.getGlobalOption("privacy", ignore=1))
363       
[1021]364    def getDebug(self) :         
365        """Returns 1 if debugging is activated, else 0."""
[1227]366        return self.isTrue(self.getGlobalOption("debug", ignore=1))
[1130]367           
368    def getCaching(self) :         
369        """Returns 1 if database caching is enabled, else 0."""
[1227]370        return self.isTrue(self.getGlobalOption("storagecaching", ignore=1))
[1148]371           
[1356]372    def getLDAPCache(self) :         
373        """Returns 1 if low-level LDAP caching is enabled, else 0."""
374        return self.isTrue(self.getGlobalOption("ldapcache", ignore=1))
375           
[1148]376    def getDisableHistory(self) :         
377        """Returns 1 if we want to disable history, else 0."""
[1227]378        return self.isTrue(self.getGlobalOption("disablehistory", ignore=1))
379           
380    def getUserNameToLower(self) :         
381        """Returns 1 if we want to convert usernames to lowercase when printing, else 0."""
382        return self.isTrue(self.getGlobalOption("utolower", ignore=1))
[1757]383       
[1956]384    def getRejectUnknown(self) :         
385        """Returns 1 if we want to reject the creation of unknown users or groups, else 0."""
386        return self.isTrue(self.getGlobalOption("reject_unknown", ignore=1))
387       
[2066]388    def getDenyDuplicates(self, printername) :         
389        """Returns 1 if we want to deny duplicate jobs, else 0."""
390        try : 
391            return self.isTrue(self.getPrinterOption(printername, "denyduplicates"))
392        except PyKotaConfigError :   
393            return 0
394       
[1757]395    def getWinbindSeparator(self) :         
396        """Returns the winbind separator's value if it is set, else None."""
397        return self.getGlobalOption("winbind_separator", ignore=1)
[1914]398
399    def getAccountBanner(self, printername) :
400        """Returns which banner(s) to account for: NONE, BOTH, STARTING, ENDING."""
401        validvalues = [ "NONE", "BOTH", "STARTING", "ENDING" ]     
402        try :
403            value = self.getPrinterOption(printername, "accountbanner")
404        except PyKotaConfigError :   
405            return "BOTH"       # Default value of BOTH
406        else :   
[1916]407            value = value.strip().upper()
[1914]408            if value not in validvalues :
[1916]409                raise PyKotaConfigError, _("Option accountbanner in section %s only supports values in %s") % (printername, str(validvalues))
[1914]410            return value 
411
412    def getStartingBanner(self, printername) :
413        """Returns the startingbanner value if set, else None."""
414        try :
[1916]415            return self.getPrinterOption(printername, "startingbanner").strip()
[1914]416        except PyKotaConfigError :
417            return None
418
419    def getEndingBanner(self, printername) :
420        """Returns the endingbanner value if set, else None."""
421        try :
[1916]422            return self.getPrinterOption(printername, "endingbanner").strip()
[1914]423        except PyKotaConfigError :
424            return None
[2062]425           
426    def getTrustJobSize(self, printername) :
427        """Returns the normalized value of the trustjobsize's directive."""
428        try :
429            value = self.getPrinterOption(printername, "trustjobsize").strip().upper()
430        except PyKotaConfigError :
431            return (None, "YES")
432        else :   
433            if value == "YES" :
434                return (None, "YES")
435            try :   
436                (limit, replacement) = [p.strip() for p in value.split(">")[1].split(":")]
437                limit = int(limit)
438                try :
439                    replacement = int(replacement) 
440                except ValueError :   
441                    if replacement != "PRECOMPUTED" :
442                        raise
443                if limit < 0 :
444                    raise ValueError
445                if (replacement != "PRECOMPUTED") and (replacement < 0) :
446                    raise ValueError
447            except (IndexError, ValueError, TypeError) :
448                raise PyKotaConfigError, _("Option trustjobsize for printer %s is incorrect") % printername
449            return (limit, replacement)   
Note: See TracBrowser for help on using the browser.