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

Revision 2385, 22.8 kB (checked in by jerome, 19 years ago)

Added two new directives :

unknown_billingcode : defines what to do when printing if the billing code

used is not present in the database.

overwrite_jobticket : defines a command to launch when overwriting the username

or the billing code used is desirable (for example when
an user interaction should take place, see the work
of George Farris)

Severity : no support for this in the backend right now, so be patient (again).

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