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

Revision 2385, 22.8 kB (checked in by jerome, 19 years ago)

Added two new directives :

unknown_billingcode : defines what to do when printing if the billing code

used is not present in the database.

overwrite_jobticket : defines a command to launch when overwriting the username

or the billing code used is desirable (for example when
an user interaction should take place, see the work
of George Farris)

Severity : no support for this in the backend right now, so be patient (again).

  • 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."""
[2308]51        if (option is not None) and (option.strip().upper() in ['Y', 'YES', '1', 'ON', 'T', 'TRUE']) :
[1227]52            return 1
53        else :   
54            return 0
[695]55                       
[2308]56    def isFalse(self, option) :       
57        """Returns 1 if option is set to false, else 0."""
58        if (option is not None) and (option.strip().upper() in ['N', 'NO', '0', 'OFF', 'F', 'FALSE']) :
59            return 1
60        else :   
61            return 0
62                       
[695]63    def getPrinterNames(self) :   
64        """Returns the list of configured printers, i.e. all sections names minus 'global'."""
65        return [pname for pname in self.config.sections() if pname != "global"]
66       
[802]67    def getGlobalOption(self, option, ignore=0) :   
68        """Returns an option from the global section, or raises a PyKotaConfigError if ignore is not set, else returns None."""
69        try :
70            return self.config.get("global", option, raw=1)
71        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
72            if ignore :
73                return
74            else :
75                raise PyKotaConfigError, _("Option %s not found in section global of %s") % (option, self.filename)
76               
[1192]77    def getPrinterOption(self, printername, option) :   
[802]78        """Returns an option from the printer section, or the global section, or raises a PyKotaConfigError."""
79        globaloption = self.getGlobalOption(option, ignore=1)
80        try :
[1192]81            return self.config.get(printername, option, raw=1)
[802]82        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
83            if globaloption is not None :
84                return globaloption
85            else :
[1192]86                raise PyKotaConfigError, _("Option %s not found in section %s of %s") % (option, printername, self.filename)
[802]87       
[695]88    def getStorageBackend(self) :   
[800]89        """Returns the storage backend information as a Python mapping."""       
90        backendinfo = {}
[695]91        for option in [ "storagebackend", "storageserver", \
[1087]92                        "storagename", "storageuser", \
[695]93                      ] :
[804]94            backendinfo[option] = self.getGlobalOption(option)
[1087]95        backendinfo["storageuserpw"] = self.getGlobalOption("storageuserpw", ignore=1)  # password is optional
96        backendinfo["storageadmin"] = None
97        backendinfo["storageadminpw"] = None
98        adminconf = ConfigParser.ConfigParser()
[1785]99        filename = os.path.join(self.directory, "pykotadmin.conf")
100        adminconf.read([filename])
[1087]101        if adminconf.sections() : # were we able to read the file ?
102            try :
103                backendinfo["storageadmin"] = adminconf.get("global", "storageadmin", raw=1)
104            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
[1785]105                raise PyKotaConfigError, _("Option %s not found in section global of %s") % ("storageadmin", filename)
106            else :   
107                self.isAdmin = 1 # We are a PyKota administrator
[1087]108            try :
109                backendinfo["storageadminpw"] = adminconf.get("global", "storageadminpw", raw=1)
110            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
111                pass # Password is optional
[800]112        return backendinfo
[695]113       
[1029]114    def getLDAPInfo(self) :   
115        """Returns some hints for the LDAP backend."""       
116        ldapinfo = {}
117        for option in [ "userbase", "userrdn", \
[1041]118                        "balancebase", "balancerdn", \
[1029]119                        "groupbase", "grouprdn", "groupmembers", \
120                        "printerbase", "printerrdn", \
121                        "userquotabase", "groupquotabase", \
[2370]122                        "jobbase", "lastjobbase", "billingcodebase", \
[1105]123                        "newuser", "newgroup", \
[1111]124                        "usermail", \
[1029]125                      ] :
[1105]126            ldapinfo[option] = self.getGlobalOption(option).strip()
127        for field in ["newuser", "newgroup"] :
128            if ldapinfo[field].lower().startswith('attach(') :
129                ldapinfo[field] = ldapinfo[field][7:-1]
[1968]130               
131        # should we use TLS, by default (if unset) value is NO       
132        ldapinfo["ldaptls"] = self.isTrue(self.getGlobalOption("ldaptls", ignore=1))
133        ldapinfo["cacert"] = self.getGlobalOption("cacert", ignore=1)
134        if ldapinfo["cacert"] :
135            ldapinfo["cacert"] = ldapinfo["cacert"].strip()
136        if ldapinfo["ldaptls"] :   
137            if not os.access(ldapinfo["cacert"] or "", os.R_OK) :
138                raise PyKotaConfigError, _("Option ldaptls is set, but certificate %s is not readable.") % str(ldapinfo["cacert"])
[1029]139        return ldapinfo
140       
[695]141    def getLoggingBackend(self) :   
142        """Returns the logging backend information."""
[802]143        validloggers = [ "stderr", "system" ] 
[853]144        try :
145            logger = self.getGlobalOption("logger").lower()
146        except PyKotaConfigError :   
147            logger = "system"
[802]148        if logger not in validloggers :             
149            raise PyKotaConfigError, _("Option logger only supports values in %s") % str(validloggers)
150        return logger   
[695]151       
[2262]152    def getLogoURL(self) :
153        """Returns the URL to use for the logo in the CGI scripts."""
154        url = self.getGlobalOption("logourl", ignore=1) or \
155                   "http://www.librelogiciel.com/software/PyKota/pykota.png"
156        return url.strip()           
[2265]157       
158    def getLogoLink(self) :
159        """Returns the URL to go to when the user clicks on the logo in the CGI scripts."""
160        url = self.getGlobalOption("logolink", ignore=1) or \
161                   "http://www.librelogiciel.com/software/"
162        return url.strip()           
[2262]163   
[1192]164    def getAccounterBackend(self, printername) :   
[973]165        """Returns the accounter backend to use for a given printer.
166       
[1475]167           if it is not set, it defaults to 'hardware' which means ask printer
[973]168           for its internal lifetime page counter.
169        """   
[1475]170        validaccounters = [ "hardware", "software" ]     
[1371]171        fullaccounter = self.getPrinterOption(printername, "accounter").strip()
[1483]172        flower = fullaccounter.lower()
173        if flower.startswith("software") or flower.startswith("hardware") :   
[980]174            try :
175                (accounter, args) = [x.strip() for x in fullaccounter.split('(', 1)]
176            except ValueError :   
[1483]177                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
[980]178            if args.endswith(')') :
[2074]179                args = args[:-1].strip()
180            if (accounter == "hardware") and not args :
[1483]181                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
[1000]182            return (accounter.lower(), args)   
[1483]183        else :
[1192]184            raise PyKotaConfigError, _("Option accounter in section %s only supports values in %s") % (printername, str(validaccounters))
[973]185       
[1371]186    def getPreHook(self, printername) :   
187        """Returns the prehook command line to launch, or None if unset."""
188        try :
189            return self.getPrinterOption(printername, "prehook").strip()
190        except PyKotaConfigError :   
191            return      # No command to launch in the pre-hook
192           
193    def getPostHook(self, printername) :   
194        """Returns the posthook command line to launch, or None if unset."""
195        try :
196            return self.getPrinterOption(printername, "posthook").strip()
197        except PyKotaConfigError :   
198            return      # No command to launch in the post-hook
199           
[2307]200    def getStripTitle(self, printername) :   
201        """Returns the striptitle directive's content, or None if unset."""
202        try :
203            return self.getPrinterOption(printername, "striptitle").strip()
204        except PyKotaConfigError :   
205            return      # No prefix to strip off
206           
[2385]207    def getOverwriteJobTicket(self, printername) :       
208        """Returns the overwrite_jobticket directive's content, or None if unset."""
209        try :
210            return self.getPrinterOption(printername, "overwrite_jobticket").strip()
211        except PyKotaConfigError :   
212            return      # No overwriting will be done
213       
214    def getUnknownBillingCode(self, printername) :       
215        """Returns the unknown_billingcode directive's content, or the default value if unset."""
216        validvalues = [ "CREATE", "DENY" ]
217        try :
218            fullvalue = self.getPrinterOption(printername, "unknown_billingcode")
219        except PyKotaConfigError :   
220            return ("CREATE", None)
221        else :   
222            try :
223                value = [x.strip() for x in fullvalue.split('(', 1)]
224            except ValueError :   
225                raise PyKotaConfigError, _("Invalid unknown_billingcode directive %s for printer %s") % (fullvalue, printername)
226            if len(value) == 1 :   
227                value.append("")
228            (value, args) = value   
229            if args.endswith(')') :
230                args = args[:-1]
231            value = value.upper()   
232            if (value == "DENY") and not args :
233                return ("DENY", None)
234            if value not in validvalues :
235                raise PyKotaConfigError, _("Directive unknown_billingcode in section %s only supports values in %s") % (printername, str(validvalues))
236            return (value, args)
237       
[1495]238    def getPrinterEnforcement(self, printername) :   
239        """Returns if quota enforcement should be strict or laxist for the current printer."""
240        validenforcements = [ "STRICT", "LAXIST" ]     
241        try :
242            enforcement = self.getPrinterOption(printername, "enforcement")
243        except PyKotaConfigError :   
244            return "LAXIST"
245        else :   
246            enforcement = enforcement.upper()
247            if enforcement not in validenforcements :
248                raise PyKotaConfigError, _("Option enforcement in section %s only supports values in %s") % (printername, str(validenforcements))
249            return enforcement   
250           
[1687]251    def getPrinterOnAccounterError(self, printername) :   
252        """Returns what must be done whenever the accounter fails."""
253        validactions = [ "CONTINUE", "STOP" ]     
254        try :
255            action = self.getPrinterOption(printername, "onaccountererror")
256        except PyKotaConfigError :   
257            return "STOP"
258        else :   
259            action = action.upper()
260            if action not in validactions :
261                raise PyKotaConfigError, _("Option onaccountererror in section %s only supports values in %s") % (printername, str(validactions))
262            return action 
263           
[1192]264    def getPrinterPolicy(self, printername) :   
[695]265        """Returns the default policy for the current printer."""
[1152]266        validpolicies = [ "ALLOW", "DENY", "EXTERNAL" ]     
[853]267        try :
[1192]268            fullpolicy = self.getPrinterOption(printername, "policy")
[853]269        except PyKotaConfigError :   
[1152]270            return ("DENY", None)
271        else :   
272            try :
273                policy = [x.strip() for x in fullpolicy.split('(', 1)]
274            except ValueError :   
[1192]275                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
[1152]276            if len(policy) == 1 :   
277                policy.append("")
278            (policy, args) = policy   
279            if args.endswith(')') :
280                args = args[:-1]
281            policy = policy.upper()   
282            if (policy == "EXTERNAL") and not args :
[1192]283                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
[1152]284            if policy not in validpolicies :
[1192]285                raise PyKotaConfigError, _("Option policy in section %s only supports values in %s") % (printername, str(validpolicies))
[1152]286            return (policy, args)
[695]287       
[1518]288    def getCrashRecipient(self) :   
289        """Returns the email address of the software crash messages recipient."""
290        try :
291            return self.getGlobalOption("crashrecipient")
292        except :   
293            return
294           
[695]295    def getSMTPServer(self) :   
296        """Returns the SMTP server to use to send messages to users."""
[853]297        try :
298            return self.getGlobalOption("smtpserver")
299        except PyKotaConfigError :   
300            return "localhost"
[695]301       
[1353]302    def getMailDomain(self) :   
303        """Returns the mail domain to use to send messages to users."""
304        try :
305            return self.getGlobalOption("maildomain")
306        except PyKotaConfigError :   
307            return 
308       
[1192]309    def getAdminMail(self, printername) :   
[695]310        """Returns the Email address of the Print Quota Administrator."""
[853]311        try :
[1192]312            return self.getPrinterOption(printername, "adminmail")
[853]313        except PyKotaConfigError :   
314            return "root@localhost"
[695]315       
[1192]316    def getAdmin(self, printername) :   
[695]317        """Returns the full name of the Print Quota Administrator."""
[853]318        try :
[1192]319            return self.getPrinterOption(printername, "admin")
[853]320        except PyKotaConfigError :   
321            return "root"
[708]322       
[1192]323    def getMailTo(self, printername) :   
[852]324        """Returns the recipient of email messages."""
[1192]325        validmailtos = [ "EXTERNAL", "NOBODY", "NONE", "NOONE", "BITBUCKET", "DEVNULL", "BOTH", "USER", "ADMIN" ]
[853]326        try :
[1192]327            fullmailto = self.getPrinterOption(printername, "mailto")
[853]328        except PyKotaConfigError :   
[1192]329            return ("BOTH", None)
330        else :   
331            try :
332                mailto = [x.strip() for x in fullmailto.split('(', 1)]
333            except ValueError :   
334                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
335            if len(mailto) == 1 :   
336                mailto.append("")
337            (mailto, args) = mailto   
338            if args.endswith(')') :
339                args = args[:-1]
340            mailto = mailto.upper()   
341            if (mailto == "EXTERNAL") and not args :
342                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
343            if mailto not in validmailtos :
344                raise PyKotaConfigError, _("Option mailto in section %s only supports values in %s") % (printername, str(validmailtos))
345            return (mailto, args)
[852]346       
[2054]347    def getMaxDenyBanners(self, printername) :   
348        """Returns the maximum number of deny banners to be printed for a particular user on a particular printer."""
349        try :
350            maxdb = self.getPrinterOption(printername, "maxdenybanners")
351        except PyKotaConfigError :   
352            return 0 # default value is to forbid printing a deny banner.
353        try :
354            value = int(maxdb.strip())
355            if value < 0 :
356                raise ValueError
357        except (TypeError, ValueError) :   
358            raise PyKotaConfigError, _("Invalid maximal deny banners counter %s") % maxdb
359        else :   
360            return value
361           
[1192]362    def getGraceDelay(self, printername) :   
[708]363        """Returns the grace delay in days."""
[731]364        try :
[1192]365            gd = self.getPrinterOption(printername, "gracedelay")
[853]366        except PyKotaConfigError :   
[1914]367            gd = 7      # default value of 7 days
[853]368        try :
[731]369            return int(gd)
[1077]370        except (TypeError, ValueError) :   
[773]371            raise PyKotaConfigError, _("Invalid grace delay %s") % gd
[1021]372           
[1077]373    def getPoorMan(self) :   
[1646]374        """Returns the poor man's threshold."""
[1077]375        try :
376            pm = self.getGlobalOption("poorman")
377        except PyKotaConfigError :   
[1914]378            pm = 1.0    # default value of 1 unit
[1077]379        try :
380            return float(pm)
381        except (TypeError, ValueError) :   
[1646]382            raise PyKotaConfigError, _("Invalid poor man's threshold %s") % pm
[1077]383           
384    def getPoorWarn(self) :   
385        """Returns the poor man's warning message."""
386        try :
387            return self.getGlobalOption("poorwarn")
388        except PyKotaConfigError :   
389            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.")
390           
[1192]391    def getHardWarn(self, printername) :   
[1077]392        """Returns the hard limit error message."""
393        try :
[1192]394            return self.getPrinterOption(printername, "hardwarn")
[1077]395        except PyKotaConfigError :   
[1192]396            return _("You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s.") % printername
[1077]397           
[1192]398    def getSoftWarn(self, printername) :   
[1077]399        """Returns the soft limit error message."""
400        try :
[1192]401            return self.getPrinterOption(printername, "softwarn")
[1077]402        except PyKotaConfigError :   
[1192]403            return _("You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s.") % printername
[1077]404           
[1875]405    def getPrivacy(self) :       
406        """Returns 1 if privacy is activated, else 0."""
407        return self.isTrue(self.getGlobalOption("privacy", ignore=1))
408       
[1021]409    def getDebug(self) :         
410        """Returns 1 if debugging is activated, else 0."""
[1227]411        return self.isTrue(self.getGlobalOption("debug", ignore=1))
[1130]412           
413    def getCaching(self) :         
414        """Returns 1 if database caching is enabled, else 0."""
[1227]415        return self.isTrue(self.getGlobalOption("storagecaching", ignore=1))
[1148]416           
[1356]417    def getLDAPCache(self) :         
418        """Returns 1 if low-level LDAP caching is enabled, else 0."""
419        return self.isTrue(self.getGlobalOption("ldapcache", ignore=1))
420           
[1148]421    def getDisableHistory(self) :         
422        """Returns 1 if we want to disable history, else 0."""
[1227]423        return self.isTrue(self.getGlobalOption("disablehistory", ignore=1))
424           
425    def getUserNameToLower(self) :         
426        """Returns 1 if we want to convert usernames to lowercase when printing, else 0."""
427        return self.isTrue(self.getGlobalOption("utolower", ignore=1))
[1757]428       
[1956]429    def getRejectUnknown(self) :         
430        """Returns 1 if we want to reject the creation of unknown users or groups, else 0."""
431        return self.isTrue(self.getGlobalOption("reject_unknown", ignore=1))
432       
[2066]433    def getDenyDuplicates(self, printername) :         
[2308]434        """Returns 1 or a command if we want to deny duplicate jobs, else 0."""
[2066]435        try : 
[2308]436            denyduplicates = self.getPrinterOption(printername, "denyduplicates")
[2066]437        except PyKotaConfigError :   
438            return 0
[2308]439        else :   
440            if self.isTrue(denyduplicates) :
441                return 1
442            elif self.isFalse(denyduplicates) :
443                return 0
444            else :   
445                # it's a command to run.
446                return denyduplicates
[2066]447       
[1757]448    def getWinbindSeparator(self) :         
449        """Returns the winbind separator's value if it is set, else None."""
450        return self.getGlobalOption("winbind_separator", ignore=1)
[1914]451
452    def getAccountBanner(self, printername) :
453        """Returns which banner(s) to account for: NONE, BOTH, STARTING, ENDING."""
454        validvalues = [ "NONE", "BOTH", "STARTING", "ENDING" ]     
455        try :
456            value = self.getPrinterOption(printername, "accountbanner")
457        except PyKotaConfigError :   
458            return "BOTH"       # Default value of BOTH
459        else :   
[1916]460            value = value.strip().upper()
[1914]461            if value not in validvalues :
[1916]462                raise PyKotaConfigError, _("Option accountbanner in section %s only supports values in %s") % (printername, str(validvalues))
[1914]463            return value 
464
465    def getStartingBanner(self, printername) :
466        """Returns the startingbanner value if set, else None."""
467        try :
[1916]468            return self.getPrinterOption(printername, "startingbanner").strip()
[1914]469        except PyKotaConfigError :
470            return None
471
472    def getEndingBanner(self, printername) :
473        """Returns the endingbanner value if set, else None."""
474        try :
[1916]475            return self.getPrinterOption(printername, "endingbanner").strip()
[1914]476        except PyKotaConfigError :
477            return None
[2062]478           
479    def getTrustJobSize(self, printername) :
480        """Returns the normalized value of the trustjobsize's directive."""
481        try :
482            value = self.getPrinterOption(printername, "trustjobsize").strip().upper()
483        except PyKotaConfigError :
484            return (None, "YES")
485        else :   
486            if value == "YES" :
487                return (None, "YES")
488            try :   
489                (limit, replacement) = [p.strip() for p in value.split(">")[1].split(":")]
490                limit = int(limit)
491                try :
492                    replacement = int(replacement) 
493                except ValueError :   
494                    if replacement != "PRECOMPUTED" :
495                        raise
496                if limit < 0 :
497                    raise ValueError
498                if (replacement != "PRECOMPUTED") and (replacement < 0) :
499                    raise ValueError
500            except (IndexError, ValueError, TypeError) :
501                raise PyKotaConfigError, _("Option trustjobsize for printer %s is incorrect") % printername
502            return (limit, replacement)   
Note: See TracBrowser for help on using the browser.