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