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

Revision 3029, 29.2 kB (checked in by jerome, 18 years ago)

Make the configuration file parser recognize the 'bw', 'cmyk', 'cmy', and 'rgb'
preaccounter and accounter directives.

  • 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 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
25import os
26import tempfile
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."""
42        self.isAdmin = 0
43        self.directory = directory
44        self.filename = os.path.join(directory, "pykota.conf")
45        self.adminfilename = os.path.join(directory, "pykotadmin.conf")
46        if not os.access(self.filename, os.R_OK) :
47            raise PyKotaConfigError, _("Configuration file %s can't be read. Please check that the file exists and that your permissions are sufficient.") % self.filename
48        if not os.path.isfile(self.adminfilename) :
49            raise PyKotaConfigError, _("Configuration file %s not found.") % self.adminfilename
50        if os.access(self.adminfilename, os.R_OK) :   
51            self.isAdmin = 1
52        self.config = ConfigParser.ConfigParser()
53        self.config.read([self.filename])
54           
55    def isTrue(self, option) :       
56        """Returns 1 if option is set to true, else 0."""
57        if (option is not None) and (option.strip().upper() in ['Y', 'YES', '1', 'ON', 'T', 'TRUE']) :
58            return 1
59        else :   
60            return 0
61                       
62    def isFalse(self, option) :       
63        """Returns 1 if option is set to false, else 0."""
64        if (option is not None) and (option.strip().upper() in ['N', 'NO', '0', 'OFF', 'F', 'FALSE']) :
65            return 1
66        else :   
67            return 0
68                       
69    def getPrinterNames(self) :   
70        """Returns the list of configured printers, i.e. all sections names minus 'global'."""
71        return [pname for pname in self.config.sections() if pname != "global"]
72       
73    def getGlobalOption(self, option, ignore=0) :   
74        """Returns an option from the global section, or raises a PyKotaConfigError if ignore is not set, else returns None."""
75        try :
76            return self.config.get("global", option, raw=1)
77        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
78            if ignore :
79                return
80            else :
81                raise PyKotaConfigError, _("Option %s not found in section global of %s") % (option, self.filename)
82               
83    def getPrinterOption(self, printername, option) :   
84        """Returns an option from the printer section, or the global section, or raises a PyKotaConfigError."""
85        globaloption = self.getGlobalOption(option, ignore=1)
86        try :
87            return self.config.get(printername, option, raw=1)
88        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
89            if globaloption is not None :
90                return globaloption
91            else :
92                raise PyKotaConfigError, _("Option %s not found in section %s of %s") % (option, printername, self.filename)
93       
94    def getStorageBackend(self) :   
95        """Returns the storage backend information as a Python mapping."""       
96        backendinfo = {}
97        backend = self.getGlobalOption("storagebackend").lower()
98        backendinfo["storagebackend"] = backend
99        if backend == "sqlitestorage" :
100            issqlite = 1
101            backendinfo["storagename"] = self.getGlobalOption("storagename")
102            for option in ["storageserver", "storageuser", "storageuserpw"] :
103                backendinfo[option] = None         
104        else :
105            issqlite = 0
106            for option in ["storageserver", "storagename", "storageuser"] :
107                backendinfo[option] = self.getGlobalOption(option)
108            backendinfo["storageuserpw"] = self.getGlobalOption("storageuserpw", ignore=1)  # password is optional
109           
110        backendinfo["storageadmin"] = None
111        backendinfo["storageadminpw"] = None
112        if self.isAdmin :
113            adminconf = ConfigParser.ConfigParser()
114            adminconf.read([self.adminfilename])
115            if adminconf.sections() : # were we able to read the file ?
116                try :
117                    backendinfo["storageadmin"] = adminconf.get("global", "storageadmin", raw=1)
118                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
119                    if not issqlite :
120                        raise PyKotaConfigError, _("Option %s not found in section global of %s") % ("storageadmin", self.adminfilename)
121                try :
122                    backendinfo["storageadminpw"] = adminconf.get("global", "storageadminpw", raw=1)
123                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
124                    pass # Password is optional
125                # Now try to overwrite the storagebackend, storageserver
126                # and storagename. This allows admins to use the master LDAP
127                # server directly and users to use the replicas transparently.
128                try :
129                    backendinfo["storagebackend"] = adminconf.get("global", "storagebackend", raw=1)
130                except ConfigParser.NoOptionError :
131                    pass
132                try :
133                    backendinfo["storageserver"] = adminconf.get("global", "storageserver", raw=1)
134                except ConfigParser.NoOptionError :
135                    pass
136                try :
137                    backendinfo["storagename"] = adminconf.get("global", "storagename", raw=1)
138                except ConfigParser.NoOptionError :
139                    pass
140        return backendinfo
141       
142    def getLDAPInfo(self) :   
143        """Returns some hints for the LDAP backend."""       
144        ldapinfo = {}
145        for option in [ "userbase", "userrdn", \
146                        "balancebase", "balancerdn", \
147                        "groupbase", "grouprdn", "groupmembers", \
148                        "printerbase", "printerrdn", \
149                        "userquotabase", "groupquotabase", \
150                        "jobbase", "lastjobbase", "billingcodebase", \
151                        "newuser", "newgroup", \
152                        "usermail", \
153                      ] :
154            ldapinfo[option] = self.getGlobalOption(option).strip()
155        for field in ["newuser", "newgroup"] :
156            if ldapinfo[field].lower().startswith('attach(') :
157                ldapinfo[field] = ldapinfo[field][7:-1]
158               
159        # should we use TLS, by default (if unset) value is NO       
160        ldapinfo["ldaptls"] = self.isTrue(self.getGlobalOption("ldaptls", ignore=1))
161        ldapinfo["cacert"] = self.getGlobalOption("cacert", ignore=1)
162        if ldapinfo["cacert"] :
163            ldapinfo["cacert"] = ldapinfo["cacert"].strip()
164        if ldapinfo["ldaptls"] :   
165            if not os.access(ldapinfo["cacert"] or "", os.R_OK) :
166                raise PyKotaConfigError, _("Option ldaptls is set, but certificate %s is not readable.") % str(ldapinfo["cacert"])
167        return ldapinfo
168       
169    def getLoggingBackend(self) :   
170        """Returns the logging backend information."""
171        validloggers = [ "stderr", "system" ] 
172        try :
173            logger = self.getGlobalOption("logger").lower()
174        except PyKotaConfigError :   
175            logger = "system"
176        if logger not in validloggers :             
177            raise PyKotaConfigError, _("Option logger only supports values in %s") % str(validloggers)
178        return logger   
179       
180    def getLogoURL(self) :
181        """Returns the URL to use for the logo in the CGI scripts."""
182        url = self.getGlobalOption("logourl", ignore=1) or \
183                   "http://www.pykota.com/pykota.png"
184        return url.strip()           
185       
186    def getLogoLink(self) :
187        """Returns the URL to go to when the user clicks on the logo in the CGI scripts."""
188        url = self.getGlobalOption("logolink", ignore=1) or \
189                   "http://www.pykota.com/"
190        return url.strip()           
191   
192    def getPreAccounterBackend(self, printername) :   
193        """Returns the preaccounter backend to use for a given printer."""
194        validaccounters = [ "software", "bw", "cmyk", "cmy", "rgb" ]     
195        try :
196            fullaccounter = self.getPrinterOption(printername, "preaccounter").strip()
197        except PyKotaConfigError :   
198            return ("software", "")
199        else :   
200            flower = fullaccounter.lower()
201            for vac in validaccounters :
202                if flower.startswith(vac) :   
203                    try :
204                        (accounter, args) = [x.strip() for x in fullaccounter.split('(', 1)]
205                    except ValueError :   
206                        raise PyKotaConfigError, _("Invalid preaccounter %s for printer %s") % (fullaccounter, printername)
207                    if args.endswith(')') :
208                        args = args[:-1].strip()
209                    return (vac, args)
210            raise PyKotaConfigError, _("Option preaccounter in section %s only supports values in %s") % (printername, str(validaccounters))
211       
212    def getAccounterBackend(self, printername) :   
213        """Returns the accounter backend to use for a given printer."""
214        validaccounters = [ "hardware", "software", "bw", "cmyk", "cmy", "rgb" ]     
215        try :
216            fullaccounter = self.getPrinterOption(printername, "accounter").strip()
217        except PyKotaConfigError :   
218            return ("software", "")
219        else :   
220            flower = fullaccounter.lower()
221            for vac in validaccounters :
222                if flower.startswith(vac) :   
223                    try :
224                        (accounter, args) = [x.strip() for x in fullaccounter.split('(', 1)]
225                    except ValueError :   
226                        raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
227                    if args.endswith(')') :
228                        args = args[:-1].strip()
229                    if (accounter == "hardware") and not args :
230                        raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
231                    return (vac, args)
232            raise PyKotaConfigError, _("Option accounter in section %s only supports values in %s") % (printername, str(validaccounters))
233       
234    def getPreHook(self, printername) :   
235        """Returns the prehook command line to launch, or None if unset."""
236        try :
237            return self.getPrinterOption(printername, "prehook").strip()
238        except PyKotaConfigError :   
239            return      # No command to launch in the pre-hook
240           
241    def getPostHook(self, printername) :   
242        """Returns the posthook command line to launch, or None if unset."""
243        try :
244            return self.getPrinterOption(printername, "posthook").strip()
245        except PyKotaConfigError :   
246            return      # No command to launch in the post-hook
247           
248    def getStripTitle(self, printername) :   
249        """Returns the striptitle directive's content, or None if unset."""
250        try :
251            return self.getPrinterOption(printername, "striptitle").strip()
252        except PyKotaConfigError :   
253            return      # No prefix to strip off
254           
255    def getAskConfirmation(self, printername) :       
256        """Returns the askconfirmation directive's content, or None if unset."""
257        try :
258            return self.getPrinterOption(printername, "askconfirmation").strip()
259        except PyKotaConfigError :   
260            return      # No overwriting will be done
261           
262    def getOverwriteJobTicket(self, printername) :       
263        """Returns the overwrite_jobticket directive's content, or None if unset."""
264        try :
265            return self.getPrinterOption(printername, "overwrite_jobticket").strip()
266        except PyKotaConfigError :   
267            return      # No overwriting will be done
268       
269    def getUnknownBillingCode(self, printername) :       
270        """Returns the unknown_billingcode directive's content, or the default value if unset."""
271        validvalues = [ "CREATE", "DENY" ]
272        try :
273            fullvalue = self.getPrinterOption(printername, "unknown_billingcode")
274        except PyKotaConfigError :   
275            return ("CREATE", None)
276        else :   
277            try :
278                value = [x.strip() for x in fullvalue.split('(', 1)]
279            except ValueError :   
280                raise PyKotaConfigError, _("Invalid unknown_billingcode directive %s for printer %s") % (fullvalue, printername)
281            if len(value) == 1 :   
282                value.append("")
283            (value, args) = value   
284            if args.endswith(')') :
285                args = args[:-1]
286            value = value.upper()   
287            if (value == "DENY") and not args :
288                return ("DENY", None)
289            if value not in validvalues :
290                raise PyKotaConfigError, _("Directive unknown_billingcode in section %s only supports values in %s") % (printername, str(validvalues))
291            return (value, args)
292       
293    def getPrinterEnforcement(self, printername) :   
294        """Returns if quota enforcement should be strict or laxist for the current printer."""
295        validenforcements = [ "STRICT", "LAXIST" ]     
296        try :
297            enforcement = self.getPrinterOption(printername, "enforcement")
298        except PyKotaConfigError :   
299            return "LAXIST"
300        else :   
301            enforcement = enforcement.upper()
302            if enforcement not in validenforcements :
303                raise PyKotaConfigError, _("Option enforcement in section %s only supports values in %s") % (printername, str(validenforcements))
304            return enforcement   
305           
306    def getPrinterOnBackendError(self, printername) :   
307        """Returns what must be done whenever the real CUPS backend fails."""
308        validactions = [ "CHARGE", "NOCHARGE" ]     
309        try :
310            action = self.getPrinterOption(printername, "onbackenderror")
311        except PyKotaConfigError :   
312            return ["NOCHARGE"]
313        else :   
314            action = action.upper().split(",")
315            error = False
316            for act in action :
317                if act not in validactions :
318                    if act.startswith("RETRY:") :
319                        try :
320                            (num, delay) = [int(p) for p in act[6:].split(":", 2)]
321                        except ValueError :   
322                            error = True
323                    else :       
324                        error = True
325            if error :
326                raise PyKotaConfigError, _("Option onbackenderror in section %s only supports values 'charge', 'nocharge', and 'retry:num:delay'") % printername
327            return action 
328           
329    def getPrinterOnAccounterError(self, printername) :   
330        """Returns what must be done whenever the accounter fails."""
331        validactions = [ "CONTINUE", "STOP" ]     
332        try :
333            action = self.getPrinterOption(printername, "onaccountererror")
334        except PyKotaConfigError :   
335            return "STOP"
336        else :   
337            action = action.upper()
338            if action not in validactions :
339                raise PyKotaConfigError, _("Option onaccountererror in section %s only supports values in %s") % (printername, str(validactions))
340            return action 
341           
342    def getPrinterPolicy(self, printername) :   
343        """Returns the default policy for the current printer."""
344        validpolicies = [ "ALLOW", "DENY", "EXTERNAL" ]     
345        try :
346            fullpolicy = self.getPrinterOption(printername, "policy")
347        except PyKotaConfigError :   
348            return ("DENY", None)
349        else :   
350            try :
351                policy = [x.strip() for x in fullpolicy.split('(', 1)]
352            except ValueError :   
353                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
354            if len(policy) == 1 :   
355                policy.append("")
356            (policy, args) = policy   
357            if args.endswith(')') :
358                args = args[:-1]
359            policy = policy.upper()   
360            if (policy == "EXTERNAL") and not args :
361                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
362            if policy not in validpolicies :
363                raise PyKotaConfigError, _("Option policy in section %s only supports values in %s") % (printername, str(validpolicies))
364            return (policy, args)
365       
366    def getCrashRecipient(self) :   
367        """Returns the email address of the software crash messages recipient."""
368        try :
369            return self.getGlobalOption("crashrecipient")
370        except :   
371            return
372           
373    def getSMTPServer(self) :   
374        """Returns the SMTP server to use to send messages to users."""
375        try :
376            return self.getGlobalOption("smtpserver")
377        except PyKotaConfigError :   
378            return "localhost"
379       
380    def getMailDomain(self) :   
381        """Returns the mail domain to use to send messages to users."""
382        try :
383            return self.getGlobalOption("maildomain")
384        except PyKotaConfigError :   
385            return 
386       
387    def getAdminMail(self, printername) :   
388        """Returns the Email address of the Print Quota Administrator."""
389        try :
390            return self.getPrinterOption(printername, "adminmail")
391        except PyKotaConfigError :   
392            return "root@localhost"
393       
394    def getAdmin(self, printername) :   
395        """Returns the full name of the Print Quota Administrator."""
396        try :
397            return self.getPrinterOption(printername, "admin")
398        except PyKotaConfigError :   
399            return "root"
400       
401    def getMailTo(self, printername) :   
402        """Returns the recipient of email messages."""
403        validmailtos = [ "EXTERNAL", "NOBODY", "NONE", "NOONE", "BITBUCKET", "DEVNULL", "BOTH", "USER", "ADMIN" ]
404        try :
405            fullmailto = self.getPrinterOption(printername, "mailto")
406        except PyKotaConfigError :   
407            return ("BOTH", None)
408        else :   
409            try :
410                mailto = [x.strip() for x in fullmailto.split('(', 1)]
411            except ValueError :   
412                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
413            if len(mailto) == 1 :   
414                mailto.append("")
415            (mailto, args) = mailto   
416            if args.endswith(')') :
417                args = args[:-1]
418            mailto = mailto.upper()   
419            if (mailto == "EXTERNAL") and not args :
420                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
421            if mailto not in validmailtos :
422                raise PyKotaConfigError, _("Option mailto in section %s only supports values in %s") % (printername, str(validmailtos))
423            return (mailto, args)
424       
425    def getMaxDenyBanners(self, printername) :   
426        """Returns the maximum number of deny banners to be printed for a particular user on a particular printer."""
427        try :
428            maxdb = self.getPrinterOption(printername, "maxdenybanners")
429        except PyKotaConfigError :   
430            return 0 # default value is to forbid printing a deny banner.
431        try :
432            value = int(maxdb.strip())
433            if value < 0 :
434                raise ValueError
435        except (TypeError, ValueError) :   
436            raise PyKotaConfigError, _("Invalid maximal deny banners counter %s") % maxdb
437        else :   
438            return value
439           
440    def getGraceDelay(self, printername) :   
441        """Returns the grace delay in days."""
442        try :
443            gd = self.getPrinterOption(printername, "gracedelay")
444        except PyKotaConfigError :   
445            gd = 7      # default value of 7 days
446        try :
447            return int(gd)
448        except (TypeError, ValueError) :   
449            raise PyKotaConfigError, _("Invalid grace delay %s") % gd
450           
451    def getPoorMan(self) :   
452        """Returns the poor man's threshold."""
453        try :
454            pm = self.getGlobalOption("poorman")
455        except PyKotaConfigError :   
456            pm = 1.0    # default value of 1 unit
457        try :
458            return float(pm)
459        except (TypeError, ValueError) :   
460            raise PyKotaConfigError, _("Invalid poor man's threshold %s") % pm
461           
462    def getBalanceZero(self) :   
463        """Returns the value of the zero for balance limitation."""
464        try :
465            bz = self.getGlobalOption("balancezero")
466        except PyKotaConfigError :   
467            bz = 0.0    # default value, zero is 0.0
468        try :
469            return float(bz)
470        except (TypeError, ValueError) :   
471            raise PyKotaConfigError, _("Invalid balancezero value %s") % bz
472           
473    def getPoorWarn(self) :   
474        """Returns the poor man's warning message."""
475        try :
476            return self.getGlobalOption("poorwarn")
477        except PyKotaConfigError :   
478            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.")
479           
480    def getHardWarn(self, printername) :   
481        """Returns the hard limit error message."""
482        try :
483            return self.getPrinterOption(printername, "hardwarn")
484        except PyKotaConfigError :   
485            return _("You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s.") % printername
486           
487    def getSoftWarn(self, printername) :   
488        """Returns the soft limit error message."""
489        try :
490            return self.getPrinterOption(printername, "softwarn")
491        except PyKotaConfigError :   
492            return _("You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s.") % printername
493           
494    def getPrivacy(self) :       
495        """Returns 1 if privacy is activated, else 0."""
496        return self.isTrue(self.getGlobalOption("privacy", ignore=1))
497       
498    def getDebug(self) :         
499        """Returns 1 if debugging is activated, else 0."""
500        return self.isTrue(self.getGlobalOption("debug", ignore=1))
501           
502    def getCaching(self) :         
503        """Returns 1 if database caching is enabled, else 0."""
504        return self.isTrue(self.getGlobalOption("storagecaching", ignore=1))
505           
506    def getLDAPCache(self) :         
507        """Returns 1 if low-level LDAP caching is enabled, else 0."""
508        return self.isTrue(self.getGlobalOption("ldapcache", ignore=1))
509           
510    def getDisableHistory(self) :         
511        """Returns 1 if we want to disable history, else 0."""
512        return self.isTrue(self.getGlobalOption("disablehistory", ignore=1))
513           
514    def getUserNameToLower(self) :         
515        """Returns 1 if we want to convert usernames to lowercase when printing, else 0."""
516        return self.isTrue(self.getGlobalOption("utolower", ignore=1))
517       
518    def getRejectUnknown(self) :         
519        """Returns 1 if we want to reject the creation of unknown users or groups, else 0."""
520        return self.isTrue(self.getGlobalOption("reject_unknown", ignore=1))
521       
522    def getPrinterKeepFiles(self, printername) :         
523        """Returns 1 if files must be kept on disk, else 0."""
524        try : 
525            return self.isTrue(self.getPrinterOption(printername, "keepfiles"))
526        except PyKotaConfigError :   
527            return 0
528           
529    def getPrinterDirectory(self, printername) :         
530        """Returns the path to our working directory, else a directory suitable for temporary files."""
531        try : 
532            return self.getPrinterOption(printername, "directory").strip()
533        except PyKotaConfigError :   
534            return tempfile.gettempdir()
535           
536    def getDenyDuplicates(self, printername) :         
537        """Returns 1 or a command if we want to deny duplicate jobs, else 0."""
538        try : 
539            denyduplicates = self.getPrinterOption(printername, "denyduplicates")
540        except PyKotaConfigError :   
541            return 0
542        else :   
543            if self.isTrue(denyduplicates) :
544                return 1
545            elif self.isFalse(denyduplicates) :
546                return 0
547            else :   
548                # it's a command to run.
549                return denyduplicates
550               
551    def getDuplicatesDelay(self, printername) :         
552        """Returns the number of seconds after which two identical jobs are not considered a duplicate anymore."""
553        try : 
554            duplicatesdelay = self.getPrinterOption(printername, "duplicatesdelay")
555        except PyKotaConfigError :   
556            return 0
557        else :   
558            try :
559                return int(duplicatesdelay)
560            except (TypeError, ValueError) :
561                raise PyKotaConfigError, _("Incorrect value %s for the duplicatesdelay directive in section %s") % (str(duplicatesdelay), printername)
562       
563    def getNoPrintingMaxDelay(self, printername) :         
564        """Returns the max number of seconds to wait for the printer to be in 'printing' mode."""
565        try : 
566            maxdelay = self.getPrinterOption(printername, "noprintingmaxdelay")
567        except PyKotaConfigError :   
568            return None         # tells to use hardcoded value
569        else :   
570            try :
571                maxdelay = int(maxdelay)
572                if maxdelay < 0 :
573                    raise ValueError
574            except (TypeError, ValueError) :
575                raise PyKotaConfigError, _("Incorrect value %s for the noprintingmaxdelay directive in section %s") % (str(maxdelay), printername)
576            else :   
577                return maxdelay
578       
579    def getWinbindSeparator(self) :         
580        """Returns the winbind separator's value if it is set, else None."""
581        return self.getGlobalOption("winbind_separator", ignore=1)
582
583    def getAccountBanner(self, printername) :
584        """Returns which banner(s) to account for: NONE, BOTH, STARTING, ENDING."""
585        validvalues = [ "NONE", "BOTH", "STARTING", "ENDING" ]     
586        try :
587            value = self.getPrinterOption(printername, "accountbanner")
588        except PyKotaConfigError :   
589            return "BOTH"       # Default value of BOTH
590        else :   
591            value = value.strip().upper()
592            if value not in validvalues :
593                raise PyKotaConfigError, _("Option accountbanner in section %s only supports values in %s") % (printername, str(validvalues))
594            return value 
595
596    def getStartingBanner(self, printername) :
597        """Returns the startingbanner value if set, else None."""
598        try :
599            return self.getPrinterOption(printername, "startingbanner").strip()
600        except PyKotaConfigError :
601            return None
602
603    def getEndingBanner(self, printername) :
604        """Returns the endingbanner value if set, else None."""
605        try :
606            return self.getPrinterOption(printername, "endingbanner").strip()
607        except PyKotaConfigError :
608            return None
609           
610    def getTrustJobSize(self, printername) :
611        """Returns the normalized value of the trustjobsize's directive."""
612        try :
613            value = self.getPrinterOption(printername, "trustjobsize").strip().upper()
614        except PyKotaConfigError :
615            return (None, "YES")
616        else :   
617            if value == "YES" :
618                return (None, "YES")
619            try :   
620                (limit, replacement) = [p.strip() for p in value.split(">")[1].split(":")]
621                limit = int(limit)
622                try :
623                    replacement = int(replacement) 
624                except ValueError :   
625                    if replacement != "PRECOMPUTED" :
626                        raise
627                if limit < 0 :
628                    raise ValueError
629                if (replacement != "PRECOMPUTED") and (replacement < 0) :
630                    raise ValueError
631            except (IndexError, ValueError, TypeError) :
632                raise PyKotaConfigError, _("Option trustjobsize for printer %s is incorrect") % printername
633            return (limit, replacement)   
Note: See TracBrowser for help on using the browser.