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

Revision 3296, 35.6 kB (checked in by jerome, 16 years ago)

Introduces the 'config_charset' directive to specify the character
set to use when decoding the configuration files' contents.
All directives are now decoded to unicode strings for internal use.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[3260]1# -*- coding: UTF-8 -*-
[695]2#
[3260]3# PyKota : Print Quotas for CUPS
[695]4#
[3275]5# (c) 2003, 2004, 2005, 2006, 2007, 2008 Jerome Alet <alet@librelogiciel.com>
[3260]6# This program is free software: you can redistribute it and/or modify
[873]7# it under the terms of the GNU General Public License as published by
[3260]8# the Free Software Foundation, either version 3 of the License, or
[873]9# (at your option) any later version.
[3260]10#
[873]11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
[3260]17# along with this program.  If not, see <http://www.gnu.org/licenses/>.
[695]18#
19# $Id$
20#
[2074]21#
[695]22
[3184]23"""This module defines classes used to parse PyKota configuration files."""
24
[695]25import os
[2405]26import tempfile
[695]27import ConfigParser
28
[3288]29from pykota.errors import PyKotaConfigError   
30
[695]31class PyKotaConfig :
32    """A class to deal with PyKota's configuration."""
33    def __init__(self, directory) :
34        """Reads and checks the configuration file."""
[1785]35        self.isAdmin = 0
36        self.directory = directory
[695]37        self.filename = os.path.join(directory, "pykota.conf")
[2418]38        self.adminfilename = os.path.join(directory, "pykotadmin.conf")
[2421]39        if not os.access(self.filename, os.R_OK) :
40            raise PyKotaConfigError, _("Configuration file %s can't be read. Please check that the file exists and that your permissions are sufficient.") % self.filename
[2418]41        if not os.path.isfile(self.adminfilename) :
42            raise PyKotaConfigError, _("Configuration file %s not found.") % self.adminfilename
43        if os.access(self.adminfilename, os.R_OK) :   
44            self.isAdmin = 1
[695]45        self.config = ConfigParser.ConfigParser()
46        self.config.read([self.filename])
[3296]47        try :
48            self.config_charset = self.config.get("global", \
49                                                  "config_charset", \
50                                                   raw=1)
51        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :
52            self.config_charset = "UTF-8"
[1227]53           
54    def isTrue(self, option) :       
[3126]55        """Returns True if option is set to true, else False."""
[2308]56        if (option is not None) and (option.strip().upper() in ['Y', 'YES', '1', 'ON', 'T', 'TRUE']) :
[3126]57            return True
[1227]58        else :   
[3126]59            return False
[695]60                       
[2308]61    def isFalse(self, option) :       
[3126]62        """Returns True if option is set to false, else False."""
[2308]63        if (option is not None) and (option.strip().upper() in ['N', 'NO', '0', 'OFF', 'F', 'FALSE']) :
[3126]64            return True
[2308]65        else :   
[3126]66            return False
[2308]67                       
[695]68    def getPrinterNames(self) :   
69        """Returns the list of configured printers, i.e. all sections names minus 'global'."""
70        return [pname for pname in self.config.sections() if pname != "global"]
71       
[3296]72    def getGlobalOption(self, option, ignore=False) :   
[802]73        """Returns an option from the global section, or raises a PyKotaConfigError if ignore is not set, else returns None."""
74        try :
[3296]75            return self.config.get("global", option, raw=1).decode(self.config_charset)
[802]76        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
77            if ignore :
[3169]78                return None
[802]79            else :
80                raise PyKotaConfigError, _("Option %s not found in section global of %s") % (option, self.filename)
81               
[1192]82    def getPrinterOption(self, printername, option) :   
[802]83        """Returns an option from the printer section, or the global section, or raises a PyKotaConfigError."""
[3296]84        globaloption = self.getGlobalOption(option, ignore=True)
[802]85        try :
[3296]86            return self.config.get(printername, option, raw=1).decode(self.config_charset)
[802]87        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
88            if globaloption is not None :
89                return globaloption
90            else :
[1192]91                raise PyKotaConfigError, _("Option %s not found in section %s of %s") % (option, printername, self.filename)
[802]92       
[695]93    def getStorageBackend(self) :   
[800]94        """Returns the storage backend information as a Python mapping."""       
95        backendinfo = {}
[2593]96        backend = self.getGlobalOption("storagebackend").lower()
97        backendinfo["storagebackend"] = backend
98        if backend == "sqlitestorage" :
99            issqlite = 1
100            backendinfo["storagename"] = self.getGlobalOption("storagename")
101            for option in ["storageserver", "storageuser", "storageuserpw"] :
102                backendinfo[option] = None         
103        else :
104            issqlite = 0
105            for option in ["storageserver", "storagename", "storageuser"] :
106                backendinfo[option] = self.getGlobalOption(option)
[3296]107            backendinfo["storageuserpw"] = self.getGlobalOption("storageuserpw", ignore=True)  # password is optional
[2593]108           
[1087]109        backendinfo["storageadmin"] = None
110        backendinfo["storageadminpw"] = None
[2418]111        if self.isAdmin :
112            adminconf = ConfigParser.ConfigParser()
113            adminconf.read([self.adminfilename])
114            if adminconf.sections() : # were we able to read the file ?
115                try :
[3296]116                    backendinfo["storageadmin"] = adminconf.get("global", "storageadmin", raw=1).decode(self.config_charset)
[2418]117                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
[2593]118                    if not issqlite :
119                        raise PyKotaConfigError, _("Option %s not found in section global of %s") % ("storageadmin", self.adminfilename)
[2418]120                try :
[3296]121                    backendinfo["storageadminpw"] = adminconf.get("global", "storageadminpw", raw=1).decode(self.config_charset)
[2418]122                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
123                    pass # Password is optional
124                # Now try to overwrite the storagebackend, storageserver
125                # and storagename. This allows admins to use the master LDAP
126                # server directly and users to use the replicas transparently.
127                try :
[3296]128                    backendinfo["storagebackend"] = adminconf.get("global", "storagebackend", raw=1).decode(self.config_charset)
[2418]129                except ConfigParser.NoOptionError :
130                    pass
131                try :
[3296]132                    backendinfo["storageserver"] = adminconf.get("global", "storageserver", raw=1).decode(self.config_charset)
[2418]133                except ConfigParser.NoOptionError :
134                    pass
135                try :
[3296]136                    backendinfo["storagename"] = adminconf.get("global", "storagename", raw=1).decode(self.config_charset)
[2418]137                except ConfigParser.NoOptionError :
138                    pass
[800]139        return backendinfo
[695]140       
[1029]141    def getLDAPInfo(self) :   
142        """Returns some hints for the LDAP backend."""       
143        ldapinfo = {}
144        for option in [ "userbase", "userrdn", \
[1041]145                        "balancebase", "balancerdn", \
[1029]146                        "groupbase", "grouprdn", "groupmembers", \
147                        "printerbase", "printerrdn", \
148                        "userquotabase", "groupquotabase", \
[2370]149                        "jobbase", "lastjobbase", "billingcodebase", \
[1105]150                        "newuser", "newgroup", \
[1111]151                        "usermail", \
[1029]152                      ] :
[1105]153            ldapinfo[option] = self.getGlobalOption(option).strip()
154        for field in ["newuser", "newgroup"] :
155            if ldapinfo[field].lower().startswith('attach(') :
156                ldapinfo[field] = ldapinfo[field][7:-1]
[1968]157               
158        # should we use TLS, by default (if unset) value is NO       
[3296]159        ldapinfo["ldaptls"] = self.isTrue(self.getGlobalOption("ldaptls", ignore=True))
160        ldapinfo["cacert"] = self.getGlobalOption("cacert", ignore=True)
[1968]161        if ldapinfo["cacert"] :
162            ldapinfo["cacert"] = ldapinfo["cacert"].strip()
163        if ldapinfo["ldaptls"] :   
164            if not os.access(ldapinfo["cacert"] or "", os.R_OK) :
165                raise PyKotaConfigError, _("Option ldaptls is set, but certificate %s is not readable.") % str(ldapinfo["cacert"])
[1029]166        return ldapinfo
167       
[695]168    def getLoggingBackend(self) :   
169        """Returns the logging backend information."""
[802]170        validloggers = [ "stderr", "system" ] 
[853]171        try :
172            logger = self.getGlobalOption("logger").lower()
173        except PyKotaConfigError :   
174            logger = "system"
[802]175        if logger not in validloggers :             
176            raise PyKotaConfigError, _("Option logger only supports values in %s") % str(validloggers)
177        return logger   
[695]178       
[2262]179    def getLogoURL(self) :
180        """Returns the URL to use for the logo in the CGI scripts."""
[3296]181        url = self.getGlobalOption("logourl", ignore=True) or \
[2909]182                   "http://www.pykota.com/pykota.png"
[2262]183        return url.strip()           
[2265]184       
185    def getLogoLink(self) :
186        """Returns the URL to go to when the user clicks on the logo in the CGI scripts."""
[3296]187        url = self.getGlobalOption("logolink", ignore=True) or \
[2909]188                   "http://www.pykota.com/"
[2265]189        return url.strip()           
[2262]190   
[2635]191    def getPreAccounterBackend(self, printername) :   
192        """Returns the preaccounter backend to use for a given printer."""
[3034]193        validaccounters = [ "software", "ink" ]     
[2635]194        try :
195            fullaccounter = self.getPrinterOption(printername, "preaccounter").strip()
196        except PyKotaConfigError :   
197            return ("software", "")
198        else :   
199            flower = fullaccounter.lower()
[3029]200            for vac in validaccounters :
201                if flower.startswith(vac) :   
202                    try :
203                        (accounter, args) = [x.strip() for x in fullaccounter.split('(', 1)]
204                    except ValueError :   
205                        raise PyKotaConfigError, _("Invalid preaccounter %s for printer %s") % (fullaccounter, printername)
206                    if args.endswith(')') :
207                        args = args[:-1].strip()
[3034]208                    if (vac == "ink") and not args :   
209                        raise PyKotaConfigError, _("Invalid preaccounter %s for printer %s") % (fullaccounter, printername)
[3029]210                    return (vac, args)
211            raise PyKotaConfigError, _("Option preaccounter in section %s only supports values in %s") % (printername, str(validaccounters))
[2635]212       
[1192]213    def getAccounterBackend(self, printername) :   
[2635]214        """Returns the accounter backend to use for a given printer."""
[3034]215        validaccounters = [ "hardware", "software", "ink" ]     
[3029]216        try :
217            fullaccounter = self.getPrinterOption(printername, "accounter").strip()
218        except PyKotaConfigError :   
219            return ("software", "")
220        else :   
221            flower = fullaccounter.lower()
222            for vac in validaccounters :
223                if flower.startswith(vac) :   
224                    try :
225                        (accounter, args) = [x.strip() for x in fullaccounter.split('(', 1)]
226                    except ValueError :   
227                        raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
228                    if args.endswith(')') :
229                        args = args[:-1].strip()
[3034]230                    if (vac in ("hardware", "ink")) and not args :
[3029]231                        raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
232                    return (vac, args)
[1192]233            raise PyKotaConfigError, _("Option accounter in section %s only supports values in %s") % (printername, str(validaccounters))
[973]234       
[1371]235    def getPreHook(self, printername) :   
236        """Returns the prehook command line to launch, or None if unset."""
237        try :
238            return self.getPrinterOption(printername, "prehook").strip()
239        except PyKotaConfigError :   
240            return      # No command to launch in the pre-hook
241           
242    def getPostHook(self, printername) :   
243        """Returns the posthook command line to launch, or None if unset."""
244        try :
245            return self.getPrinterOption(printername, "posthook").strip()
246        except PyKotaConfigError :   
247            return      # No command to launch in the post-hook
248           
[2307]249    def getStripTitle(self, printername) :   
250        """Returns the striptitle directive's content, or None if unset."""
251        try :
252            return self.getPrinterOption(printername, "striptitle").strip()
253        except PyKotaConfigError :   
254            return      # No prefix to strip off
255           
[2895]256    def getAskConfirmation(self, printername) :       
257        """Returns the askconfirmation directive's content, or None if unset."""
258        try :
259            return self.getPrinterOption(printername, "askconfirmation").strip()
260        except PyKotaConfigError :   
261            return      # No overwriting will be done
262           
[2385]263    def getOverwriteJobTicket(self, printername) :       
264        """Returns the overwrite_jobticket directive's content, or None if unset."""
265        try :
266            return self.getPrinterOption(printername, "overwrite_jobticket").strip()
267        except PyKotaConfigError :   
268            return      # No overwriting will be done
269       
270    def getUnknownBillingCode(self, printername) :       
271        """Returns the unknown_billingcode directive's content, or the default value if unset."""
272        validvalues = [ "CREATE", "DENY" ]
273        try :
274            fullvalue = self.getPrinterOption(printername, "unknown_billingcode")
275        except PyKotaConfigError :   
276            return ("CREATE", None)
277        else :   
278            try :
279                value = [x.strip() for x in fullvalue.split('(', 1)]
280            except ValueError :   
281                raise PyKotaConfigError, _("Invalid unknown_billingcode directive %s for printer %s") % (fullvalue, printername)
282            if len(value) == 1 :   
283                value.append("")
284            (value, args) = value   
285            if args.endswith(')') :
286                args = args[:-1]
287            value = value.upper()   
288            if (value == "DENY") and not args :
289                return ("DENY", None)
290            if value not in validvalues :
291                raise PyKotaConfigError, _("Directive unknown_billingcode in section %s only supports values in %s") % (printername, str(validvalues))
292            return (value, args)
293       
[1495]294    def getPrinterEnforcement(self, printername) :   
295        """Returns if quota enforcement should be strict or laxist for the current printer."""
296        validenforcements = [ "STRICT", "LAXIST" ]     
297        try :
298            enforcement = self.getPrinterOption(printername, "enforcement")
299        except PyKotaConfigError :   
300            return "LAXIST"
301        else :   
302            enforcement = enforcement.upper()
303            if enforcement not in validenforcements :
304                raise PyKotaConfigError, _("Option enforcement in section %s only supports values in %s") % (printername, str(validenforcements))
305            return enforcement   
306           
[2583]307    def getPrinterOnBackendError(self, printername) :   
308        """Returns what must be done whenever the real CUPS backend fails."""
309        validactions = [ "CHARGE", "NOCHARGE" ]     
310        try :
311            action = self.getPrinterOption(printername, "onbackenderror")
312        except PyKotaConfigError :   
[2759]313            return ["NOCHARGE"]
[2583]314        else :   
[2759]315            action = action.upper().split(",")
316            error = False
317            for act in action :
318                if act not in validactions :
319                    if act.startswith("RETRY:") :
320                        try :
321                            (num, delay) = [int(p) for p in act[6:].split(":", 2)]
322                        except ValueError :   
323                            error = True
324                    else :       
325                        error = True
326            if error :
327                raise PyKotaConfigError, _("Option onbackenderror in section %s only supports values 'charge', 'nocharge', and 'retry:num:delay'") % printername
[2583]328            return action 
329           
[1687]330    def getPrinterOnAccounterError(self, printername) :   
331        """Returns what must be done whenever the accounter fails."""
332        validactions = [ "CONTINUE", "STOP" ]     
333        try :
334            action = self.getPrinterOption(printername, "onaccountererror")
335        except PyKotaConfigError :   
336            return "STOP"
337        else :   
338            action = action.upper()
339            if action not in validactions :
340                raise PyKotaConfigError, _("Option onaccountererror in section %s only supports values in %s") % (printername, str(validactions))
341            return action 
342           
[1192]343    def getPrinterPolicy(self, printername) :   
[695]344        """Returns the default policy for the current printer."""
[1152]345        validpolicies = [ "ALLOW", "DENY", "EXTERNAL" ]     
[853]346        try :
[1192]347            fullpolicy = self.getPrinterOption(printername, "policy")
[853]348        except PyKotaConfigError :   
[1152]349            return ("DENY", None)
350        else :   
351            try :
352                policy = [x.strip() for x in fullpolicy.split('(', 1)]
353            except ValueError :   
[1192]354                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
[1152]355            if len(policy) == 1 :   
356                policy.append("")
357            (policy, args) = policy   
358            if args.endswith(')') :
359                args = args[:-1]
360            policy = policy.upper()   
361            if (policy == "EXTERNAL") and not args :
[1192]362                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
[1152]363            if policy not in validpolicies :
[1192]364                raise PyKotaConfigError, _("Option policy in section %s only supports values in %s") % (printername, str(validpolicies))
[1152]365            return (policy, args)
[695]366       
[1518]367    def getCrashRecipient(self) :   
368        """Returns the email address of the software crash messages recipient."""
369        try :
370            return self.getGlobalOption("crashrecipient")
371        except :   
372            return
373           
[695]374    def getSMTPServer(self) :   
375        """Returns the SMTP server to use to send messages to users."""
[853]376        try :
377            return self.getGlobalOption("smtpserver")
378        except PyKotaConfigError :   
379            return "localhost"
[695]380       
[1353]381    def getMailDomain(self) :   
382        """Returns the mail domain to use to send messages to users."""
383        try :
384            return self.getGlobalOption("maildomain")
385        except PyKotaConfigError :   
386            return 
387       
[1192]388    def getAdminMail(self, printername) :   
[695]389        """Returns the Email address of the Print Quota Administrator."""
[853]390        try :
[1192]391            return self.getPrinterOption(printername, "adminmail")
[853]392        except PyKotaConfigError :   
393            return "root@localhost"
[695]394       
[1192]395    def getAdmin(self, printername) :   
[695]396        """Returns the full name of the Print Quota Administrator."""
[853]397        try :
[1192]398            return self.getPrinterOption(printername, "admin")
[853]399        except PyKotaConfigError :   
400            return "root"
[708]401       
[1192]402    def getMailTo(self, printername) :   
[852]403        """Returns the recipient of email messages."""
[1192]404        validmailtos = [ "EXTERNAL", "NOBODY", "NONE", "NOONE", "BITBUCKET", "DEVNULL", "BOTH", "USER", "ADMIN" ]
[853]405        try :
[1192]406            fullmailto = self.getPrinterOption(printername, "mailto")
[853]407        except PyKotaConfigError :   
[1192]408            return ("BOTH", None)
409        else :   
410            try :
411                mailto = [x.strip() for x in fullmailto.split('(', 1)]
412            except ValueError :   
413                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
414            if len(mailto) == 1 :   
415                mailto.append("")
416            (mailto, args) = mailto   
417            if args.endswith(')') :
418                args = args[:-1]
419            mailto = mailto.upper()   
420            if (mailto == "EXTERNAL") and not args :
421                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
422            if mailto not in validmailtos :
423                raise PyKotaConfigError, _("Option mailto in section %s only supports values in %s") % (printername, str(validmailtos))
424            return (mailto, args)
[852]425       
[2054]426    def getMaxDenyBanners(self, printername) :   
427        """Returns the maximum number of deny banners to be printed for a particular user on a particular printer."""
428        try :
429            maxdb = self.getPrinterOption(printername, "maxdenybanners")
430        except PyKotaConfigError :   
431            return 0 # default value is to forbid printing a deny banner.
432        try :
433            value = int(maxdb.strip())
434            if value < 0 :
435                raise ValueError
436        except (TypeError, ValueError) :   
437            raise PyKotaConfigError, _("Invalid maximal deny banners counter %s") % maxdb
438        else :   
439            return value
[3124]440
441    def getPrintCancelledBanners(self, printername) :
[3126]442        """Returns True if a banner should be printed when a job is cancelled, else False."""
[3124]443        try :
444            return self.isTrue(self.getPrinterOption(printername, "printcancelledbanners"))
445        except PyKotaConfigError :
[3126]446            return True
[3124]447             
[1192]448    def getGraceDelay(self, printername) :   
[708]449        """Returns the grace delay in days."""
[731]450        try :
[1192]451            gd = self.getPrinterOption(printername, "gracedelay")
[853]452        except PyKotaConfigError :   
[1914]453            gd = 7      # default value of 7 days
[853]454        try :
[731]455            return int(gd)
[1077]456        except (TypeError, ValueError) :   
[773]457            raise PyKotaConfigError, _("Invalid grace delay %s") % gd
[1021]458           
[1077]459    def getPoorMan(self) :   
[1646]460        """Returns the poor man's threshold."""
[1077]461        try :
462            pm = self.getGlobalOption("poorman")
463        except PyKotaConfigError :   
[1914]464            pm = 1.0    # default value of 1 unit
[1077]465        try :
466            return float(pm)
467        except (TypeError, ValueError) :   
[1646]468            raise PyKotaConfigError, _("Invalid poor man's threshold %s") % pm
[1077]469           
[2692]470    def getBalanceZero(self) :   
471        """Returns the value of the zero for balance limitation."""
472        try :
473            bz = self.getGlobalOption("balancezero")
474        except PyKotaConfigError :   
475            bz = 0.0    # default value, zero is 0.0
476        try :
477            return float(bz)
478        except (TypeError, ValueError) :   
479            raise PyKotaConfigError, _("Invalid balancezero value %s") % bz
480           
[1077]481    def getPoorWarn(self) :   
482        """Returns the poor man's warning message."""
483        try :
484            return self.getGlobalOption("poorwarn")
485        except PyKotaConfigError :   
486            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.")
487           
[1192]488    def getHardWarn(self, printername) :   
[1077]489        """Returns the hard limit error message."""
490        try :
[1192]491            return self.getPrinterOption(printername, "hardwarn")
[1077]492        except PyKotaConfigError :   
[1192]493            return _("You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s.") % printername
[1077]494           
[1192]495    def getSoftWarn(self, printername) :   
[1077]496        """Returns the soft limit error message."""
497        try :
[1192]498            return self.getPrinterOption(printername, "softwarn")
[1077]499        except PyKotaConfigError :   
[1192]500            return _("You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s.") % printername
[1077]501           
[1875]502    def getPrivacy(self) :       
[3126]503        """Returns True if privacy is activated, else False."""
[3296]504        return self.isTrue(self.getGlobalOption("privacy", ignore=True))
[1875]505       
[1021]506    def getDebug(self) :         
[3126]507        """Returns True if debugging is activated, else False."""
[3296]508        return self.isTrue(self.getGlobalOption("debug", ignore=True))
[1130]509           
510    def getCaching(self) :         
[3126]511        """Returns True if database caching is enabled, else False."""
[3296]512        return self.isTrue(self.getGlobalOption("storagecaching", ignore=True))
[1148]513           
[1356]514    def getLDAPCache(self) :         
[3126]515        """Returns True if low-level LDAP caching is enabled, else False."""
[3296]516        return self.isTrue(self.getGlobalOption("ldapcache", ignore=True))
[1356]517           
[1148]518    def getDisableHistory(self) :         
[3126]519        """Returns True if we want to disable history, else False."""
[3296]520        return self.isTrue(self.getGlobalOption("disablehistory", ignore=True))
[1227]521           
522    def getUserNameToLower(self) :         
[3169]523        """Deprecated."""
[3296]524        return self.getGlobalOption("utolower", ignore=True)
[1757]525       
[3169]526    def getUserNameCase(self) :
527        """Returns value for user name case: upper, lower or native"""
528        validvalues = [ "upper", "lower", "native" ]
[3172]529        try :
[3296]530            value = self.getGlobalOption("usernamecase", ignore=True).strip().lower()
[3172]531        except AttributeError :   
[3169]532            value = "native"
533        if value not in validvalues :
534            raise PyKotaConfigError, _("Option usernamecase only supports values in %s") % str(validvalues)
535        return value
536       
[1956]537    def getRejectUnknown(self) :         
[3126]538        """Returns True if we want to reject the creation of unknown users or groups, else False."""
[3296]539        return self.isTrue(self.getGlobalOption("reject_unknown", ignore=True))
[1956]540       
[2405]541    def getPrinterKeepFiles(self, printername) :         
[3126]542        """Returns True if files must be kept on disk, else False."""
[2405]543        try : 
544            return self.isTrue(self.getPrinterOption(printername, "keepfiles"))
545        except PyKotaConfigError :   
[3126]546            return False
[2405]547           
548    def getPrinterDirectory(self, printername) :         
549        """Returns the path to our working directory, else a directory suitable for temporary files."""
550        try : 
551            return self.getPrinterOption(printername, "directory").strip()
552        except PyKotaConfigError :   
553            return tempfile.gettempdir()
554           
[2066]555    def getDenyDuplicates(self, printername) :         
[3126]556        """Returns True or a command if we want to deny duplicate jobs, else False."""
[2066]557        try : 
[2308]558            denyduplicates = self.getPrinterOption(printername, "denyduplicates")
[2066]559        except PyKotaConfigError :   
[3126]560            return False
[2308]561        else :   
562            if self.isTrue(denyduplicates) :
[3126]563                return True
[2308]564            elif self.isFalse(denyduplicates) :
[3126]565                return False
[2308]566            else :   
567                # it's a command to run.
568                return denyduplicates
[2692]569               
570    def getDuplicatesDelay(self, printername) :         
571        """Returns the number of seconds after which two identical jobs are not considered a duplicate anymore."""
572        try : 
573            duplicatesdelay = self.getPrinterOption(printername, "duplicatesdelay")
574        except PyKotaConfigError :   
575            return 0
576        else :   
577            try :
578                return int(duplicatesdelay)
579            except (TypeError, ValueError) :
580                raise PyKotaConfigError, _("Incorrect value %s for the duplicatesdelay directive in section %s") % (str(duplicatesdelay), printername)
[2066]581       
[3025]582    def getNoPrintingMaxDelay(self, printername) :         
583        """Returns the max number of seconds to wait for the printer to be in 'printing' mode."""
584        try : 
585            maxdelay = self.getPrinterOption(printername, "noprintingmaxdelay")
586        except PyKotaConfigError :   
587            return None         # tells to use hardcoded value
588        else :   
589            try :
590                maxdelay = int(maxdelay)
591                if maxdelay < 0 :
592                    raise ValueError
593            except (TypeError, ValueError) :
594                raise PyKotaConfigError, _("Incorrect value %s for the noprintingmaxdelay directive in section %s") % (str(maxdelay), printername)
595            else :   
596                return maxdelay
597       
[3180]598    def getStatusStabilizationLoops(self, printername) :   
599        """Returns the number of times the printer must return the 'idle' status to consider it stable."""
600        try : 
601            stab = self.getPrinterOption(printername, "statusstabilizationloops")
602        except PyKotaConfigError :   
603            return None         # tells to use hardcoded value
604        else :   
605            try :
606                stab = int(stab)
607                if stab < 1 :
608                    raise ValueError
609            except (TypeError, ValueError) :
610                raise PyKotaConfigError, _("Incorrect value %s for the statusstabilizationloops directive in section %s") % (str(stab), printername)
611            else :   
612                return stab
613       
614    def getStatusStabilizationDelay(self, printername) :   
615        """Returns the number of seconds to wait between two checks of the printer's status."""
616        try : 
617            stab = self.getPrinterOption(printername, "statusstabilizationdelay")
618        except PyKotaConfigError :   
619            return None         # tells to use hardcoded value
620        else :   
621            try :
622                stab = float(stab)
623                if stab < 0.25 :
624                    raise ValueError
625            except (TypeError, ValueError) :
626                raise PyKotaConfigError, _("Incorrect value %s for the statusstabilizationdelay directive in section %s") % (str(stab), printername)
627            else :   
628                return stab
629       
[3190]630    def getPrinterSNMPErrorMask(self, printername) :   
631        """Returns the SNMP error mask for a particular printer, or None if not defined."""
632        try : 
633            errmask = self.getPrinterOption(printername, "snmperrormask").lower()
634        except PyKotaConfigError :   
635            return None         # tells to use hardcoded value
636        else :   
637            try :
638                if errmask.startswith("0x") :
639                    value = int(errmask, 16)
640                elif errmask.startswith("0") :   
641                    value = int(errmask, 8)
642                else :   
643                    value = int(errmask)
644                if 0 <= value < 65536 :
645                    return value
646                else :   
647                    raise ValueError
648            except ValueError :   
649                raise PyKotaConfigError, _("Incorrect value %s for the snmperrormask directive in section %s") % (errmask, printername)
650       
[1757]651    def getWinbindSeparator(self) :         
652        """Returns the winbind separator's value if it is set, else None."""
[3296]653        return self.getGlobalOption("winbind_separator", ignore=True)
[1914]654
655    def getAccountBanner(self, printername) :
656        """Returns which banner(s) to account for: NONE, BOTH, STARTING, ENDING."""
657        validvalues = [ "NONE", "BOTH", "STARTING", "ENDING" ]     
658        try :
659            value = self.getPrinterOption(printername, "accountbanner")
660        except PyKotaConfigError :   
661            return "BOTH"       # Default value of BOTH
662        else :   
[1916]663            value = value.strip().upper()
[1914]664            if value not in validvalues :
[1916]665                raise PyKotaConfigError, _("Option accountbanner in section %s only supports values in %s") % (printername, str(validvalues))
[1914]666            return value 
667
[3158]668    def getAvoidDuplicateBanners(self, printername) :
669        """Returns normalized value for avoiding extra banners. """
670        try :
671            avoidduplicatebanners = self.getPrinterOption(printername, "avoidduplicatebanners").upper()
672        except PyKotaConfigError :
673            return "NO"
674        else :
675            try :
676                value = int(avoidduplicatebanners)
677                if value < 0 :
678                    raise ValueError
679            except ValueError :
680                if avoidduplicatebanners not in ["YES", "NO"] :
681                    raise PyKotaConfigError, _("Option avoidduplicatebanners only accepts 'yes', 'no', or a positive integer.")
682                else :
683                    value = avoidduplicatebanners
684            return value
685
[1914]686    def getStartingBanner(self, printername) :
687        """Returns the startingbanner value if set, else None."""
688        try :
[1916]689            return self.getPrinterOption(printername, "startingbanner").strip()
[1914]690        except PyKotaConfigError :
691            return None
692
693    def getEndingBanner(self, printername) :
694        """Returns the endingbanner value if set, else None."""
695        try :
[1916]696            return self.getPrinterOption(printername, "endingbanner").strip()
[1914]697        except PyKotaConfigError :
698            return None
[2062]699           
700    def getTrustJobSize(self, printername) :
701        """Returns the normalized value of the trustjobsize's directive."""
702        try :
703            value = self.getPrinterOption(printername, "trustjobsize").strip().upper()
704        except PyKotaConfigError :
705            return (None, "YES")
706        else :   
707            if value == "YES" :
708                return (None, "YES")
709            try :   
710                (limit, replacement) = [p.strip() for p in value.split(">")[1].split(":")]
711                limit = int(limit)
712                try :
713                    replacement = int(replacement) 
714                except ValueError :   
715                    if replacement != "PRECOMPUTED" :
716                        raise
717                if limit < 0 :
718                    raise ValueError
719                if (replacement != "PRECOMPUTED") and (replacement < 0) :
720                    raise ValueError
721            except (IndexError, ValueError, TypeError) :
722                raise PyKotaConfigError, _("Option trustjobsize for printer %s is incorrect") % printername
723            return (limit, replacement)   
[3031]724           
725    def getPrinterCoefficients(self, printername) :
726        """Returns a mapping of coefficients for a particular printer."""
727        branchbasename = "coefficient_"
728        try :
[3296]729            globalbranches = [ (k, self.config.get("global", k).decode(self.config_charset)) for k in self.config.options("global") if k.startswith(branchbasename) ]
[3031]730        except ConfigParser.NoSectionError, msg :
731            raise PyKotaConfigError, "Invalid configuration file : %s" % msg
732        try :
[3296]733            sectionbranches = [ (k, self.config.get(printername, k).decode(self.config_charset)) for k in self.config.options(printername) if k.startswith(branchbasename) ]
[3031]734        except ConfigParser.NoSectionError, msg :
735            sectionbranches = []
736        branches = {}
737        for (k, v) in globalbranches :
[3035]738            k = k.split('_', 1)[1]
[3031]739            value = v.strip()
740            if value :
741                try :
742                    branches[k] = float(value)
743                except ValueError :   
744                    raise PyKotaConfigError, "Invalid coefficient %s (%s) for printer %s" % (k, value, printername)
745               
746        for (k, v) in sectionbranches :
[3035]747            k = k.split('_', 1)[1]
[3031]748            value = v.strip()
749            if value :
750                try :
751                    branches[k] = float(value) # overwrite any global option or set a new value
752                except ValueError :   
753                    raise PyKotaConfigError, "Invalid coefficient %s (%s) for printer %s" % (k, value, printername)
754            else :
755                del branches[k] # empty value disables a global option
756        return branches
[3162]757       
758    def getPrinterSkipInitialWait(self, printername) :
759        """Returns True if we want to skip the initial waiting loop, else False."""
760        try :
761            return self.isTrue(self.getPrinterOption(printername, "skipinitialwait"))
762        except PyKotaConfigError :
763            return False
Note: See TracBrowser for help on using the browser.