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

Revision 2405, 23.5 kB (checked in by jerome, 19 years ago)

Added support for the new 'directory' and 'keepfiles' directives.
Both will be used in the new cupspykota backend.

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