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

Revision 2422, 24.6 kB (checked in by jerome, 19 years ago)

removed some whitespace

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