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

Revision 3190, 35.3 kB (checked in by jerome, 17 years ago)

Added the 'snmperrormask' directive.

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